<template>
  <div>
    <!--    @focus="onFocus" -->
    <el-select
      v-bind="{ ...$attrs }"
      :value="value"
      filterable
      remote
      reserve-keyword
      collapse-tags
      clearable
      :multiple="multiple"
      :placeholder="placeholder"
      :remote-method="remoteMethod"
      ref="select"
      :loading="loading"
      @focus="onFocus"
      @change="changeValue"
      :style="{ width: this.selectWidt + 'px!important' }"
    >
      <el-option
        v-for="item in options"
        :key="item.userId"
        :label="item.userName"
        :value="item.userId"
      >
      <span style="float: left">{{ item.userName }}</span>
      <span style="float: right; color: #8492a6; font-size: 13px">{{ item.userId }}</span>
      </el-option>
    </el-select>
  </div>
</template>
<script>
const placeholder = {
  setTeachers: "请选择老师",
  setEducations: "请选乐团主管",
  setEmploys:"请选择操作人"
};
import { throttle, slice, uniqBy } from "lodash";
import selects from "@/store/modules/selects";
export default {
  name: "remote-search",
  props: ["commit", "number", "value", "width", "multiple", "ariaPlaceholder"],
  data() {
    return {
      options: [],
      list: [],
      listById: {},
      loading: false,
      constant: this.number || 50,
      placeholder: this.ariaPlaceholder || placeholder[this.commit],
      selectWidt: this.width || 180,
      isFirst: true,
    };
  },
  async mounted() {
    // this.getList();
    //  (this.value)
    this.getOptions(this.value || "");
  },
  methods: {
    async getList() {
      // 处理乐团主管数据请求
      const commit = this.commit == 'setEducations' ? 'setOrganRole' : this.commit
      await this.$store.dispatch(commit);
      if(commit == 'setOrganRole') {
        this.list = this.selects.roles[this.enumer[commit]];
      } else {
        this.list = this.selects[this.enumer[commit]];
      }
      const data = {};
      for (const item of this.list) {
        data[item.userId] = item;
      }
      this.listById = data;

      this.options =
        this.list.length <= this.constant
          ? this.list
          : slice(this.list, 0, this.constant);
      this.options = uniqBy(this.options, "userId");
      //   (this.options)
    },
    remoteMethod(query) {
      // throttle

      throttle(this.getOptions, 800)(query);
    },
    async getOptions(query) {
      if (query && query.length > 0) {
        let flag;
        this.options = uniqBy(
          this.list.filter((item) => {
            flag =
              item.userName
                .toLowerCase()
                .indexOf(query.toString().toLowerCase()) > -1 ||
              item.userId == query;
            if (this.multiple) {
              return flag || this.value.includes(item.userId);
            } else {
              //  (query,this.value)
              return flag || item.userId == this.value;
            }
          }),
          "userId"
        );
      } else {
        try {
          await this.getList();
          const optionids = this.options.map((item) => item.userId);

          const valueItem = this.listById[this.value];
          if (!optionids.includes(this.value) && valueItem) {
            this.options.push(valueItem);
            this.options = uniqBy(this.options, "userId");
          }
        } catch (e) {
          //  (e)
        }
      }
    },
    changeValue(val) {
      this.isFirst = false;
      this.$emit("input", val);
      this.$emit("change", val);
      //  ('来了',this.$refs.select.query)
      this.$nextTick((res) => {
        this.getOptions(this.$refs.select.query);
      });
    },
    onFocus() {
      this.$nextTick((res) => {
        this.getOptions(this.$refs.select.query);
      });
    },
  },
  computed: {
    enumer() {
      return {
        setTeachers: "teachers",
        setOrganRole: "EDUCATION",
        setEmploys:'employs'
      };
    },
  },
  watch: {
    value: {
      immediate: true,
      deep: true,
      handler(val) {
        // && this.isFirst
        if (this.multiple && this.isFirst) {
          if (val?.length > 0) {
            this.getOptions();
          }
        } else {
          if (val && this.isFirst) {
            this.getOptions();
          } else {
            this.getOptions(val);
          }
        }
      },
    },
  },
};
</script>
<style lang="scss" scoped>
</style>
