<template>
  <div class="box-main">
    <MomTable
      ref="MomTable"
      row-key="id"
      :columns="tableColumns"
      :data-source="tableData"
      :query-param="queryForm"
      :query-param-item="queryFormItem"
      :total="total"
      :page.sync="page"
      :action-buttons="tableAction"
      :mega-extend="{
        rowAction: false,
      }"
      @search="searchPageData"
    >
      <template slot="messageType" slot-scope="text, record">
        {{ formatData(typeList, record.messageType) }}
      </template>
      <template slot="content" slot-scope="text, record">
        <a-button type="link" @click="handleViewContent(record)">{{
          $t("VIEW")
        }}</a-button>
      </template>
      <template slot="receiver" slot-scope="text, record">
        <a-button type="link" @click="handleView(record)">{{
          $t("VIEW")
        }}</a-button>
      </template>
      <template slot="error" slot-scope="text, record">
        <a-button
          v-if="record.sendStatus !== 'S'"
          type="link"
          @click="handleViewError(record)"
          >{{ $t("VIEW") }}</a-button
        >
      </template>
      <template slot="sendStatus" slot-scope="text, record">
        <span v-if="record.sendStatus == 'F'" style="color: #d45f5f">{{
          formatData(statusList, record.sendStatus)
        }}</span>
        <span v-else style="color: #0fd19c">{{
          formatData(statusList, record.sendStatus)
        }}</span>
      </template>
      <a-row slot="toolbar" class="button-top-table"> </a-row>
    </MomTable>
    <MegaModal
      :visible="modalVisible"
      :centered="true"
      :mask-closable="false"
      :width="760"
      :title="megaModalTitle"
      @cancel="handleCloseConfigDrawer"
      @ok="modalVisible = false"
    >
      <div
        v-if="showType === 1"
        class="content"
        v-html="content || error"
      ></div>
      <MomTable
        v-else
        ref="MomTableDrawer"
        row-key="id"
        :columns="tableColumnsReceiver"
        :data-source="tableDataReceiver"
        :mega-extend="{
          rowAction: false,
        }"
      >
      </MomTable>
      <template slot="footer">
        <a-button type="primary" @click="handleCloseConfigDrawer">{{
          $t("CONFIRM")
        }}</a-button>
      </template>
    </MegaModal>
  </div>
</template>
<script>
import { Modal as MegaModal, Icon } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";

