<template>
  <el-cascader
    :show-all-levels="false"
    :props="props"
    :value="value"
    @change="changeVal"
  ></el-cascader>
</template>

<script>
  import { getAllDepartment, getAllStaff } from "@/api/Department";
  export default {
    name: "DepartmentAndStaff",
    model: {
      prop: "value",
      event: "change",
    },
    props: {
      value: {
        type: Array,
        default: () => {
          return [];
        },
      },
    },
    data() {
      return {
        id_path: [],
        department_data: [],
        staff_list: [],
        departmentId: "",
        props: {
          lazy: true,
          lazyLoad: async (node, resolve) => {
            const { level } = node;
            if (!node.value) {
              const { data } = await getAllDepartment({
                page: 1,
                pageSize: 50,
              });

              this.department_data = data;
              const nodes = this.reduceData(data);
              // 通过调用resolve将子节点数据返回，通知组件数据加载完成
              resolve(nodes);
            } else {
              const { data } = await getAllStaff({
                page: 1,
                pageSize: 100,
                departmentId: node.value,
              });

              this.staff_list = data;
              const staffData = data.map((item) => ({
                value: item.id,
                label: item.staffName,
                leaf: true,
              }));
              // 通过调用resolve将子节点数据返回，通知组件数据加载完成

              if (node.children.length > 0) {
                // node.children = node.children.concat(staffData)
                resolve(node.children.concat(staffData));
              } else {
                resolve(staffData);
              }
            }
          },
        },
      };
    },
    created() {},
    methods: {
      reduceData(list) {
        list.forEach((item) => {
          item.label = item.title;
          item.value = item.id;
          item.leaf = false;
          if (item.children) {
            this.reduceData(item.children);
          } else {
            item.children = [];
          }
        });
        return list;
      },
      changeVal(val) {
        const staffData = this.staff_list.find((item) => item.id === val[1]);
        const params = {
          staff: staffData,
        };
        this.$emit("change", val, params);
      },
    },
  };
</script>

<style scoped></style>
