<template>
  <div class="menu box-main">
    <MomTable
      ref="MomTable"
      row-key="id"
      :expand-icon-column-index="1"
      :row-selection="rowSelection"
      :columns="tableColumns"
      :data-source="tableData"
      :query-param="queryForm"
      :query-param-item="queryFormItem"
      :action-buttons="actionButtons"
      :pagination="false"
      :mega-extend="{ rowIndex: false }"
      :expanded-row-keys="expandedRowKeys"
      :show-enable-flag="hasAuth('DEPTMENT_MANAGEMENT:ENABLED')"
      @beforeSearch="beforeSearch"
      @expand="expandedOnClickIcon"
      @search="searchPageData"
      @add="add"
      @edit="edit"
      @delete="del"
      @enable="
        (record) =>
          handleStatus(
            { status: 'Y', id: record.id },
            'ENABLED',
            'ENABLED_DATA_INFO',
            'ENABLE_SUCCESS'
          )
      "
      @disable="
        (record) =>
          handleStatus(
            { status: 'N', id: record.id },
            'DISABLED',
            'DISABLED_DATA_INFO',
            'DISABLE_SUCCESS'
          )
      "
    >
      <template slot="orgType" slot-scope="text">
        {{ text === "G" ? "集团" : text === "C" ? "公司" : "部门" }}
      </template>
      <template slot="enableFlag" slot-scope="text">
        <span v-if="text == 'Y'" style="color: #0fd19c">
          {{ text === "Y" ? "启用" : "禁用" }}
        </span>
        <span v-else style="color: #d45f5f">
          {{ text === "Y" ? "启用" : "禁用" }}
        </span>
      </template>
      <a-row slot="toolbar" class="button-top-table">
        <a-button v-if="hasAuth('DEPTMENT_MANAGEMENT:ADD')" @click="addMenu">
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <a-button
          :icon="isExpand ? 'up' : 'down'"
          class="btn__blue-4"
          @click="expandedAllRowsChange"
        >
          {{ isExpand ? $t("FOLD") : $t("UNFOLD") }}
        </a-button>
        <a-button
          v-if="hasAuth('DEPTMENT_MANAGEMENT:BATCH_DELETE')"
          type="danger"
          icon="delete"
          @click="handDelete"
        >
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </a-row>
    </MomTable>
    <!-- 集团drawer -->
    <cor-drawer
      ref="corDrawer"
      :drawer="corDrawer"
      :title="title"
      :menu-form="corForm"
      :menu-form-rules="corRules"
      :confirm="() => confirm('cor')"
      :cancel="() => cancel('cor')"
      :drawer-close="() => cancel('cor')"
    />
    <!-- 公司drawer -->
    <com-drawer
      ref="comDrawer"
      :drawer="comDrawer"
      :title="title"
      :menu-form="comForm"
      :menu-form-rules="comRules"
      :confirm="() => confirm('com')"
      :cancel="() => cancel('com')"
      :drawer-close="() => cancel('com')"
    />
    <!-- 部门drawer -->
    <drawer
      ref="drawer"
      :drawer="drawer"
      :title="title"
      :menu-form="menuForm"
      :menu-form-rules="menuFormRules"
      :role-id-list="roleIdList"
      :confirm="() => confirm('depa')"
      :cancel="() => cancel('depa')"
      :drawer-close="() => cancel('depa')"
      @returnData="getReturnData"
    />
    <!-- 上传弹框 -->
    <i-upload-modal
      ref="iUploadModal"
      :url="uploadUrl"
      @fetchList="
        () => {
          if ($refs.MomTable) {
            $refs.MomTable.search({
              orgCode: currentClickNode.orgCode,
            });
          }
        }
      "
    />
  </div>
</template>
<script>
import { deleteLeafArray, getLevelMark } from "@mega-apps/utils";
import { exportExcel } from "@/utils";
import ApiConstant from "@/api/ApiConstant";
import { loadGlobalLoading } from "@/plugins/axios";
import Drawer from "./drawers/drawer";
import CorDrawer from "./drawers/corDrawer";
import ComDrawer from "./drawers/comDrawer";

