<template>
  <span
    :class="{ 'show-red-border-select': showRedBorder === true }"
    style="width: 100%"
  >
    <a-select
      style="width: 100%"
      :value="value || defaultValue"
      :mode="showMultiple ? 'multiple' : 'default'"
      :filter-option="false"
      :show-search="true"
      :allow-clear="true"
      :disabled="disabled"
      :placeholder="$t(placeholder)"
      @popupScroll="handlePopScroll"
      @focus="onFocus"
      @search="handleSearch"
      @change="hansldeChange"
    >
      <div slot="dropdownRender" slot-scope="menu">
        <v-nodes :vnodes="menu" />
        <a-divider v-if="isShowAdd" style="margin: 0" />
        <div
          v-if="isShowAdd"
          class="add-btn cursor"
          @mousedown="(e) => e.preventDefault()"
          @click="addItem"
        >
          <a-icon type="plus" /> {{ $t("ADD") }}
        </div>
      </div>
      <a-select-option
        v-for="item in searchList"
        :key="item[optionValue]"
        :value="item[optionValue]"
        :disabled="item.enableFlag === 'N' && needDisabled"
      >
        <span v-for="(ele, index) in optionLabelList" :key="index">
          <span v-if="index > 0">-</span>
          {{ item[ele] }}
        </span>
      </a-select-option>
    </a-select>
  </span>
</template>

<script>
import ApiConstant from "@/api/ApiConstant";

