<template>
  <div class="page_main">
    <mega-table-query-filter
      class="system-divide-bg"
      :query-param="queryForm"
      :query-param-item="queryFormItem"
      @query="queryFilterSearch"
    />
    <div class="main_box">
      <MomTable
        class="main_left"
        row-key="id"
        :row-selection="rowSelection"
        :columns="leftTableColumns"
        :data-source="leftTableData"
        :show-util-operator="false"
        :row-class-name="
          (record, index) => {
            return index === selectIndex ? 'clickRowStyle' : ' ';
          }
        "
        :scroll="{ y: 600 }"
        :pagination="{
          size: 'small',
          showQuickJumper: false,
          showTotal: () => null,
        }"
        :mega-extend="{
          rowIndex: false,
        }"
        :page.sync="leftTablePage"
        :total="leftTableTotal"
        :action-buttons="leftTableAction"
        @change="tableChange"
        @edit="editDict"
        @delete="delDict"
        @search="searchPageData"
      >
        <template slot="dictName" slot-scope="text, record">
          <span :title="`${record.dictName}(${record.dictCode})`"
            >{{ record.dictName }}({{ record.dictCode }})</span
          >
        </template>
        <div slot="toolbar">
          <a-button
            v-if="hasAuth('DICTIONARY_MANAGEMENT:ADD')"
            @click="addMDict"
          >
            <a-icon type="plus" />
            {{ $t("ADD") }}
          </a-button>
          <a-button
            v-if="hasAuth('DICTIONARY_MANAGEMENT:EXPORT')"
            class="btn__green-1"
            icon="to-top"
            :disabled="!leftTableData.length"
            @click="handleExportExcel"
          >
            {{ $t("EXPORT") }}
          </a-button>
          <a-button
            v-if="hasAuth('DICTIONARY_MANAGEMENT:BATCH_DELETE')"
            type="danger"
            icon="delete"
            @click="handDelete"
          >
            {{ $t("BATCH_DELETE") }}
          </a-button>
        </div>
      </MomTable>
      <MomTable
        row-key="id"
        class="main_right"
        :row-selection="rowRightSelection"
        :columns="rightTableColumns"
        :data-source="rightTableData"
        :action-buttons="tableAction"
        :pagination="false"
        @edit="editChildDict"
        @delete="delChildDict"
      >
        <template slot="enableFlag" slot-scope="text">
          <span :class="text === 'Y' ? 'text-success' : 'text-error'">
            {{ getAttrValue(stateList, text) }}
          </span>
        </template>
        <div slot="toolbar">
          <a-button
            v-if="hasAuth('DICTIONARY_MANAGEMENT:ADD')"
            class="fr"
            type="success"
            :disabled="dictForm.dictCode === ''"
            @click="addChildDict"
          >
            <a-icon type="plus" />
            {{ $t("ADD") }}
          </a-button>
          <MomImportButton
            v-if="hasAuth('DICTIONARY_MANAGEMENT:IMPORT')"
            object-name="DICTIONARY_DATA"
          />
          <a-button
            v-if="hasAuth('DICTIONARY_MANAGEMENT:BATCH_DELETE')"
            type="danger"
            icon="delete"
            @click="handRightDelete"
          >
            {{ $t("BATCH_DELETE") }}
          </a-button>
        </div>
      </MomTable>
    </div>
    <!-- 新增、编辑字典弹框 -->
    <MegaDrawer
      :title="$t(title)"
      :visible.sync="drawer"
      width="520"
      @close="drawerClose"
    >
      <template slot="main">
        <a-form-model
          ref="dictForm"
          layout="vertical"
          :model="dictForm"
          :rules="dictFormRules"
        >
          <a-form-model-item :label="$t('CODE')" prop="dictCode">
            <a-input
              v-model.trim="dictForm.dictCode"
              :placeholder="$t('PLACEENTER')"
              allow-clear
            />
          </a-form-model-item>

          <a-form-model-item :label="$t('NAME')" prop="dictName">
            <a-input
              v-model.trim="dictForm.dictName"
              :placeholder="$t('PLACEENTER')"
              allow-clear
            />
          </a-form-model-item>
          <a-form-model-item :label="$t('CATEGORY')" prop="dictCategory">
            <a-select
              v-model="dictForm.dictCategory"
              :placeholder="$t('PLACESELECT')"
            >
              <a-select-option
                v-for="item in dictCategoryList"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item :label="$t('REMARK')" prop="remark">
            <a-textarea
              v-model.trim="dictForm.remark"
              :placeholder="$t('PLACEENTER')"
              type="textarea"
              :auto-size="{ minRows: 2 }"
            />
          </a-form-model-item>
        </a-form-model>
      </template>
      <footer slot="footer">
        <a-button type="primary" @click="confirm">
          <Icon type="icon-cur-save_1" :size="18" /> {{ $t("SAVE") }}
        </a-button>
        <a-button @click="cancel">
          <Icon type="icon-dir-f-rollback" :size="18" />{{ $t("CANCEL") }}
        </a-button>
      </footer>
    </MegaDrawer>
    <!-- 新增、编辑子字典弹框 -->
    <MegaDrawer
      :title="$t(title)"
      :visible.sync="drawerChild"
      width="520"
      @close="drawerCloseChild"
    >
      <template slot="main">
        <a-form-model
          ref="dictChildForm"
          layout="vertical"
          :model="dictChildForm"
          :rules="dictChildFormRules"
        >
          <a-form-model-item :label="$t('NAME')" prop="dataLabel">
            <a-input
              v-model.trim="dictChildForm.dataLabel"
              :placeholder="$t('PLACEENTER')"
              allow-clear
            />
          </a-form-model-item>
          <a-form-model-item :label="$t('DATA_VALUE')" prop="dataValue">
            <a-input
              v-model.trim="dictChildForm.dataValue"
              :placeholder="$t('PLACEENTER')"
              allow-clear
            />
          </a-form-model-item>
          <a-form-model-item :label="$t('STATUS')" prop="enableFlag">
            <a-select
              v-model="dictChildForm.enableFlag"
              :placeholder="$t('PLACESELECT')"
            >
              <a-select-option
                v-for="item in enableFlagList"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item :label="$t('SORT')" prop="dataOrder">
            <a-input-number
              v-model="dictChildForm.dataOrder"
              :min="0"
              style="width: 100%"
            />
          </a-form-model-item>
          <a-form-model-item :label="$t('CATEGORY')" prop="dataCategory">
            <a-select
              v-model="dictChildForm.dataCategory"
              :placeholder="$t('PLACESELECT')"
            >
              <a-select-option
                v-for="item in dictCategoryList"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item
            :label="$t('EXTENDED_FIELD') + '1'"
            prop="dataValueExt1"
          >
            <a-textarea
              v-model.trim="dictChildForm.dataValueExt1"
              :placeholder="$t('PLACEENTER')"
              type="textarea"
              :auto-size="{ minRows: 2 }"
            />
          </a-form-model-item>
          <a-form-model-item
            :label="$t('EXTENDED_FIELD') + '2'"
            prop="dataValueExt2"
          >
            <a-textarea
              v-model.trim="dictChildForm.dataValueExt2"
              :placeholder="$t('PLACEENTER')"
              type="textarea"
              :auto-size="{ minRows: 2 }"
            />
          </a-form-model-item>
          <a-form-model-item :label="$t('REMARK')" prop="remark">
            <a-textarea
              v-model.trim="dictChildForm.remark"
              :placeholder="$t('PLACEENTER')"
              type="textarea"
              :auto-size="{ minRows: 2 }"
            />
          </a-form-model-item>
        </a-form-model>
      </template>
      <footer slot="footer">
        <a-button type="primary" @click="confirmChild">
          <Icon type="icon-cur-save_1" :size="18" /> {{ $t("SAVE") }}
        </a-button>
        <a-button @click="cancelChild">
          <Icon type="icon-dir-f-rollback" :size="18" /> {{ $t("CANCEL") }}
        </a-button>
      </footer>
    </MegaDrawer>
    <!-- 上传弹框 -->
    <i-upload-modal
      ref="iUploadModal"
      :url="uploadUrl"
      @fetchList="searchPageData"
    />
  </div>