export default {
  components: {
    Drawer,
    CorDrawer,
    ComDrawer,
  },
  data() {
    return {
      uploadUrl: `${ApiConstant.PREFIX_CORE}/api/sys/i18n/upload`,
      sortParams: null,
      // 查询的表单的配置项
      supEmployee: {
        supEmployeeName: "",
      },
      queryForm: {
        orgName: "",
        orgCode: "",
        orgType: "",
      },
      actionButtons: [
        this.hasAuth("DEPTMENT_MANAGEMENT:ADD") && "add",
        this.hasAuth("DEPTMENT_MANAGEMENT:EDIT") && "edit",
        this.hasAuth("DEPTMENT_MANAGEMENT:DELETE") && "delete",
      ],
      // 是否展开
      isExpand: false,
      // 加载
      tableColumns: [
        {
          dataIndex: "orgCode",
          title: () => this.$t("ORG_CODE"),
          sorter: false,
          width: 300,
        },
        {
          dataIndex: "label",
          title: () => this.$t("ORG_NAME"),
          align: "left",
          dynamic: false,
          sorter: false,
          minWidth: 300,
        },
        {
          dataIndex: "orgType",
          title: () => this.$t("ORG_TYPE"),
          align: "left",
          dynamic: false,
          sorter: false,
          minWidth: 300,
          scopedSlots: { customRender: "orgType" },
        },
        {
          dataIndex: "seq",
          title: () => this.$t("ORDER"),
          sorter: false,
          width: 200,
        },
        {
          dataIndex: "enableFlag",
          title: () => this.$t("STATUS"),
          sorter: false,
          width: 200,
          scopedSlots: { customRender: "enableFlag" },
        },
        {
          dataIndex: "updateBy",
          title: () => this.$t("UPDATE_BY"),
          sorter: false,
          width: 200,
        },
        {
          dataIndex: "updateTime",
          title: () => this.$t("UPDATE_TIME"),
          sorter: false,
          width: 200,
        },
      ],
      selectedRowKeys: [],
      selectData: [],
      tableData: [],
      tableDataCode: [],
      expandedRowKeys: [],
      roleIdList: [],
      // 抽屉的显示隐藏
      drawer: false,
      corDrawer: false,
      comDrawer: false,
      title: "",
      id: "",
      corForm: {
        orgType: "G",
        orgCode: "",
        orgName: "",
        orgNameFull: "",
        extCode: "",
        wechatCorpAgentId: "",
        wechatCorpId: "",
        wechatCorpSecret: "",
        remark: "",
      },
      corRules: {
        orgName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        esopCode: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        remark: [
          {
            max: 255,
            message: this.$t("PLACEENTER") + 255 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
      },
      comForm: {
        orgType: "C",
        orgCode: "",
        orgName: "",
        orgNameFull: "",
        extCode: "",
        parentId: "",
        wechatCorpAgentId: "",
        wechatCorpId: "",
        wechatCorpSecret: "",
        remark: "",
      },
      comRules: {
        orgName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
      },
      menuForm: {
        orgType: "D",
        parentName: "",
        parentId: "", // 上级部门
        orgCode: "", // 组织编码
        orgName: "", // 组织名称
        extCode: "",
        orgNameFull: "", // 部门全称
        seq: "", // 排序
        rolesIds: [],
        roles: [], // 角色
      },
      menuFormRules: {
        orgName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        orgCode: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
      },
      page: 1,
      corporationQueryForm: {
        orgCode: "",
        orgName: "",
      },
      corTableData: [],
      openKeys: [],
      rowId: "",
    };
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    queryFormItem() {
      return this.$observable("queryFormItem", {
        objectCode: {
          itemType: "select",
          options: [],
          optionsProps: {
            label: "objectName",
            value: "objectCode",
          },
          label: () => this.$t("RELATED_ORG"), // 关联组织
        },
        orgName: {
          label: () => this.$t("ORG_NAME"), // 组织名称
        },
        orgCode: {
          label: () => this.$t("ORG_CODE"), // 组织编码
        },
        orgType: {
          itemType: "select",
          options: [
            {
              label: "集团",
              value: "G",
            },
            {
              label: "公司",
              value: "C",
            },
            {
              label: "部门",
              value: "D",
            },
          ],
          optionsProps: {
            label: "label",
            value: "value",
          },
          label: () => this.$t("ORG_TYPE"), // 关联组织
        },
      });
    },
  },
  methods: {
    beforeSearch() {},
    // 启用、禁用
    handleStatus(record, titleText, contentText, tips) {
      this.$confirm({
        title: this.$t(titleText),
        content: this.$t(contentText),
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "exclamation-circle",
        onOk: () => {
          const { id, status } = record;
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/sys/org/enable/${id}/${status}`
            )
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    searchPageData(params) {
      // 若存在查询条件
      if (
        this.queryForm.orgCode ||
        this.queryForm.orgName ||
        this.queryForm.enableFlag ||
        this.queryForm.orgType
      ) {
        this.$axios
          .get(`${ApiConstant.PREFIX_CORE}/api/sys/org/list`, { params })
          .then((res) => {
            deleteLeafArray(res.data.data, "children");
            this.tableData = res.data.data;
          });
      } else {
        // 若不存在查询条件 则查询完整部门树
        this.$axios
          .get(`${ApiConstant.PREFIX_CORE}/api/sys/org/tree`)
          .then((res) => {
            deleteLeafArray(res.data.data, "children");
            this.tableDataCode = getLevelMark(res.data.data, "children", "id");
            this.tableData = res.data.data;
          });
      }
    },
    // 展开/收起所有行
    expandedAllRowsChange() {
      // setTimeout 不能修改为 $nextTick 原因请有兴趣的同学研究
      loadGlobalLoading(1, this.$i18n);
      setTimeout(() => {
        if (this.expandedRowKeys.length === this.tableDataCode.length) {
          this.expandedRowKeys = [];
          this.isExpand = false;
        } else {
          this.expandedRowKeys = [...this.tableDataCode];
          this.isExpand = true;
        }
        loadGlobalLoading(0);
      }, 200);
    },
    expandedOnClickIcon(expanded, record) {
      if (expanded) {
        this.expandedRowKeys.push(record.id);
      } else {
        const index = this.expandedRowKeys.findIndex((e) => e === record.id);
        index !== -1 && this.expandedRowKeys.splice(index, 1);
      }
    },
    // 获取选择用户组件返回数据
    getReturnData(selectKeys, selectData) {
      this.selectData = selectData;
      this.menuForm.rolesIds = selectKeys;
      this.roleIdList = selectData;
    },
    // 下载模板
    handleDownload() {
      const a = document.createElement("a");
      a.href = "/template/i18n_template.xlsx";
      a.click();
    },
    // 导入
    handleImport() {
      this.$refs.iUploadModal.init();
    },
    // 导出
    handleExportExcel() {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/org/department/list`, {
          params: this.queryForm,
        })
        .then((res) => {
          exportExcel(res.data, `${this.$t("MENU:CORE:SYSTEM:I18N")}.xls`);
        });
    },

    // 是否展开table
    expandTable() {
      this.isExpand = !this.isExpand;
      this.$nextTick(() => {
        this.forArr(this.tableData, this.isExpand);
      });
    },
    // 遍历树元素
    forArr(arr, isExpand) {
      const tableRef = this.$refs.iTableComp.$refs.elTable;
      tableRef &&
        arr.forEach((i) => {
          // toggleRowExpansion(i, isExpand)用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
          tableRef && tableRef.toggleRowExpansion(i, isExpand);
          if (i.children) {
            this.forArr(i.children, isExpand);
          }
        });
    },
    // 添加集团
    addMenu() {
      this.clearData("cor");
      this.title = `${this.$t("ADD")}${this.$t("CORPORATION")}`;
      this.corDrawer = true;
    },
    // 添加公司/部门
    add(row) {
      if (row.orgType === "G") {
        this.clearData("com");
        this.comForm.parentId = row.id;
        this.title = `${this.$t("ADD")}${this.$t("COMPANY")}`;
        this.comDrawer = true;
      } else {
        this.clearData("depa");
        this.roleIdList = [];
        this.menuForm.parentId = row.id;
        this.menuForm.seq = (row.children?.length || 0) + 1;
        this.menuForm.parentName = row.label;
        this.title = `${this.$t("ADD")}${this.$t("DEPARTMENT")}`;
        this.drawer = true;
      }
      // eslint-disable-next-line no-param-reassign
      const str = row.parentIds.slice(0, -1);
      this.openKeys = str?.split(",");
      this.rowId = row.id;
    },
    // 编辑按钮点击事件
    edit(row) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/org/get-by-id/${row.id}`)
        .then((res) => {
          this.menuForm.parentName = res.data.data.parentName;
          if (row.orgType === "G") {
            this.corForm = {
              ...res.data.data,
            };
            this.corDrawer = true;
            this.title = `${this.$t("EDIT")}${this.$t("CORPORATION")}`;
          } else if (row.orgType === "C") {
            this.comForm = {
              ...res.data.data,
            };
            this.comDrawer = true;
            this.title = `${this.$t("EDIT")}${this.$t("COMPANY")}`;
          } else {
            [
              "parentName",
              "orgCode",
              "orgName",
              "seq",
              "extCode",
              "parentId",
              "orgNameFull",
              "id",
            ].forEach((key) => {
              this.menuForm[key] = res.data.data[key];
            });
            const tempArr = [];
            const nameArr = [];
            if (res.data.data.roles && res.data.data.roles.length > 0) {
              res.data.data.roles.forEach((item) => {
                tempArr.push(item.id);
                nameArr.push(item.roleName);
              });
              this.menuForm.rolesIds = tempArr;
              this.roleIdList = res.data.data.roles;
            }
            // this.menuForm.roles = res.data.data.roles;
            this.drawer = true;
            this.title = `${this.$t("EDIT")}${this.$t("DEPARTMENT")}`;
          }
        });
    },
    // eslint-disable-next-line
    async confirm(type) {
      const obj = {
        cor: "corDrawer",
        com: "comDrawer",
        depa: "drawer",
      };
      const params = {
        cor: "corForm",
        com: "comForm",
        depa: "menuForm",
      };
      const drawer = obj[type];
      const form = params[type];

      const valid = await this.$refs[drawer].$refs.menuForm.validate();
      const med = this.title.includes(this.$t("EDIT")) ? "put" : "post";
      const msg = this.title.includes(this.$t("EDIT"))
        ? this.$t("EDIT_SUCCESS")
        : this.$t("ADD_SUCCESS");
      if (!valid) return false;
      try {
        // if (type === "depa") {
        //   this[form].rolesIds = this.selectedRowKeys;
        // }
        await this.$axios[med](
          `${ApiConstant.PREFIX_CORE}/api/sys/org`,
          this[form]
        );
        this.$message.success(msg);
        this.$refs.MomTable?.query();
        if (this.openKeys.length >= 2) {
          this.openKeys.shift();
          this.openKeys.push(this.rowId);
          this.expandedRowKeys = this.openKeys;
        } else {
          this[form].parentId && (this.expandedRowKeys = [this[form].parentId]);
        }
        this[drawer] = false;
      } catch (_err) {
        if (type === "depa") {
          if (this.selectData.length > 0) {
            const tempArr = [];
            const nameArr = [];
            this.selectData.forEach((item) => {
              tempArr.push(item.id);
              nameArr.push(item.roleName);
            });
            this[form].rolesIds = tempArr;
            this.roleIdList = nameArr;
          }
        }
        console.error(_err); // eslint-disable-line
      }
    },
    handDelete() {
      if (this.selectedRowKeys.length > 0) {
        this.$confirm({
          title: this.$t("DELETE"),
          content: this.$t("DELETE_INFO"),
          okType: "warning",
          okText: this.$t("CONFIRM"),
          cancelText: this.$t("CANCEL"),
          centered: false,
          icon: "close-circle",
          onOk: () => {
            this.$axios
              .delete(`${ApiConstant.PREFIX_CORE}/api/sys/org/batch-delete`, {
                params: {
                  ids: this.selectedRowKeys.join(","),
                },
              })
              .then(() => {
                this.selectedRowKeys = [];
                this.$message.success(this.$t("DELETE_SUCCESS"));
                this.$refs.MomTable?.query();
              });
          },
        });
      } else {
        this.$message.error(this.$t("SELECT_ONE_DATA"));
      }
    },
    async del({ id }) {
      await this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okType: "warning",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(`${ApiConstant.PREFIX_CORE}/api/sys/org/${id}`)
            .then(() => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 取消
    cancel(type) {
      const obj = {
        cor: "corDrawer",
        com: "comDrawer",
        depa: "drawer",
      };
      const key = obj[type];
      this[key] = false;
      this.$refs[key].$refs.menuForm.resetFields();
    },
    // 清理数据
    clearData(type) {
      const corForm = {
        parentName: "",
        orgType: "G",
        orgCode: "",
        orgName: "",
        orgNameFull: "",
        extCode: "",
        wechatCorpAgentId: "",
        wechatCorpId: "",
        wechatCorpSecret: "",
        remark: "",
      };
      const comForm = {
        parentName: "",
        orgType: "C",
        orgCode: "",
        orgName: "",
        extCode: "",
        orgNameFull: "",
        parentId: "",
        wechatCorpAgentId: "",
        wechatCorpId: "",
        wechatCorpSecret: "",
        remark: "",
      };
      const menuForm = {
        orgType: "D",
        roles: [],
        parentName: "",
        parentId: "",
        orgNameFull: "",
        extCode: "",
        seq: "",
        orgCode: "",
        orgName: "",
      };
      const defaultKey = {
        cor: "corForm",
        com: "comForm",
        depa: "menuForm",
      };
      const defaultObj = {
        cor: corForm,
        com: comForm,
        depa: menuForm,
      };
      const key = defaultKey[type];
      const obj = defaultObj[type];
      this[key] = { ...obj };
    },
  },
};
</script>

<style lang="less" scoped>
/deep/ .action-column {
  display: flex;
  align-items: center;
}
</style>
