<template>
  <MegaModal
    :visible="modalVisible"
    :centered="true"
    :mask-closable="false"
    :width="760"
    :title="$t('SELECT_ORG')"
    @cancel="handleCloseDrawer"
    @ok="modalVisible = false"
  >
    <a-tree
      ref="departnemtTree"
      v-model="selectedDataList"
      class="functionTree"
      :tree-data="treeData"
      checkable
      :replace-fields="{
        children: 'children',
        key: 'id',
        value: 'id',
        title: 'label',
      }"
      :default-expand-all="true"
      @check="(checkedKeys, info) => handCheck(checkedKeys, info)"
    >
    </a-tree>
    <template slot="footer">
      <a-button type="primary" @click="handleConfirm">{{
        $t("CONFIRM")
      }}</a-button>
      <a-button type="primary" @click="handleCloseDrawer">{{
        $t("CANCEL")
      }}</a-button>
    </template>
  </MegaModal>
</template>
<script>
import { uniqBy } from "lodash";
import { Modal as MegaModal } from "@mega-design/ui-vue";

export default {
  components: {
    MegaModal,
  },
  props: {
    selectedData: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      modalVisible: false, // 新增修改的弹框
      treeData: [],
      selectedDataList: [],
      arrList: [],
    };
  },
  computed: {},
  mounted() {
    this.getTreeData();
  },
  methods: {
    // 打开弹框事件
    openDialog() {
      this.modalVisible = true;
      this.selectedRowKeys = [];
      this.page = 1;
      this.selectedDataList = this.selectedData;
      this.selectedRowKeys = uniqBy([].concat(this.selectedData));
    },
    /**
     * 获取table的数据
     */
    getTreeData() {
      const params = {
        enableFlag: "Y",
      };
      this.$axios.get(`/core/api/sys/org/tree`, { params }).then((res) => {
        this.treeData = res.data?.data || [];
      });
    },
    // 监听确认按钮事件
    handleConfirm() {
      if (this.arrList.length > 0) {
        const arr = [];
        this.arrList.forEach((item) => {
          arr.push({
            id: item.data.props.id,
            label: item.data.props.label,
          });
        });
        this.$emit("returnData", this.selectedDataList, arr);
      }
      this.handleCloseDrawer();
    },
    // 关闭弹框
    handleCloseDrawer() {
      this.selectedDataList = [];
      this.modalVisible = false;
    },
    handCheck(handCheck, info) {
      this.arrList = info.checkedNodes;
      this.selectedDataList = handCheck;
    },
  },
};
</script>
