<template>
  <div class="tree-border permi-select">
    <el-tree
      ref="treeRef"
      :data="treeData"
      show-checkbox
      default-expand-all
      node-key="id"
      :props="{ label: 'name', children: 'children' }"
      :check-strictly="true"
      empty-text="暂无数据"
      @check="handleCheck"
    />
  </div>
</template>

<script setup lang="ts" name="PermiSelect">
import { ref, computed, watch, nextTick, PropType } from 'vue';
import type { ElTree } from 'element-plus';

const props = defineProps({
  modelValue: {
    type: Array as PropType<number[]>,
    default: () => []
  },
  options: {
    type: Array as PropType<any[]>,
    default: () => []
  }
});

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

const treeRef = ref<InstanceType<typeof ElTree>>();

const treeData = computed(() => {
  return [
    {
      id: 0,
      name: '全部门店',
      children: props.options
    }
  ];
});

watch(
  () => props.modelValue,
  (newVal) => {
    nextTick(() => {
      if (!treeRef.value) return;
      if (!newVal || newVal.length === 0) {
        treeRef.value.setCheckedKeys([]);
        const rootNode = treeRef.value.getNode(0);
        if (rootNode) rootNode.indeterminate = false;
      } else if (newVal.includes(0)) {
        const allKeys = [0, ...props.options.map(o => o.id)];
        treeRef.value.setCheckedKeys(allKeys);
        const rootNode = treeRef.value.getNode(0);
        if (rootNode) rootNode.indeterminate = false;
      } else {
        treeRef.value.setCheckedKeys(newVal);
        const rootNode = treeRef.value.getNode(0);
        if (rootNode) rootNode.indeterminate = newVal.length > 0;
      }
    });
  },
  { immediate: true, deep: true }
);

const handleCheck = (data: any, info: any) => {
  if (!treeRef.value) return;
  const isChecked = info.checkedKeys.includes(data.id);
  
  let newValue: number[] = [];
  
  if (data.id === 0) {
    if (isChecked) {
      newValue = [0];
    } else {
      newValue = [];
    }
  } else {
    // 获取当前树中选中的子节点，不包含 0
    let currentCheckedChildren = props.options
      .map(o => o.id)
      .filter(id => info.checkedKeys.includes(id));
      
    newValue = currentCheckedChildren;
  }
  
  emit('update:modelValue', newValue);
};
</script>

<style scoped>
.permi-select {
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 5px;
  max-height: 200px;
  overflow-y: auto;
}
</style>
