<script setup>
import { ref, watch } from 'vue';
import 'element-plus/dist/index.css';
import { ElCascader } from 'element-plus';

const props = defineProps({
  options: {
    type: Array,
    default: () => []
  },
  modelValue: {
    type: Array,
    default: () => []
  }
});
const cascader = ref(props.modelValue);
const emit = defineEmits(['update:modelValue']);
// 直接使用 toRef 保持响应式
const selectedValue = ref(props.modelValue);
watch(
  () => props.modelValue,
  (newVal) => {
    selectedValue.value = newVal;
    cascader.value = newVal;
  }
);
const changeValue = (value) => {
  const hasEmpty = value.some((item) => item[0] === '0');
  const propEmpty = cascader.value.some((item) => item[0] === '0');
  if (hasEmpty && !propEmpty) {
    emit('update:modelValue', [['0']]);
  } else {
    emit(
      'update:modelValue',
      value.filter((item) => item[0] !== '0')
    );
  }
};
</script>

<template>
  <el-cascader
    v-model="selectedValue"
    class="yl-cascader"
    style="width: 100%"
    :show-all-levels="false"
    :options="props.options"
    :props="{ multiple: true }"
    @change="changeValue"
  >
  </el-cascader>
</template>
<style scoped>
::v-deep .yl-cascader {
  width: 100%;
}
</style>