export default {
  name: "",
  components: {
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes,
    },
  },
  props: {
    // 当前列表查询key
    queryListKey: {
      type: String,
      default: "eqpName",
    },
    // option label && 父组件搜索用到的key
    optionLabel: {
      type: String,
      default: "eqpName",
    },
    // option value
    optionValue: {
      type: String,
      default: "id",
    },
    // 列表接口api
    requestApi: {
      type: String,
      default: "",
    },
    // 是否显示红色边框，开发者模式下
    showRedBorder: {
      type: Boolean,
      default: false,
    },
    // 是否多选
    showMultiple: {
      type: Boolean,
      default: true,
    },
    defaultSelectedKeys: {
      type: String,
      default: "",
    },
    defaultSelectedNames: {
      type: String,
      default: "",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    isShowAdd: {
      type: Boolean,
      default: false,
    },
    // 请求接口时附带的查询条件
    searchParams: {
      type: Object,
      default: null,
    },
    // 是否需要禁用
    needDisabled: {
      type: Boolean,
      default: true,
    },
    // 是否获取默认
    getDefault: {
      type: Boolean,
      default: false,
    },
    // 是否重置value
    isReset: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: "PLACESELECT",
    },
  },
  data() {
    return {
      value: "",
      searchList: [],
      page: 1,
      total: 0,
      searchName: "",
      optionLabelList: [],
      isFristOpen: true,
    };
  },
  computed: {
    defaultValue() {
      if (this.defaultSelectedKeys) {
        if (this.showMultiple) {
          return this.defaultSelectedKeys.split(",");
        }
        return this.defaultSelectedKeys;
      }
      return undefined;
    },
  },
  watch: {
    defaultValue: {
      handler() {
        this.value = undefined;
      },
      immediate: true,
    },
    defaultSelectedNames: {
      handler(newValue, oldValue) {
        if (newValue) {
          const idArr = this.defaultSelectedKeys.split(",");
          const nameArr = this.defaultSelectedNames.split(",");
          if (!this.showMultiple) {
            this.searchName = this.defaultSelectedNames;
          }
          for (let index = 0; index < idArr.length; index += 1) {
            const id = idArr[index];
            const name = nameArr[index];
            const data = this.searchList.find((item) => item.id === id);
            if (!data) {
              this.searchList.push({
                id,
                [this.optionLabel]: name,
              });
            }
          }
        }
      },
      immediate: true,
      deep: true,
    },
    optionLabel: {
      handler(newValue, oldValue) {
        if (newValue) {
          this.optionLabelList = this.optionLabel.split(",");
        }
      },
      immediate: true,
      deep: true,
    },
    isReset: {
      handler(newValue, oldValue) {
        if (newValue === true) {
          this.reset();
        }
      },
      immediate: true,
      deep: true,
    },
  },
  created() {
    this.getPageData();
  },
  methods: {
    onFocus() {
      // eslint-disable-next-line default-case
      // if (this.searchName || this.searchParams) {
      //   this.clearData();
      //   this.getPageData(); // 调用接口
      // }
      this.clearData();
      this.getPageData(); // 调用接口
    },
    // 监听搜索
    handleSearch(value) {
      if (this.timer) clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.clearData(); // 清除数据
        // eslint-disable-next-line default-case
        this.searchName = value;
        this.getPageData(); // 调用接口
        clearTimeout(this.timer);
      }, 100);
    },
    // 清除数据
    clearData() {
      this.searchName = "";
      this.page = 1;
      this.searchList = [];
      this.total = 0;
    },
    handlePopScroll(e) {
      const { scrollHeight, scrollTop, clientHeight } = e.target;
      if (scrollHeight - scrollTop === clientHeight) {
        // eslint-disable-next-line default-case
        this.page += 1;
        this.getPageData();
      }
    },
    // 分页查询列表数据
    getPageData() {
      if (this.total <= this.searchList.length && this.total) return;
      const params = {
        size: 10,
        // sortRule: "DESC",
        // sortColumn: "enableFlag",
        page: this.page,
        isCancelApiLoad: true,
        ...this.searchParams,
      };
      params[this.queryListKey] = this.searchName;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}${this.requestApi}`, {
          params,
        })
        .then((res) => {
          this.searchList = [...this.searchList, ...res.data.data.records];
          this.total = res.data.data.total;
          if (this.getDefault && this.isFristOpen) {
            this.value = this.searchList[0].id;
            this.$emit("defaultValue", this.searchList[0]);
          }
          this.isFristOpen = false;
        });
    },
    hansldeChange(e) {
      this.value = e;
      if (!this.showMultiple) {
        const index = this.searchList.findIndex(
          (item) => item[this.optionValue] === e
        );
        this.$emit("change", e, index > -1 ? this.searchList[index] : {});
        return;
      }
      const list = this.searchList
        .filter((item) => e.includes(item[this.optionValue]))
        .map((item) => {
          return item[this.optionLabel];
        });
      const chooseList = this.searchList.filter((item) =>
        e.includes(item[this.optionValue])
      );
      this.$emit("change", list, e, chooseList);
    },
    addItem() {
      this.$emit("add");
    },
    reset() {
      this.value = "";
      if (this.getDefault) {
        this.value = this.searchList[0].id;
        this.$emit("defaultValue", this.searchList[0]);
      }
    },
  },
};
</script>
<style lang="less" scoped>
.add-btn {
  width: 100%;
  height: 42px;
  color: @primary-color;
  text-align: center;
  line-height: 42px;
}
/deep/ .ant-select {
  height: 40px;
  line-height: 40px;
  margin-top: calc((40px - @input-height-base) / 2);
  .ant-select-selection--multiple {
    width: 100%;
    height: 32px;
    .ant-select-selection__rendered {
      height: 100%;
      ul {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow-y: hidden;
        display: -webkit-box;
        &::-webkit-scrollbar {
          width: 5px;
          height: 5px;
        }
        &::-webkit-scrollbar-track {
          background-color: #dedede;
          -webkit-border-radius: 1em;
          -moz-border-radius: 1em;
          border-radius: 1em;
        }
        &::-webkit-scrollbar-thumb {
          background-color: #bfbfbf;
          -webkit-border-radius: 1em;
          -moz-border-radius: 1em;
          border-radius: 1em;
        }
        & > li {
          padding: 0 18px 0 5px;
          box-sizing: border-box;
          min-width: 75px;
          float: unset;
        }
      }
    }
  }
}
</style>
