<template>
  <div class="box-main">
    <MomTable
      ref="MomTable"
      :row-selection="rowSelection"
      :columns="tableColumns"
      :data-source="tableData"
      :query-param="queryForm"
      :query-param-item="queryFormItem"
      row-key="id"
      :total="total"
      :page.sync="page"
      :action-buttons="tableAction"
      :show-enable-flag="true"
      @copy="handleCopy"
      @edit="handleEdit"
      @delete="handleDelete"
      @beforeSearch="beforeSearch"
      @search="searchPageData"
      @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'
          )
      "
    >
      <a-row slot="toolbar" class="button-top-table">
        <a-button v-if="hasAuth('CODE_MANAGEMENT:ADD')" @click="handleAdd">
          <a-icon type="plus" />{{ $t("ADD") }}
        </a-button>
        <a-button
          v-if="hasAuth('CODE_MANAGEMENT:BATCH_DELETE')"
          type="danger"
          icon="delete"
          @click="handDelete"
        >
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </a-row>
      <div slot="enableFlag" slot-scope="text, record">
        <span
          :style="
            record.enableFlag == 'Y' ? 'color: #0fd19c' : 'color: #d45f5f'
          "
          >{{ formatData(stateList, record.enableFlag) }}</span
        >
      </div>
    </MomTable>
  </div>
</template>

<script>
import ApiConstant from "@/api/ApiConstant";

export default {
  data() {
    return {
      tableData: [],
      sortParams: null,
      page: 1, // 页码
      total: 20, // 每页个数
      title: "", // 弹框的标题
      // 查询的表单的配置项
      queryForm: {
        ruleCode: "",
        ruleName: "",
      },
      dialogFormVisible: false,
      isEdit: false,
      defaultList: [],
      tableAction: [
        this.hasAuth("CODE_MANAGEMENT:COPY") && "copy",
        this.hasAuth("CODE_MANAGEMENT:EDIT") && "edit",
        this.hasAuth("CODE_MANAGEMENT:DELETE") && "delete",
      ],
      selectedRowKeys: [],
    };
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    queryFormItem() {
      return this.$observable("queryFormItem", {
        ruleCode: {
          label: () => this.$t("RULE_CODE"), // 规则编码
          isRequired: false,
        },
        ruleName: {
          label: () => this.$t("RULE_NAME"), // 规则名称
          isRequired: false,
        },
      });
    },
    // 表格的配置项
    tableColumns() {
      return [
        {
          dataIndex: "ruleCode",
          minWidth: 300,
          title: () => this.$t("RULE_CODE"), // 规则编码
        },
        {
          dataIndex: "ruleName",
          minWidth: 250,
          title: () => this.$t("RULE_NAME"), // 规则名称
        },
        {
          dataIndex: "enableFlag",
          sorter: false,
          width: 80,
          title: () => this.$t("STATUS"), // 状态
          scopedSlots: { customRender: "enableFlag" },
        },
        {
          dataIndex: "updateBy", // 更新人员
          title: () => this.$t("UPDATE_BY"),
          width: 120,
          sorter: false,
        },
        {
          dataIndex: "updateTime", // 更新时间
          title: () => this.$t("UPDATE_TIME"),
          width: 168,
          sorter: false,
        },
      ];
    },
  },
  methods: {
    beforeSearch() {
      this.getDictByCode("DIC:COMMON:ENABLE_FLAG").then((res) => {
        this.stateList = res?.data?.data || [];
      });
    },
    handleCopy(row) {
      this.$router.push({
        path: "/upms/system/setting/codeRules/add",
        query: {
          id: row.id,
        },
      });
    },
    // 格式化数据
    formatData(data, status) {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
    // 启用、禁用
    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/code-rule/enable/${id}/${status}`
            )
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 后台分页查询
    searchPageData(data) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/code-rule/search`, {
          params: data,
        })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
    // 点击新增
    handleAdd() {
      this.$router.push({
        path: "/upms/system/setting/codeRules/add",
      });
    },
    // 点击表格行内的编辑
    handleEdit(row) {
      this.$router.push({
        path: "/upms/system/setting/codeRules/edit",
        query: {
          id: row.id,
        },
      });
    },
    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/code-rule/batch-delete`,
                {
                  params: {
                    ids: this.selectedRowKeys.join(","),
                  },
                }
              )
              .then((res) => {
                this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
                this.$refs.MomTable?.query();
              });
          },
        });
      } else {
        this.$message.error(this.$t("SELECT_ONE_DATA"));
      }
    },
    // 点击表格行内的删除
    handleDelete(row) {
      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/code-rule/${row.id}`)
            .then((res) => {
              this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
  },
};
</script>
