<script lang="tsx">
/*
 * 业务组件 勾选部门
 * */
import { defineComponent, ref, watch, unref, watchEffect, PropType } from 'vue'
import { getDeptTree } from '../api'
import type { DepartmentItem } from '../api/types/custom'

export default defineComponent({
  name: 'SelectDept',
  props: {
    // 树形数据配置
    props: {
      type: Object,
      default: () => {}
    },
    // 默认选中的部门id
    selected: {
      type: Array<string | number>,
      default: () => []
    },
    useExternalTree: {
      type: Boolean,
      default: false
    },
    // 树形数据
    // 如果传了，则直接使用，否则调用接口获取
    externalTree: {
      type: Array as PropType<DepartmentItem[]>,
      default: () => []
    }
  },
  setup(props, { expose }) {
    const depts = ref<any[]>([])
    const getDeptTreeFunc = async () => {
      const { data, success } = await getDeptTree({})
      if (success) depts.value = data
    }
    // 如果useExternalTree为真，则直接使用，否则调用接口获取
    watchEffect(() => {
      if (props.useExternalTree) {
        depts.value = props.externalTree || []
      } else getDeptTreeFunc()
    })

    const ComponentRef = ref()
    const defaultProps = {
      label: 'name'
    }
    const filterText = ref('')
    const filterNode = (value: string, data) => {
      if (!value) return true
      return data[defaultProps.label].includes(value)
    }
    watch(filterText, (val) => {
      ComponentRef.value!.filter(val)
    })

    const getData = () => {
      return unref(ComponentRef).getCheckedKeys()
    }
    expose({
      getData
    })
    return () => {
      return (
        <div>
          <el-input
            vModel={filterText.value}
            clearable
            style="width: 240px"
            class="mb-16px"
            placeholder="筛选部门名称"
          />
          <el-tree
            ref={(el) => (ComponentRef.value = el)}
            data={depts.value}
            props={defaultProps}
            show-checkbox
            check-strictly
            node-key={'id'}
            default-checked-keys={props.selected}
            filter-node-method={(value, data) => filterNode(value, data)}
            {...props.props}
          />
        </div>
      )
    }
  }
})
</script>

<style scoped></style>
