<template>
  <LabelBox
    :label="formItems.attrs?.label"
    :need-star="formItems.attrs?.needStar"
    :width="formItems.attrs?.width"
  >
    <el-select
      v-model="value"
      size="mini"
      :placeholder="formItems.attrs?.placeholder || '请选择'"
      :clearable="formItems.clearable || true"
      :filterable="formItems.attrs?.filterable || true"
      v-bind="formItems.attrs"
      popper-class="lazy-load-select"
      remote
      :loading="loading"
      :remote-method="remoteMethod"
      v-on="formItems.events"
      @change="handleChange"
      @visible-change="handleVisibleChange"
    >
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item[formItems.attrs?.optionLabel]||item.label"
        :value="item[formItems.attrs?.optionValue]||item.value"
      />
      <!-- 加载状态提示 -->
      <!-- <div
        v-if="loading"
        class="load-more-tip"
      >
        <i class="el-icon-loading" /> 加载中...
      </div>
      <div
        v-if="noMore"
        class="no-more-tip"
      >没有更多数据了</div> -->
    </el-select>
  </LabelBox>
</template>

<script>
import LabelBox from '../labelBox/index.vue';
export default {
  components: {
    LabelBox,
  },
  props: {
    /**
     * api this.$apis.接口名  接口
     * params {}  传参
     * optionLabel string  下拉展示label
     * optionValue string  下拉选中值
     */
    formItems: {
      type: Object,
      default: () => { },
    },
    value: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      loading: false,
      // loadingMore: false, //加载更多状态
      noMore: false, // 是否没有更多数据
      total: 0,
      scrollEl: null, // 保存滚动元素引用
      options: [],
    };
  },

  watch: {
    formItems(newval) {
      // this.formItems = newval;
    },
  },
  mounted() {
    this.getSelectData();
  },
  beforeDestroy() {
    // 关键点5：组件销毁前移除监听
    if (this.scrollEl) {
      this.scrollEl.removeEventListener('scroll', this.handleScroll);
    }
  },
  methods: {
    handleChange(val) {
      this.$emit('input', val);
      this.$emit('outOperation', val);
    },
    // 下拉框显示/隐藏状态变化
    handleVisibleChange(visible) {
      if (visible) {
        this.$nextTick(() => {
          // 关键点2：获取下拉框滚动元素
          this.scrollEl = document.querySelector(
            '.lazy-load-select .el-select-dropdown__wrap',
          );
          if (this.scrollEl) {
            this.scrollEl.addEventListener('scroll', this.handleScroll);
          }
        });
      } else if (this.scrollEl) {
        // 移除监听
        this.scrollEl.removeEventListener('scroll', this.handleScroll);
        this.scrollEl = null;
      }
    },

    // 滚动事件处理
    handleScroll() {
      if (!this.scrollEl) return;

      const { scrollTop, scrollHeight, clientHeight } = this.scrollEl;
      const threshold = 50; // 距离底部阈值(px)

      // 关键点3：判断是否滚动到底部
      if (scrollHeight - (scrollTop + clientHeight) < threshold) {
        this.loadMoreData();
      }
    },
    // 加载更多数据
    async loadMoreData() {
      if (this.loading || this.noMore) { return; }
      this.searchParams.pageStart++;
      this.getSelectData(this.searchParams);
    },
    async getSelectData(params, isSearch) {
      let sParams = {};
      if (params) {
        sParams = { ...params };
      } else {
        this.searchParams = {
          pageStart: 1,
          pageLimit: 10,
          ...this.formItems.attrs.params,
        };
        sParams = { ...this.searchParams };
      }
      this.loading = true;
      const res = await this.formItems.attrs.api(sParams);

      this.loading = false;
      this.options = isSearch ? [...res.data.result.datals] : [...this.options, ...res.data.result.datals];

      this.total = res.data.result.total;
      if (this.options.length === this.total) {
        this.noMore = true;
      }
    },
    remoteMethod(keyword) {
      // if (keyword !== '') {
      //   this.searchParams[this.formItems.attrs?.searchKeyWord || this.formItems.attrs?.optionLabel || 'label'] = keyword;
      //   this.searchParams.pageStart = 1;
      //   this.getSelectData(this.searchParams, true);
      // } else {
      //   this.options = [];
      // }
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep.el-select {
  width: 100%;
  height: 24px;
  line-height: 24px;
}

::v-deep.input-box {
  height: 24px;
}

::v-deep.el-select .el-input__icon {
  height: 24px;
  line-height: 25px;
}

::v-deep.el-select .el-input-group__prepend {
  box-sizing: border-box;
  padding: 0 10px;
  height: 24px;
  line-height: 24px;
  border: none;
}

::v-deep.el-select .el-input__inner {
  height: 24px;
  line-height: 24px;
}
/* 关键点6：自定义下拉框样式 */
::v-deep.lazy-load-select .el-select-dropdown__wrap {
  max-height: 300px; /* 限制下拉框高度 */
}

/* 加载提示样式 */
.load-more-tip,
.no-more-tip {
  padding: 8px 0;
  text-align: center;
  color: #999;
  font-size: 12px;
}

.load-more-tip .el-icon-loading {
  margin-right: 5px;
}
</style>

