<template>
  <div class="box-main">
    <MomTable
      ref="MomTable"
      :loading="loading"
      :columns="tableColumns"
      :data-source="tableData"
      :mega-extend="{
        rowIndex: true,
      }"
      :query-param="queryForm"
      :query-param-item="queryFormItem"
      row-key="id"
      :page.sync="page"
      :total="total"
      :action-buttons="actionButtons"
      @beforeSearch="beforeSearch"
      @search="searchPageData"
      @expandedRowsChange="exchangeRow"
      @expand="expandFunc"
    >
      <template slot="dataType" slot-scope="text, record">
        <span>{{ $t(formatData(typeList, record.dataType)) }}</span>
      </template>
      <template slot="pushStatus" slot-scope="text, record">
        <span>{{ formatData(stateList, record.pushStatus) }}</span>
      </template>
      <template slot="receiveStatus" slot-scope="text, record">
        <span>{{ formatData(stateList, record.receiveStatus) }}</span>
      </template>
      <template slot="targetSystemCode" slot-scope="text, record">
        <span>{{ formatData(menuAllList, record.targetSystemCode) }}</span>
      </template>
      <template slot="eventType" slot-scope="text">
        <span>
          {{ getAttrValue(eventTypeList, text) }}
        </span>
      </template>
      <template slot="deleteFlag" slot-scope="text">
        <span>
          {{ getAttrValue(deleteFlayList, text) }}
        </span>
      </template>
    </MomTable>
  </div>
</template>

<script>
import { Icon } from "@mega-design/ui-vue";
import { getToken } from "@/utils/auth";
import ApiConstant from "@/api/ApiConstant";

