<template>
  <main>
    <el-select
      ref="select"
      v-model="values"
      multiple
      style="width:100%"
      :placeholder=lang.pleaseSelect
      @change="handleChange"
      @remove-tag="removeTag"
    >
      <!-- 全选项 -->
      <el-option
        key="select-all"
        :label="options.length == values.length ? lang.cancelAllSelect: lang.allSelect"
        :value="selectAllValue"
        :disabled="disabled"
      />

      <!-- 其他选项 -->
      <el-option
        v-for="item in options"
        :key="item.id"
        :disabled="disabled && item.id === Number(judgingCondition)"
        :label="item.name"
        :value="item.id"
      />
    </el-select>
  </main>
</template>

<script>
export default {
  name: 'select-tags',
  props: {
    options: {
      type: Array,
      default: () => []
    },
    value: {
      type: Array,
      default: () => []
    },
    placeholder: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    judgingCondition: {
      type: String | Number,
      default: ''
    }
  },
  data() {
    return {
      observer: null,
      hideDom: null,
      selectAllValue: 'select-all', // 用于标识“全选”选项
    };
  },
  computed: {
    values: {
      get() {
        return this.value;
      },
      set(val) {
        // 优化全选和取消全选的逻辑
        const isSelectAll = val.includes(this.selectAllValue);
        const filteredVal = val.filter(item => item !== this.selectAllValue);
        const isAllSelected = filteredVal.length === this.options.length;
        console.log(isSelectAll);

        if (isSelectAll) {
          this.$emit('input', isAllSelected ? [] : this.options.map(item => item.id)); // 全选或取消全选
        } else {
          this.$emit('input', val); // 普通选择
        }
      }
    }
  },
  mounted() {
    this.mutationObserver();
  },
  beforeDestroy() {
    this.observer.disconnect();
  },
  methods: {
    mutationObserver() {
      const tagLIstDom = this.$refs.select.$el.querySelector('.el-select__tags');
      const tagSpanDom = this.$refs.select.$el.querySelector('.el-select__tags > span');

      this.hideDom = document.createElement('span');
      this.hideDom.classList.add('count-node');
      tagSpanDom.append(this.hideDom);

      const config = { childList: true };

      const callback = mutationsList => {
        mutationsList.forEach(item => {
          if (item.type === 'childList') {
            const tagList = item.target.childNodes;
            let tagWidth = 0;
            let tagNum = 0;
            let availableTagWidth = 0;

            for (let i = 0; i < tagList.length; i++) {
              const e = tagList[i];
              if (tagWidth > tagLIstDom.offsetWidth) {
                e.style.display = 'none';
              } else {
                e.style.display = 'inline-block';
              }
              tagWidth += e.offsetWidth + 7;

              if (tagWidth > tagLIstDom.offsetWidth) {
                e.style.display = 'none';
              } else {
                e.style.display = 'inline-block';
              }

              if (e.style.display !== 'none') {
                tagNum++;
                this.hideDom.style.display = 'none';
                const margin = tagNum === 1 ? 0 : 7;
                availableTagWidth += e.offsetWidth + margin;
              } else {
                this.hideDom.style.display = 'inline-block';
                this.hideDom.style.left = `${availableTagWidth}px`;
                this.hideDom.innerHTML = `+${tagList.length - tagNum}`;
              }
            }
          }
        });
      };

      this.observer = new MutationObserver(callback);
      this.observer.observe(tagSpanDom, config);
    },
    handleChange() {
      this.$emit('change', this.value);
    },
    removeTag(val) {
      if (val === this.selectAllValue) {
        // 取消全选时清空所有选择
        this.$emit('input', []);
      } else {
        this.$emit('remove-tag', val);
      }
    }
  }
};
</script>

<style scoped>
</style>
