<template>
    <el-tree-select :size="size" :data="data" :props="treeProps" node-key="id" :default-expanded-keys="['12630']" clearable filterable check-strictly  />
</template>
<script setup>
import useCatchStore from '@/stores/modules/catch'
import { ROOT_DEPART_ID } from '@/enums/appEnums';

const data = ref([])

const props = defineProps({
    showRoot: {
        type: Boolean,
        default: false
    },
    auth: {
        type: Boolean,
        default: true
    },
    size:{
      type: String,
      default: 'small'
    },
    departData:{
      type:Object,
      departs:{}
    },
    disableRoot: {
      type: Boolean,
      default: false
    },
    onlySecondLevel: {
      type: Boolean,
      default: false
    }
})

const catchSotre = useCatchStore();
let departs = props.auth ? catchSotre.getDeparts() : catchSotre.getDepartsAll()

const treeProps = computed(() => ({
  label: 'shortName',
  value: 'id',
  disabled: (data, node) => {
    if (!node) return false
    if (!props.disableRoot) return false
    return node.level === 1
  }
}))
onMounted(() => {
    getData()
})
watch(departs, () => {
    getData()
})



function getData() {
    const baseData = props.departData
      ? [props.departData]
      : (!props.showRoot && departs.length && departs[0].id === ROOT_DEPART_ID
          ? departs[0].children
          : departs)

    if(props.departData){
      console.log(props.departData)
    }
    data.value = props.onlySecondLevel ? trimChildren(baseData, 1) : baseData
}

function trimChildren(list, level) {
    if (!Array.isArray(list)) return []
    return list.map(item => ({
      ...item,
      children: level >= 2 ? [] : trimChildren(item.children, level + 1)
    }))
}
</script>
<style lang="scss" scoped>

</style>