export default {
  name: "Material",
  components: {
    // eslint-disable-next-line vue/no-unused-components
    Icon,
  },
  data() {
    return {
      eventTypeList: [],
      loading: false,
      // 查询的表单的配置项
      queryForm: {
        dataType: "",
        eventType: "",
        pushStatus: "",
        receiveStatus: "",
      },
      sortParams: null,
      // 表格的配置项
      tableData: [],
      page: 1, // 页码
      total: 0,
      typeList: [],
      stateList: [],
      menuAllList: [],
      actionButtons: [
        (h, value, a, b) => (
          <div>
            {(value.record.pushStatus === "FAIL" ||
              value.record.receiveStatus === "FAIL" ||
              value.record.receiveStatus === "PENDING") &&
              // eslint-disable-next-line no-prototype-builtins
              !value.record.hasOwnProperty("children") && (
                <span
                  type="text"
                  onClick={() => this.handleEvent(value.record)}
                >
                  <Icon
                    type="icon-cur-reload"
                    size={15}
                    style="color:#01baea;cursor: pointer;"
                    title={this.$t("REPUSH")}
                  />
                </span>
              )}
          </div>
        ),
      ],
    };
  },
  computed: {
    queryFormItem() {
      return this.$observable("queryFormItem", {
        dataType: {
          label: () => this.$t("DATA_TYPE"), // 数据类型
          itemType: "custom",
          customRender: () => {
            return (
              <a-select
                v-model={this.queryForm.dataType}
                allow-clear
                placeholder={this.$t("PLACEENTER")}
              >
                {this.typeList.map((item) => (
                  <a-select-option key={item.value} value={item.value}>
                    {this.$t(item.label)}
                  </a-select-option>
                ))}
              </a-select>
            );
          },
        },
        eventType: {
          label: () => this.$t("EVENT_TYPE"), // 事件类型
          itemType: "select",
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
        },
        pushStatus: {
          label: () => this.$t("PUSH_STATUS"), // 推送状态
          itemType: "select",
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
        },
        receiveStatus: {
          label: () => this.$t("RECEIVING_STATUS"), // 接收状态
          itemType: "select",
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
        },
      });
    },
    tableColumns() {
      return [
        {
          dataIndex: "dataType",
          key: "dataType",
          title: () => this.$t("DATA_TYPE"),
          width: 120,
          scopedSlots: { customRender: "dataType" },
          ellipsis: true,
        },
        {
          dataIndex: "eventType",
          title: () => this.$t("EVENT_TYPE"),
          width: 120,
          scopedSlots: { customRender: "eventType" },
          ellipsis: true,
        },
        {
          dataIndex: "dataId",
          title: () => this.$t("DATA_CODEING"),
          width: 220,
          ellipsis: true,
          sorter: false,
        },
        {
          dataIndex: "targetSystemCode",
          title: () => this.$t("SYSTEM_NAME"),
          scopedSlots: { customRender: "targetSystemCode" },
          width: 150,
          ellipsis: true,
          sorter: false,
        },
        {
          dataIndex: "itemNum",
          key: "itemNum",
          title: () => this.$t("PUSH_NUM"),
          scopedSlots: { customRender: "itemNum" },
          width: 120,
          ellipsis: true,
          sorter: false,
        },
        {
          dataIndex: "pushStatus",
          key: "pushStatus",
          title: () => this.$t("PUSH_STATUS"),
          scopedSlots: { customRender: "pushStatus" },
          width: 120,
          ellipsis: true,
        },
        {
          dataIndex: "receiveStatus",
          key: "receiveStatus",
          title: () => this.$t("RECEIVING_STATUS"),
          scopedSlots: { customRender: "receiveStatus" },
          options: [],
          width: 120,
          ellipsis: true,
        },
        {
          dataIndex: "deleteFlag",
          title: () => this.$t("IF_DELETE"),
          minWidth: 120,
          options: [],
          scopedSlots: { customRender: "deleteFlag" },
          ellipsis: true,
        },
        {
          dataIndex: "pushFailReason",
          title: () => this.$t("PUSH_FAIL_REASON"),
          options: [],
          width: 300,
          ellipsis: true,
          sorter: false,
        },
        {
          dataIndex: "receiveFailReason",
          title: () => this.$t("RECEIVING_FAIL_STATUS"),
          minWidth: 300,
          options: [],
          ellipsis: true,
          sorter: false,
        },
        {
          dataIndex: "updateBy", // 更新人员
          title: () => this.$t("UPDATE_BY"),
          width: 120,
          ellipsis: true,
        },
        {
          dataIndex: "updateTime", // 更新时间
          title: () => this.$t("UPDATE_TIME"),
          width: 168,
          ellipsis: true,
        },
      ];
    },
  },
  created() {
    this.init();
  },
  methods: {
    expandFunc(expanded, record) {
      const num = this.tableData.findIndex((item) => {
        return item.id === record.id;
      });
      const params = {
        pushId: record.id,
      };
      if (expanded) {
        this.$axios
          .get(`${ApiConstant.PREFIX_CORE}/api/data-push-history-item/list`, {
            params,
          })
          .then((res) => {
            if (res.data.success) {
              this.tableData[num].children = res.data.data;
            }
          });
      }
    },
    exchangeRow(expandedRows) {},
    // 查询数据字典
    beforeSearch() {
      return Promise.all([
        this.getDictByCode(`DIC:CORE:EVENT_TYPE`), // 状态
        this.getDictByCode(`DIC:CORE:DATA_DELETE_FLAG`),
      ]).then(([enableStatusRes, deleteFlayRes]) => {
        this.eventTypeList = enableStatusRes.data.data;
        this.deleteFlayList = deleteFlayRes.data.data;
      });
    },
    formatData(data, status) {
      const result = data.find((item) => item.value === String(status));
      return result ? result.label : "";
    },
    init() {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/data-push-config/get-data-type-list`
        )
        .then((res) => {
          this.typeList = res.data.data.map((item) => {
            return {
              label: item.i18nCode,
              value: item.code,
            };
          });
        });
      this.getDictByCode("DIC:CORE:EVENT_TYPE").then((res) => {
        this.queryFormItem.eventType.options = res.data.data;
      });
      this.getDictByCode("DIC:CORE:SUB_SYSTEM").then((res) => {
        this.menuAllList = res.data.data;
        this.queryFormItem.systemCode.options = res.data.data;
      });
      this.getDictByCode("DIC:CORE:SYS_DATA_PUSH_STATUS").then((res) => {
        this.queryFormItem.pushStatus.options = res.data.data;
        this.queryFormItem.receiveStatus.options = res.data.data;
        this.stateList = res.data.data;
      });
    },
    handleEvent(row) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/data-push-history-item/retry`, {
          params: { id: row.id },
        })
        .then((res) => {
          this.$message.success(this.$t("TIPS:COMMON:RETRY_SUCCESS"));
          this.$refs.MomTable?.query();
        });
    },
    // 后台分页查询
    searchPageData(data) {
      this.tableData = [];
      this.loading = true;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/data-push-history/search`, {
          params: data,
          headers: {
            Authorization: getToken(),
            tenantId:
              this.$store.state.app.systemConfig.TENANT_OPEN === "true"
                ? this.$store.state.account.tenantId
                : "",
          },
        })
        .then((res) => {
          this.loading = false;
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
  },
};
</script>