</template>
<script>
import { mapState } from "vuex";
import { Drawer as MegaDrawer, Icon } from "@mega-design/ui-vue";
import { exportExcel } from "@/utils";
import ApiConstant from "@/api/ApiConstant";
import MomImportButton from "@/components/MomImportButton";

export default {
  components: {
    MegaDrawer,
    MomImportButton,
    Icon,
  },
  data() {
    return {
      uploadUrl: `${ApiConstant.PREFIX_CORE}/api/sys/dict/upload`,
      selectIndex: null,
      queryForm: {
        dictCode: "",
        dictName: "",
        dictCategory: "",
      },
      leftTablePage: 1,
      leftTableTotal: 0,
      leftTableData: [], // 数据字典列表
      leftTableHeight: 50,
      defaultProps: {
        children: "children",
        label: "dictName",
      },
      // 类别字典
      dictCategoryList: [],
      // 是否可用的字典
      enableFlagList: [],
      rightTableData: [],
      rightTableHeight: 50,
      title: "",
      drawer: false,
      drawerChild: false,
      id: "",
      parentDictName: "",
      dictForm: {
        dictCode: "",
        dictName: "",
        dictCategory: "",
        remark: "",
      },
      dictChildForm: {
        dictCode: "",
        parentDictCode: "",
        dataLabel: "",
        dataValue: "",
        enableFlag: "Y",
        dataOrder: "",
        dataValueExt1: "",
        dataValueExt2: "",
        remark: "",
        dataCategory: "",
      },
      confirmType: "", // 确认类型
      leftTableAction: [
        this.hasAuth("DICTIONARY_MANAGEMENT:EDIT") && "edit",
        this.hasAuth("DICTIONARY_MANAGEMENT:DELETE") && "delete",
        (h, value, a, b) => {
          if (this.hasAuth("DICTIONARY_MANAGEMENT:ENABLED")) {
            return (
              <span type="text">
                {value.record.enableFlag === "Y" ? (
                  <Icon
                    onClick={() => this.disableChildDictLeft(value.record, "N")}
                    type="icon-ins-stop"
                    size={15}
                    style="color:#d45f5f;cursor: pointer;"
                    title={this.$t("DISABLED")}
                  />
                ) : (
                  <Icon
                    onClick={() => this.disableChildDictLeft(value.record, "Y")}
                    type="icon-ins-check-circle"
                    size={15}
                    style="color:#0ea8d0;cursor: pointer;"
                    title={this.$t("ENABLED")}
                  />
                )}
              </span>
            );
          }
          return null;
        },
      ],
      tableAction: [
        this.hasAuth("DICTIONARY_MANAGEMENT:EDIT") && "edit",
        (h, value, a, b) => {
          if (this.hasAuth("DICTIONARY_MANAGEMENT:ENABLED")) {
            return (
              <span type="text">
                {value.record.enableFlag === "Y" ? (
                  <Icon
                    onClick={() => this.disableChildDict(value.record, "N")}
                    type="icon-ins-stop"
                    size={15}
                    style="color:#d45f5f;cursor: pointer;"
                    title={this.$t("DISABLED")}
                  />
                ) : (
                  <Icon
                    onClick={() => this.disableChildDict(value.record, "Y")}
                    type="icon-ins-check-circle"
                    size={15}
                    style="color:#0ea8d0;cursor: pointer;"
                    title={this.$t("ENABLED")}
                  />
                )}
              </span>
            );
          }
          return null;
        },
        this.hasAuth("DICTIONARY_MANAGEMENT:DELETE") && "delete",
      ],
      pagination: {
        size: "small",
      },
      stateList: [],
      dictCategory: "",
      selectedRowKeys: [],
      selectedRightRowKeys: [],
    };
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    rowRightSelection() {
      return {
        selectedRowKeys: this.selectedRightRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRightRowKeys = selectedRowKeys;
        },
      };
    },
    pageSize() {
      return this.$store.state.pagination.pageSize;
    },
    dictFormRules() {
      // eslint-disable-next-line
      const temp_obj = {
        dictCode: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
          {
            max: 64,
            message: this.$t("PLACEENTER") + 64 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        dictName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
          {
            max: 32,
            message: this.$t("PLACEENTER") + 32 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        dictCategory: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        type: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        remark: [
          {
            max: 255,
            message: this.$t("PLACEENTER") + 255 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
      };
      // eslint-disable-next-line
      return temp_obj;
    },
    dictChildFormRules() {
      // eslint-disable-next-line
      const temp_obj = {
        dataLabel: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
          {
            max: 32,
            message: this.$t("PLACEENTER") + 32 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        dataValue: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
          {
            max: 32,
            message: this.$t("PLACEENTER") + 32 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        enableFlag: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        dataCategory: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        dataOrder: [],
        remark: [
          {
            max: 255,
            message: this.$t("PLACEENTER") + 255 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
      };
      // eslint-disable-next-line
      return temp_obj;
    },
    queryFormItem() {
      return this.$observable("queryFormItem", {
        dictCode: {
          label: () => this.$t("CODE"),
        },
        dictName: {
          label: () => this.$t("NAME"),
        },
        dictCategory: {
          itemType: "select",
          label: () => this.$t("CATEGORY"),
          labelWidth: 60,
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
        },
      });
    },
    leftTableColumns() {
      return [
        {
          dataIndex: "dictName",
          key: "dictName",
          ellipsis: true,
          customCell: this.rowClick,
          title: () => this.$t("NAME"),
          sorter: false,
          scopedSlots: { customRender: "dictName" },
        },
      ];
    },
    rightTableColumns() {
      return [
        {
          dataIndex: "dataLabel",
          title: () => this.$t("NAME"),
          width: 160,
          sorter: false,
        },
        {
          dataIndex: "dataValue",
          title: () => this.$t("DATA_VALUE"),
          width: 280,
          sorter: false,
        },
        {
          dataIndex: "enableFlag",
          key: "enableFlag",
          title: () => this.$t("STATUS"),
          scopedSlots: { customRender: "enableFlag" },
          width: 100,
          sorter: false,
        },
        {
          dataIndex: "dataOrder",
          title: () => this.$t("SORT"),
          width: 80,
          sorter: false,
        },
        {
          dataIndex: "remark",
          title: () => this.$t("REMARK"),
          width: 200,
          sorter: false,
        },
        {
          dataIndex: "updateBy",
          title: () => this.$t("UPDATE_BY"),
          width: 120,
          sorter: false,
        },
        {
          dataIndex: "updateTime",
          title: () => this.$t("UPDATE_TIME"),
          minWidth: 200,
          sorter: false,
        },
      ];
    },
    ...mapState({
      user: (state) => state.auth.user.user,
    }),
  },
  watch: {
    "$route.query": {
      handler({ objectName }) {
        if (this.$route?.path.includes("/batch-import")) {
          if (objectName === "DICTIONARY_DATA") {
            localStorage.setItem("dictCode", this.dictForm.dictCode);
          }
        } else if (this.$route?.path.includes("system/setting/dictionar")) {
          this.dictForm.dictCode = localStorage.getItem("dictCode")
            ? localStorage.getItem("dictCode")
            : "";
          if (this.dictForm.dictCode) {
            this.getAllDictData();
          }
        }
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    this.getAllStatusList();
    // 初始化字典数据
    this.initDictData();
  },
  methods: {
    tableChange(pagination, filters, sorter) {
      const { current, pageSize } = pagination;
      if (pageSize !== this.$store.state.pagination.pageSize) {
        this.$store.state.pagination.pageSize = pageSize;
        this.leftTablePage = 1;
      } else {
        this.leftTablePage = current;
        this.selectIndex = null;
      }
      this.searchPageData();
    },
    formatData(data, status) {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
    // 下载模板
    handleDownload() {
      const a = document.createElement("a");
      a.href = "/template/DICTIONARY_DATA.xlsx";
      a.click();
    },
    // 导入
    handleImport() {
      this.$refs.iUploadModal.init();
    },
    // 导出
    handleExportExcel() {
      this.$axios({
        url: `${ApiConstant.PREFIX_CORE}/api/sys/dict/export`,
        method: "get",
        params: {
          page: this.leftTablePage,
          size: this.$store.state.pagination.pageSize,
          ...this.queryForm,
        },
        responseType: "blob",
      }).then((res) => {
        exportExcel(res.data, `${this.$t("DICTIONARY")}.xls`);
      });
    },
    // 初始化字典数据
    initDictData() {
      // 字典分类
      this.getDictByCode("DIC:CORE:DIC_CATEGORY").then((res) => {
        if (res.data.data && res.data.data.length > 0) {
          this.dictCategoryList = res.data.data;
          this.queryFormItem.dictCategory.options = res.data.data;
          this.dictForm.dictCategory = res.data.data[0].value;
        }
      });
    },
    /**
     * 请求状态的字典表
     */
    getAllStatusList() {
      this.getDictByCode("DIC:COMMON:ENABLE_FLAG").then((res) => {
        if (res.data.data && res.data.data.length > 0) {
          this.dictChildForm.enableFlag = res.data.data[0].value;
          this.enableFlagList = res.data.data;
          this.stateList = res.data.data;
        }
      });
    },
    queryFilterSearch() {
      this.leftTablePage = 1;
      this.searchPageData("isQuery");
    },
    /**
     *获取左侧字典分页数据
     */
    searchPageData(val) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/dict/search`, {
          params: {
            page: this.leftTablePage,
            size: this.$store.state.pagination.pageSize,
            ...this.queryForm,
          },
        })
        .then((res) => {
          this.leftTableData = res.data.data.records;
          this.leftTableTotal = res.data.data.total;
          if (val === "isQuery") {
            if (res.data?.data?.records.length === 0) {
              this.rightTableData = [];
            }
          }
        });
    },
    /**
     * 左侧字典点击事件
     */
    rowClick(row, column, event) {
      return {
        on: {
          click: () => {
            this.selectIndex = column;
            this.dictForm.dictCode = row.dictCode;
            this.dictChildForm.dictCode = row.dictCode;
            this.dictChildForm.parentDictCode = row.dictCode;
            this.dictCategory = row.dictCategory;
            this.getAllDictData();
          },
        },
      };
    },
    /**
     * 获取右侧所有子字典的数据
     */
    getAllDictData(sortParams) {
      this.$axios({
        url: `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/list`,
        method: "get",
        params: {
          // eslint-disable-next-line no-nested-ternary
          dictCode: this.dictForm.dictCode
            ? this.dictForm.dictCode === undefined
              ? ""
              : this.dictForm.dictCode
            : "",
          ...sortParams,
        },
      }).then((res) => {
        this.rightTableData = res.data.data;
      });
    },
    // 新增、字典
    addMDict() {
      this.title = this.$t("ADD");
      this.parentDictName = "";
      this.dictForm.dictName = "";
      this.dictForm.dictCode = "";
      if (this.dictCategoryList.length > 0) {
        this.dictForm.dictCategory = this.dictCategoryList[1].value;
      } else {
        this.dictForm.dictCategory = "U";
      }
      this.dictForm.remark = "";
      this.drawer = true;
    },
    // 编辑字典
    editDict(data) {
      // 普通用户不能编辑系统类型的字典
      if (data.dictCategory === "S" && this.user?.mgrType === "USER") {
        this.$message.error(this.$t("EDITDELNOJURISDICTION"));
        return;
      }
      this.title = "编辑字典";
      this.title = this.$t("EDIT");
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/dict/get-by-id/${data.id}`)
        .then((res) => {
          // eslint-disable-next-line
          const { data } = res.data;
          this.id = data.id;
          this.dictForm.dictCode = data.dictCode;
          this.dictForm.dictName = data.dictName;
          this.dictForm.dictCategory = data.dictCategory;
          this.dictForm.remark = data.remark;
        });
      this.drawer = true;
    },
    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.parentDictName = "";
            this.$axios
              .delete(`${ApiConstant.PREFIX_CORE}/api/sys/dict/batch-delete`, {
                params: {
                  ids: this.selectedRowKeys.join(","),
                },
              })
              .then((res) => {
                this.$message.success(this.$t("DELETE_SUCCESS"));
                this.leftTablePage = 1;
                this.rightTableData = [];
                this.dictForm.dictCode = "";
                this.dictForm.dictName = "";
                this.dictForm.dictCategory = "";
                this.dictForm.remark = "";
                this.searchPageData();
              });
          },
        });
      } else {
        this.$message.error(this.$t("SELECT_ONE_DATA"));
      }
    },
    // 删除字典
    async delDict(data) {
      // 普通用户不能删除系统类型的字典
      if (data.dictCategory === "S" && this.user?.mgrType === "USER") {
        this.$message.error(this.$t("EDITDELNOJURISDICTION"));
        return;
      }
      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.parentDictName = "";
          this.$axios
            .delete(`${ApiConstant.PREFIX_CORE}/api/sys/dict/${data.id}`)
            .then((res) => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.leftTablePage = 1;
              this.rightTableData = [];
              this.dictForm.dictCode = "";
              this.dictForm.dictName = "";
              this.dictForm.dictCategory = "";
              this.dictForm.remark = "";
              this.searchPageData();
            });
        },
      });
    },
    // 类型切换时清空 编码数据
    typeChange() {
      this.dictForm.dictCode = "";
    },
    // 新增子字典（右侧数据）
    addChildDict() {
      this.drawerChild = true;
      this.title = this.$t("ADD");
      this.dictChildForm.dataLabel = "";
      this.dictChildForm.dataValue = "";
      if (this.enableFlagList.length > 0) {
        this.dictChildForm.enableFlag = this.enableFlagList[0].value;
      } else {
        this.dictChildForm.enableFlag = "Y";
      }
      this.dictChildForm.dataValueExt1 = "";
      this.dictChildForm.dataValueExt2 = "";
      this.dictChildForm.dataOrder = "";
      this.dictChildForm.remark = "";
      this.dictChildForm.dataCategory = "U";
    },
    // 编辑子字典（右侧数据）
    editChildDict(row) {
      // 普通用户不能编辑系统类型的字典
      if (this.dictCategory === "S" && this.user?.mgrType === "USER") {
        this.$message.error(this.$t("EDITDELNOJURISDICTION"));
        return;
      }
      this.drawerChild = true;
      this.title = this.$t("EDIT");
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/dict-data/get-by-id/${row.id}`)
        .then((res) => {
          const { data } = res.data;
          this.id = data.id;
          this.dictChildForm.dictCode = data.dictCode;
          this.dictChildForm.dataLabel = data.dataLabel;
          this.dictChildForm.dataValue = data.dataValue;
          this.dictChildForm.enableFlag = data.enableFlag;
          this.dictChildForm.dataOrder = data.dataOrder;
          this.dictChildForm.dataValueExt1 = data.dataValueExt1;
          this.dictChildForm.dataValueExt2 = data.dataValueExt2;
          this.dictChildForm.remark = data.remark;
          this.dictChildForm.dataCategory = data.dataCategory;
        });
    },
    disableChildDictLeft(row, state) {
      let title = "";
      let content = "";
      if (state === "N") {
        content = this.$t("DISABLED_DATA_INFO");
        title = this.$t("DISABLED");
      } else {
        content = this.$t("ENABLED_DATA_INFO");
        title = this.$t("ENABLED");
      }
      this.$confirm({
        title,
        content,
        okType: "warning",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "exclamation-circle",
        onOk: () => {
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/sys/dict/enable/${row.id}/${state}`
            )
            .then(() => {
              if (state === "N") {
                this.$message.success(this.$t("DISABLE_SUCCESS"));
              } else {
                this.$message.success(this.$t("ENABLE_SUCCESS"));
              }
              this.searchPageData();
            });
        },
      });
    },
    // 禁用子字典（右侧数据）
    disableChildDict(row, state) {
      let title = "";
      let content = "";
      if (state === "N") {
        content = this.$t("DISABLED_DATA_INFO");
        title = this.$t("DISABLED");
      } else {
        content = this.$t("ENABLED_DATA_INFO");
        title = this.$t("ENABLED");
      }
      this.$confirm({
        title,
        content,
        okType: "warning",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "exclamation-circle",
        onOk: () => {
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/enable/${row.id}/${state}`
            )
            .then(() => {
              if (state === "N") {
                this.$message.success(this.$t("DISABLE_SUCCESS"));
              } else {
                this.$message.success(this.$t("ENABLE_SUCCESS"));
              }
              this.getAllDictData();
            });
        },
      });
    },
    async handRightDelete() {
      // 普通用户不能删除系统类型的字典
      if (this.dictCategory === "S" && this.user?.mgrType === "USER") {
        this.$message.error(this.$t("EDITDELNOJURISDICTION"));
        return;
      }
      if (this.selectedRightRowKeys.length > 0) {
        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/dict-data/batch-delete`,
                {
                  params: {
                    ids: this.selectedRightRowKeys.join(","),
                  },
                }
              )
              .then(() => {
                this.$message.success(this.$t("DELETE_SUCCESS"));
                this.getAllDictData();
              });
          },
        });
      } else {
        this.$message.error(this.$t("SELECT_ONE_DATA"));
      }
    },
    // 删除子字典（右侧数据）
    async delChildDict(row) {
      // 普通用户不能删除系统类型的字典
      if (this.dictCategory === "S" && this.user?.mgrType === "USER") {
        this.$message.error(this.$t("EDITDELNOJURISDICTION"));
        return;
      }
      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/dict-data/${row.id}`)
            .then(() => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.getAllDictData();
            });
        },
      });
    },
    // eslint-disable-next-line
    async confirm() {
      const valid = await this.$refs.dictForm.validate();
      if (!valid) {
        return false;
      }
      try {
        if (this.title === this.$t("EDIT")) {
          await this.$axios.put(`${ApiConstant.PREFIX_CORE}/api/sys/dict`, {
            ...this.dictForm,
            id: this.id,
          });
          this.$message.success(this.$t("EDIT_SUCCESS"));
        } else {
          // 添加左侧字典数据
          await this.$axios.post(`${ApiConstant.PREFIX_CORE}/api/sys/dict`, {
            ...this.dictForm,
          });
          this.$message.success(this.$t("ADD_SUCCESS"));
        }
        this.drawer = false;
        this.leftTablePage = 1;
        await this.searchPageData();
        await this.getAllDictData();
      } catch (err) {}
    },
    // eslint-disable-next-line
    async confirmChild() {
      // eslint-disable-next-line no-unused-expressions
      this.dictForm.dictCode
        ? (this.dictChildForm.dictCode = this.dictForm.dictCode)
        : "";
      const valid = await this.$refs.dictChildForm.validate();
      if (!valid) {
        return false;
      }
      try {
        if (this.title === this.$t("EDIT")) {
          await this.$axios.put(
            `${ApiConstant.PREFIX_CORE}/api/sys/dict-data`,
            {
              ...this.dictChildForm,
              id: this.id,
            }
          );
          this.$message.success(this.$t("EDIT_SUCCESS"));
        } else {
          await this.$axios.post(
            `${ApiConstant.PREFIX_CORE}/api/sys/dict-data`,
            this.dictChildForm
          );
          this.$message.success(this.$t("ADD_SUCCESS"));
        }
        this.drawerChild = false;
        this.leftTablePage = 1;
        await this.searchPageData();
        await this.getAllDictData();
      } catch (err) {}
    },
    // 取消
    cancel() {
      this.drawer = false;
    },
    // 取消
    cancelChild() {
      this.drawerChild = false;
    },
    // 关闭
    drawerClose() {
      this.$refs.dictForm.resetFields();
      this.cancel();
    },
    // 关闭
    drawerCloseChild() {
      this.$refs.dictChildForm.resetFields();
      this.cancelChild();
    },
  },
};
</script>

<style lang="less" scoped>
/deep/ .main_box {
  display: flex;
  .main_left {
    width: 450px;
    .mega-design-pro-table {
      padding-right: 0;
    }
    .ant-table-row-cell-ellipsis {
      cursor: pointer;
    }
  }
  .main_right {
    width: calc(100% - 465px);
  }
  .clickRowStyle {
    background-color: #ecf6fd;
  }
}
.ant-drawer-content-wrapper {
  .ant-drawer-body {
    position: relative;
    .drawer_btns {
      position: absolute;
      left: 50%;
      bottom: 80px;
      transform: translateX(-50%);
    }
  }
}
.system-divide-bg {
  border-bottom: 10px solid #f0f2f5;
}
</style>
