<template>
  <div>
    <el-cascader v-model="selectedDeptIds" :options="deptOptions" :props="cascaderProps" placeholder="请选择部门" @change="handleCascaderChange"></el-cascader>
  </div>
</template>

<script>
import { listDept } from '@/api/system/dept';

export default {
  name: 'DeptCascader',
  props: {
    // 双向绑定的部门编号
    deptId: {
      type: [Number, String],
      default: null
    }
  },
  data() {
    return {
      selectedDeptIds: [],
      deptOptions: [],
      cascaderProps: {
        value: 'deptId',
        label: 'deptName',
        children: 'children'
      }
    };
  },
  watch: {
    deptId: {
      immediate: true,
      handler(newVal) {
        this.selectedDeptIds = [newVal];
      }
    },
    selectedDeptIds: {
      deep: true,
      handler(newVal) {
        this.$emit('update:deptId', newVal[newVal.length - 1]);
      }
    }
  },
  created() {
    this.getDeptList();
  },
  methods: {
    getDeptList() {
      listDept().then((response) => {
        this.deptOptions = this.handleTree(response.data, 'deptId');
        if (this.deptId) {
          this.findAndSelectDept(this.deptOptions, this.deptId);
        }
      });
    },
    handleTree(data, idKey) {
      const map = {};
      const tree = [];

      data.forEach((item) => {
        map[item[idKey]] = { ...item, children: [] };
      });

      data.forEach((item) => {
        if (item.parentId === 0) {
          tree.push(map[item[idKey]]);
        } else {
          if (map[item.parentId]) {
            map[item.parentId].children.push(map[item[idKey]]);
          }
        }
      });

      return tree;
    },
    handleCascaderChange(value) {
      const selectedDept = this.findDeptById(this.deptOptions, value[value.length - 1]);
      const pathLabels = [];
      this.buildPathLabels(selectedDept, pathLabels);
      const deptName = selectedDept ? selectedDept.deptName : '';
      const deptPath = pathLabels.reverse().join(' / ');
      const deptId = value[value.length - 1];
      this.$emit('deptChange', { deptName, deptPath, deptId });
    },
    findDeptById(options, id) {
      for (const option of options) {
        if (option.deptId === id) {
          return option;
        }
        if (option.children) {
          const found = this.findDeptById(option.children, id);
          if (found) {
            return found;
          }
        }
      }
      return null;
    },
    buildPathLabels(dept, pathLabels) {
      if (dept) {
        pathLabels.push(dept.deptName);
        if (dept.parentId !== 0) {
          const parentDept = this.findDeptById(this.deptOptions, dept.parentId);
          this.buildPathLabels(parentDept, pathLabels);
        }
      }
    },
    findAndSelectDept(options, id) {
      for (const option of options) {
        if (option.deptId === id) {
          const path = [];
          this.buildPathIds(option, path);
          this.selectedDeptIds = path.reverse();
          return;
        }
        if (option.children) {
          this.findAndSelectDept(option.children, id);
        }
      }
    },
    buildPathIds(dept, path) {
      if (dept) {
        path.push(dept.deptId);
        if (dept.parentId !== 0) {
          const parentDept = this.findDeptById(this.deptOptions, dept.parentId);
          this.buildPathIds(parentDept, path);
        }
      }
    }
  }
};
</script>

<style scoped>
/* 可根据需要添加样式 */
</style>
