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

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

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

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

watch(() => props.modelValue, val => {
  selectedOptions.value = val;
  if (props.options.length > 0) {
    isAll.value = val.length === props.options.length
  }
}, {
  deep: true,
  immediate: true
})

// 全选点击
const selectAll = () => {
  isAll.value = !isAll.value
  if (isAll.value) {
    selectedOptions.value = props.options.map(item => item.value);
    emits('update:modelValue', selectedOptions.value);
    emits('change')
  } else {
    selectedOptions.value = [];
    emits('update:modelValue', selectedOptions.value);
    emits('change')
  }
  nextTick(() => {
    const list = document.querySelectorAll('.el-select-dropdown .el-select-dropdown__item')
    list.forEach(el => el.classList.add('no-hovering'))
  })
}

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

const over = () => {
  const list = document.querySelectorAll('.el-select-dropdown .el-select-dropdown__item')
  list.forEach(el => el.classList.add('no-hovering'))
}
const out = () => {
  const list = document.querySelectorAll('.el-select-dropdown .el-select-dropdown__item')
  list.forEach(el => el.classList.remove('no-hovering'))
}
</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>
