<template>
  <el-cascader
    ref="cascaderRef"
    v-bind="$attrs"
    :placeholder="placeholder"
    :options="options || deptList"
    :value="value"
    :props="cascaderProps"
    @change="handleSelect"
  ></el-cascader>
</template>

<script>
import { getTreeHospDept as getDeptApi2 } from "@/api/admin";
const getDeptApi = getDeptApi2
export default {
  name: "TreeDept",
  props: {
    value: {
      type: [Number, String, Array],
    },
    defaultName: {
      type: String,
      required: false,
    },
    props: {
      type: Object,
      default: () => ({}),
    },
    autoFetch: {
      type: Boolean,
      default: true,
    },
    options: {
      type: Array,
    },
  },
  data() {
    return {
      deptList: [],
    };
  },
  created() {
    if (this.autoFetch) {
      this.loadDept();
    }
  },
  computed: {
    // 特殊逻辑，如果表单科室ID是一级科室，且该科室下存在二级科室，此时科室名无法回显，折中方案：placeholder位置回显科室名
    // BUG: http://szyx.zentaopm.com/bug-view-11929.html
    placeholder() {
      if (this.defaultName && this.value && this.deptList.length > 0) {
        const deptOption = this.deptList.find((item) => item.id === this.value);
        if (deptOption && deptOption.children?.length > 0) {
          return this.defaultName;
        }
      }
      return "请选择";
    },
    cascaderProps() {
      return Object.assign(
        {
          emitPath: false,
          label: "name",
          value: "id",
          leaf: "children",
        },
        this.props
      );
    },
    selectItem() {
      return this.$refs.cascaderRef.getCheckedNodes(true)?.[0]?.data || {}
    }
  },
  methods: {
    clear() {
      this.deptList = [];
    },
    async loadDept(query) {
      const res = await getDeptApi(query);
      this.deptList = res.data || [];
    },
    handleSelect(val) {
      console.log('handleSelect=', this.selectItem)
      this.$emit("input", val);
      this.$emit("change", val, this.selectItem);
    },
  },
};
</script>
