<template>
  <el-select v-bind="$attrs"
    v-model="selectedOptions"
    @change="handleChange">
    <el-option v-for="str in options"
      :label="str"
      :value="str">
    </el-option>
    <li class="el-select-dropdown__item all_item"
      :class="{ 'is-selected': isAll }"
      @click.stop="selectAll"
      @mouseenter.stop="over"
      @mouseleave.stop="out">
      <span>全选</span>
    </li>
  </el-select>
</template>

<script setup>
const selectedOptions = ref([]) // 当前选中的值集合
const isAll = ref(false) // 全选状态

const emits = defineEmits(['update:modelValue']);

const props = defineProps({
  options: {
    type: Array,
    default: () => [],
  },
  modelValue: {
    type: [Array, String],
    default: () => []
  }
})

watch(() => props.modelValue, val => {
  selectedOptions.value = val;
  isAll.value = val.length === props.options.length
}, {
  deep: true,
  immediate: true
})
// 设置样式
const noHover = () => {

  const list = document.querySelectorAll('.el-select-dropdown .el-select-dropdown__item')
  list.forEach(el => el.classList.add('no-hovering'))
}

// 全选点击
const selectAll = () => {
  isAll.value = !isAll.value
  if (isAll.value) {
    selectedOptions.value = [...props.options];
    emits('update:modelValue', selectedOptions.value);
  } else {
    selectedOptions.value = [];
    emits('update:modelValue', selectedOptions.value);
  }
  nextTick(() => {
    noHover()
  })
}

const handleChange = (val) => {
  isAll.value = val.length === props.options.length
  emits('update:modelValue', val)
}

const over = () => {
  noHover()
}
const out = () => {
  noHover()
}
</script>

<style scoped
  lang="scss">

  .all_item {
    cursor: pointer;
  }

  .all_item:hover {
    background-color: var(--el-fill-color-light);
  }

  .no-hovering {
    background-color: transparent;
  }


</style>
