<template>
  <div class="color-select">
    <Select
      v-model="value"
      multiple
      transfer
      clearable
      label-in-value
      @on-change="onChange"
    >
      <Option
        v-for="(item, index) in options"
        :key="item.id"
        :ref="`option${item.value}${index}`"
        :value="item.value"
        :label="item.label"
        :disabled="item.disabled"
        :class="[item.disabled ? 'disabled': '']"
      >
        <div class="color-option">
          <span
            v-if="item.value === 'transparent'"
            style="color: #575757;"
          >{{ item.label }}</span>
          <span
            v-else
            class="color-icon"
            :style="{color: item.value, border: `1px solid ${item.value}`}"
          >{{ item.label }}</span>
        </div>
      </Option>
    </Select>
    <!-- <div
      class="select-wrap"
    >
      <p
        v-if="value.length === 0"
        class="select-placeholder"
      >
        请选择
      </p>
      <div v-else>
        <ColorTag
          :params="selectValue"
        />
      </div>
    </div> -->
  </div>
</template>

<script>
// import ColorTag from '@yunque/component/TableComponents/colorTag.vue';

const R3 = window.R3;
const { network, urlSearchParams } = R3;

export default {
  name: 'ColorSelect',

  // components: {
  //   ColorTag,
  // },

  data() {
    return {
      value: [],
      options: [],
      selectValue: {},
    };
  },

  created() {
    this.getTags();
  },

  methods: {
    onChange(value) {
      let searchValue = []
      const transparentOptionIndex = value.findIndex(item => item.value === 'transparent');
      const isSelectNone = value.length > 0 && value[value.length - 1].value === 'transparent';

      if (value.length > 0 && isSelectNone) {
        // 选了无颜色。则禁用其他颜色
        this.options.forEach((option, index) => {
          if (option.value !== 'transparent') {
            const vm = this.$refs[`option${option.value}${index}`][0];
            vm.$children[0].disabled = true;
            option.disabled = true
          } else {
            const vm = this.$refs[`option${option.value}${index}`][0];
            vm.$children[0].disabled = false;
            option.disabled = false
          }
        });

        // 移除其他颜色选择
        const len = value.length
        for (let i = len - 1; i >= 0; i--) {
          if (value[i].value !== 'transparent') {
            this.value.splice(i, 1);
          }
        }
        searchValue = [this.options[0].label];
      } else if (value.length > 0 && !isSelectNone) {
        // 选了其他颜色。则禁用无颜色
        this.options.forEach((option, index) => {
          if (option.value === 'transparent') {
            const vm = this.$refs[`option${option.value}${index}`][0];
            vm.$children[0].disabled = true;
            option.disabled = true
          } else {
            const vm = this.$refs[`option${option.value}${index}`][0];
            vm.$children[0].disabled = false;
            option.disabled = false
          }
        });

        // 移除无颜色选择
        if (transparentOptionIndex > -1) {
          this.value.splice(transparentOptionIndex, 1);
        }
        searchValue = value.map(item => item.label);
      } else {
        // 没选颜色。解除所有禁用
        this.options.forEach((option, index) => {
          const vm = this.$refs[`option${option.value}${index}`][0];
          vm.$children[0].disabled = false;
          option.disabled = false
        });

        searchValue = [];
      }
      this.$emit('change', searchValue);
    },

    setOptionsStyle() {
      const optionDom = document.querySelector('.ark-select-dropdown-list .color-option');
      if (optionDom) {
        const dropDom = optionDom.parentElement.parentElement;

        // 设置option默认样式
        for (let i = 0; i < dropDom.children.length; i++) {
          const element = dropDom.children[i];
          element.style.display = 'flex';
          element.style.alignItems = 'center';
        }

        // 隐藏【全部】选项
        const allDom = dropDom.querySelector('.ark-select-item-all');
        allDom.style.display = 'none';
      }
    },

    getTags() {
      const params = {
        searchdata: {
          isdroplistsearch: true,
          table: 'T_IESCOLOR_MARK',
          range: 200,
          startindex: 0,
        }
      };
      network.post('/p/cs/newQueryList', urlSearchParams(params)).then(res => {
        if (res.data.code === 0) {
          const data = res.data.data;
          console.log(333, data);
          const options = data.row.map((item) => {
            const colorObj = JSON.parse(item.CVALUE.val);
            return {
              id: item.ID.val,
              label: item.REMARK.val,
              value: colorObj.color,
              disabled: false
            };
          });

          // 先按阿拉伯数字升序，再展示汉字
          options.sort((v1, v2) => {
            const a = v1.label
            const b = v2.label
            const regex = /^[0-9]$/; // 正则表达式匹配以数字开头的字符串

            // 检查a和b的首字母是否是数字
            const isNumberA = regex.test(a);
            const isNumberB = regex.test(b);

            if (isNumberA && isNumberB) {
              // 如果a和b都是数字，按阿拉伯数字升序排序
              return parseInt(a) - parseInt(b);
            } else if (isNumberA) {
              // 如果只有a是数字，a排在b前面
              return -1;
            } else if (isNumberB) {
              // 如果只有b是数字，b排在a前面
              return 1;
            } else {
              // 如果a和b都不是数字，按拼音升序排序
              return a.localeCompare(b, 'zh');
            }
          })

          // 添加无色标签
          options.unshift({
            id: '-1',
            label: '无颜色标签',
            value: 'transparent'
          });
          this.options = options;

          this.$nextTick(() => {
            this.setOptionsStyle();
          });
        }
      });
    }
  },
};
</script>

<style lang="less" scoped>
.color-select {
  position: relative;

  .select-wrap {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    // border: 1px solid red;
    left: 1px;
    right: 23px;
    line-height: 24px;
    height: 24px;
    pointer-events: none;
    cursor: pointer;
    padding-left: 10px;
    background-color: #fff;
  }

  .select-placeholder {
    color: #aaa;
  }
}
</style>
<style lang="less">
.color-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .color-icon {
    padding: 1px 3px;
    border-radius: 4px;
  }
}
.ark-select-item.disabled {
  cursor: not-allowed !important;
}
</style>
