<template>
  <el-dialog
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :visible.sync="dialogVisible"
    append-to-body
    title="选择机构"
  >
    <el-cascader-panel
      ref="cascader"
      v-model="selectetValue"
      :options="options"
      :props="cascaderProps"
    ></el-cascader-panel>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeVisible">取消</el-button>
      <el-button type="primary" @click="comfirm">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getAllTree } from "@/api/system/dept";

export default {
  name: "BranchCascaderDialog",
  props: {
    parentId: {
      type: Number,
      default: 0,
    },
    // 包含父级
    containParent: {
      type: Boolean,
      default: false,
    },
    emitPath: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      dialogVisible: false,
      cascaderProps: {
        multiple: true,
        checkStrictly: true,
        value: "deptId",
        label: "deptName",
        emitPath: this.emitPath,
      },
      options: [],
      tempOptions: [],
      selectetValue: null,
    };
  },
  watch: {
    dialogVisible(val) {
      if (!val) {
        this.$refs.cascader?.clearCheckedNodes();
      }
    },
  },
  created() {
    this.getTreeData();
  },
  methods: {
    open(data) {
      this.dialogVisible = true;
      this.selectetValue = data?.map((val) => val.deptId) || null;
    },
    closeVisible() {
      this.dialogVisible = false;
    },
    comfirm() {
      this.$emit("comfirm", this.getCheckedDatas());
      this.dialogVisible = false;
    },
    // 获取所有数据
    getTreeData() {
      getAllTree().then((res) => {
        this.options = res || [];
        this.tempOptions = [...this.options];
        this.updateOptions();
      });
    },
    updateOptions() {
      if (this.parentId) {
        let findList = this.tempOptions;
        const findListFun = (list) => {
          list?.findIndex((item) => {
            if (item.deptId === this.parentId) {
              findList = this.containParent ? [item] : item.children || [];
              return true;
            } else {
              findListFun(item.children);
            }
            return false;
          });
        };
        findListFun(findList);
        this.options = findList;
      } else {
        this.options = this.tempOptions;
      }
    },
    selectedChange(val) {
      console.log("选中的值：", this.selectetValue);
    },
    // emitPath为true时获取选中所有节点数据，false时获取当前
    getCheckedDatas() {
      return (
        this.$refs.cascader.getCheckedNodes()?.map((val) => val.data) || []
      );
    },
  },
};
</script>

<style>
</style>