export default {
  components: {
    MegaModal,
    // eslint-disable-next-line vue/no-unused-components
    Icon,
  },
  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 {
      title: "", // 弹框标题
      drawerVisible: false, // 新增修改的弹框
      drawerVisibleView: false, // 查看弹框
      modalVisible: false,
      // 查询sort
      tableData: [], // 表格数据
      page: 1, // 分页第几页
      total: 0, // 数据表格总条数
      form: {
        id: "",
        serverCode: "",
        serverName: "",
        authType: "",
        enterpriseId: "",
        appId: "",
        appSecret: "",
        authAddress: "",
        status: "",
      },
      checkedStatus: true,
      rules: {
        serverCode: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        serverName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        smsSign: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        serverType: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        accessKey: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
      },
      rulesConfig: {
        propertyCode: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        propertyValue: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
      },
      typeList: [], // 服务类型列表
      statusList: [], // 状态列表
      // 查询的表单的配置项
      queryForm: {
        messageType: "",
        status: "",
        subject: "",
        serverCode: "",
      },
      actionButtons: [this.hasAuth("CORE:MESSAGE:MONITOR:RECEIVER") && "retry"],
      tableAction: [
        (h, value, a, b) => (
          <a-button type="text" onClick={() => this.handleView(value)}>
            <Icon
              type="icon-cur-team"
              class="icon-ren operation-icon"
              size={20}
              title={this.$t("RECEIVER")}
            />
          </a-button>
        ),
      ],
      content: "", // 消息内容
      error: "", // 错误
      megaModalTitle: this.$t("CONTENT"),
      tableDataReceiver: [],
      showType: "", // 显示类型，1: 内容, 错误, 2: 接收人
    };
  },
  computed: {
    queryFormItem() {
      return this.$observable("queryFormItem", {
        messageType: {
          itemType: "select",
          label: () => this.$t("TYPE"), // 类型
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
        },
        status: {
          itemType: "select",
          label: () => this.$t("STATUS"), // 状态
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
        },
        subject: {
          label: () => this.$t("THEME"),
        },
        serverCode: {
          label: () => this.$t("ACCOUNT_CODE"),
        },
      });
    },
    tableColumns() {
      return [
        {
          dataIndex: "serverCode",
          sorter: false,
          title: this.$t("ACCOUNT_CODE"),
          minWidth: 210,
        },
        {
          dataIndex: "messageType",
          title: () => this.$t("TYPE"),
          scopedSlots: { customRender: "messageType" },
          minWidth: 200,
        },
        {
          dataIndex: "subject",
          title: this.$t("THEME"),
          width: 210,
        },
        {
          dataIndex: "content",
          title: () => this.$t("CONTENT"),
          scopedSlots: { customRender: "content" },
          sorter: false,
          width: 200,
        },
        {
          dataIndex: "receiver",
          title: () => this.$t("RECEIVER"),
          scopedSlots: { customRender: "receiver" },
          sorter: false,
          width: 200,
        },
        {
          dataIndex: "error",
          title: () => this.$t("ERROR"),
          scopedSlots: { customRender: "error" },
          sorter: false,
          width: 200,
        },
        {
          dataIndex: "sendStatus",
          title: () => this.$t("STATUS"),
          scopedSlots: { customRender: "sendStatus" },
          width: 120,
        },
        // 更新人员
        {
          dataIndex: "updateBy",
          sorter: false,
          title: this.$t("UPDATE_BY"),
          width: 210,
        },
        // 更新时间
        {
          dataIndex: "updateTime",
          sorter: false,
          title: this.$t("UPDATE_TIME"),
          width: 210,
        },
      ];
    },
    tableColumnsReceiver() {
      return [
        {
          dataIndex: "userName",
          title: this.$t("RECEIVER"),
          minWidth: 210,
        },
        {
          dataIndex: "receiverAddress",
          title: this.$t("RECEIVER_ADDRESS"),
          minWidth: 210,
        },
        // 更新人员
        {
          dataIndex: "updateBy",
          title: this.$t("UPDATE_BY"),
          width: 210,
        },
        // 更新时间
        {
          dataIndex: "updateTime",
          title: this.$t("UPDATE_TIME"),
          width: 210,
        },
      ];
    },
  },
  mounted() {
    this.queryDictData();
  },
  methods: {
    queryDictData() {
      return Promise.all([
        this.getDictByCode(`DIC:MSG:MESSAGE_TYPE`), // 类型
        this.getDictByCode(`DIC:MSG:MESSAGE_STATUS`), // 状态
      ]).then(([typeRes, statusRes]) => {
        this.typeList = typeRes.data.data;
        this.statusList = statusRes.data.data;
        this.queryFormItem.messageType.options = typeRes.data.data;
        this.queryFormItem.status.options = statusRes.data.data;
      });
    },
    formatData(data, curItem) {
      const result = data.find(
        (item) => item.value === curItem && curItem.toString()
      );
      return result ? result.label : "";
    },
    searchPageData(params) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/msg/message/search`, { params })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = parseFloat(res.data.data.total);
        });
    },
    // 关闭弹框
    handleCloseDrawer() {
      this.drawerVisible = false;
    },
    // 点击表格行内的查看
    handleView(row) {
      this.clearCacheData();
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/msg/message/receiver/${row.id}`)
        .then((res) => {
          this.tableDataReceiver = res.data?.data || [];
        });
      this.showType = 2;
      this.megaModalTitle = this.$t("RECEIVER");
      this.modalVisible = true;
    },
    // 点击查看内容
    handleViewContent(row) {
      this.clearCacheData();
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/msg/message/content/${row.id}`)
        .then((res) => {
          this.content = res.data?.data?.content || "";
        });
      this.showType = 1;
      this.megaModalTitle = this.$t("CONTENT");
      this.modalVisible = true;
    },
    // 点击查看错误
    handleViewError(row) {
      this.clearCacheData();
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/msg/message/transaction/${row.id}`)
        .then((res) => {
          this.error = res.data?.data?.errorMessage || "";
        });
      this.showType = 1;
      this.megaModalTitle = this.$t("ERROR");
      this.modalVisible = true;
    },
    clearCacheData() {
      this.content = "";
      this.error = "";
      this.tableDataReceiver = [];
    },
    // 关闭弹框
    handleCloseConfigDrawer() {
      this.modalVisible = 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>
