<template>
  <div class="box-main">
    <MomTable
      ref="MomTable"
      row-key="id"
      :row-selection="rowSelection"
      :columns="tableColumns"
      :data-source="tableData"
      :query-param="queryForm"
      :query-param-item="queryFormItem"
      :total="total"
      :page.sync="page"
      :action-buttons="actionButtons"
      :show-enable-flag="true"
      @edit="handleEdit"
      @delete="handleDelete"
      @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'
          )
      "
    >
      <div slot="toolbar" class="button-top-table">
        <a-button
          v-if="hasAuth('MESSAGE_TEMPLATE:ADD')"
          type="primary"
          @click="handleAdd"
        >
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <a-button
          v-if="hasAuth('MESSAGE_TEMPLATE:BATCH_DELETE')"
          type="danger"
          icon="delete"
          @click="handDelete"
        >
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </div>
      <template slot="lang" slot-scope="text, record">
        <span>{{ formatData(langList, record.lang) }}</span>
      </template>
      <template slot="enableFlag" slot-scope="text">
        <span :class="text === 'Y' ? 'text-success' : 'text-error'">
          {{ getAttrValue(statusList, text) }}
        </span>
      </template>
    </MomTable>
  </div>
</template>
<script>
import ApiConstant from "@/api/ApiConstant";

export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("COMPANY_CREDIT_CODE")));
      } else if (this.form.creditCode !== "") {
        const patrn = /^[0-9A-Z]+$/;
        if (
          patrn.test(this.form.creditCode) === false ||
          this.form.creditCode.length !== 18
        ) {
          callback(new Error(this.$t("COMPANY_CREDIT_CODE")));
        } else {
          callback();
        }
      }
    };
    return {
      // 查询sort
      tableData: [], // 表格数据
      page: 1, // 分页第几页
      total: 0, // 数据表格总条数
      statusList: [], // 状态列表
      langList: [], // 语言列表
      // 查询的表单的配置项
      queryForm: {
        templateCode: "",
        templateName: "",
        lang: "",
      },
      actionButtons: [
        this.hasAuth("MESSAGE_TEMPLATE:EDIT") && "edit",
        this.hasAuth("MESSAGE_TEMPLATE:DELETE") && "delete",
      ],
      selectedRowKeys: [],
    };
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    queryFormItem() {
      return this.$observable("queryFormItem", {
        templateCode: {
          label: () => this.$t("MESSAGE_TEMPLATE_CODE"),
        },
        templateName: {
          label: () => this.$t("MESSAGE_TEMPLATE_NAME"),
        },
        lang: {
          itemType: "select",
          label: () => this.$t("LANGUAGE"), // 语言
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
        },
      });
    },
    tableColumns() {
      return [
        {
          dataIndex: "templateCode",
          title: () => this.$t("MESSAGE_TEMPLATE_CODE"),
          sorter: false,
          width: 210,
        },
        {
          dataIndex: "templateName",
          title: () => this.$t("MESSAGE_TEMPLATE_NAME"),
          minWidth: 260,
        },
        {
          dataIndex: "templateTitle",
          sorter: false,
          title: () => this.$t("MESSAGE_TEMPLATE_TITLE"),
          width: 210,
        },
        {
          dataIndex: "lang",
          sorter: false,
          title: () => this.$t("LANGUAGE"),
          scopedSlots: { customRender: "lang" },
          width: 120,
        },
        {
          dataIndex: "enableFlag",
          sorter: false,
          title: () => this.$t("STATUS"),
          scopedSlots: { customRender: "enableFlag" },
          width: 120,
        },
        // 更新人员
        {
          dataIndex: "updateBy",
          sorter: false,
          title: () => this.$t("UPDATE_BY"),
          width: 210,
        },
        // 更新时间
        {
          dataIndex: "updateTime",
          sorter: false,
          title: () => this.$t("UPDATE_TIME"),
          width: 210,
        },
      ];
    },
  },
  mounted() {
    this.queryDictData();
  },
  methods: {
    queryDictData() {
      return Promise.all([
        this.getDictByCode(`DIC:COMMON:ENABLE_FLAG`), // 启用状态
        this.getDictByCode(`DIC:MSG:TEMPLATE_LANG`), // 语言列表
      ]).then(([enableStatusRes, languageRes]) => {
        this.statusList = enableStatusRes.data.data;
        this.langList = languageRes.data.data;
        this.queryFormItem.lang.options = languageRes.data.data;
      });
    },
    formatData(data, curItem) {
      const result = data.find((item) => item.value === curItem);
      return result ? result.label : "";
    },
    searchPageData(params) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/msg/template/search`, { params })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = parseFloat(res.data.data.total);
        });
    },
    // 新增按钮的点击
    handleAdd() {
      this.$router.push({
        path: "/upms/service/message/messageTemplate/add",
      });
    },
    // 编辑按钮点击
    handleEdit(row) {
      this.$router.push({
        path: "/upms/service/message/messageTemplate/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/msg/template/batch-delete`,
                {
                  params: {
                    ids: this.selectedRowKeys.join(","),
                  },
                }
              )
              .then((res) => {
                this.$message.success(this.$t("DELETE_SUCCESS"));
                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/msg/template/${row.id}`)
            .then((res) => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 启用、禁用
    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/msg/template/enable/${id}/${status}`
            )
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 关闭弹框
    handleCloseDrawer() {
      this.$refs.addForm.clearValidate();
      this.drawerVisible = false;
    },
  },
};
</script>
<style lang="scss" scoped>
/deep/ .mega-design-drawer__footer {
  border-top: none;
  button:last-child {
    margin-left: 10px;
    i {
      margin-right: 5px;
    }
  }
}
</style>
