<template>
  <div class="tenant">
    <MomTable
      ref="MomTable"
      row-key="id"
      :columns="tableColumns"
      :data-source="tableData"
      :query-param="queryParam"
      :query-param-item="queryFormItem"
      :action-buttons="actionButtons"
      :total="total"
      :page.sync="page"
      :show-enable-flag="true"
      :mega-extend="{
        rowAction: {
          width: 150,
        },
      }"
      @beforeSearch="beforeSearch"
      @search="searchPageData"
      @edit="handleEdit"
      @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('TENANT_MANAGEMENT:ADD')" @click="handleAdd">
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <a-button
          v-if="hasAuth('TENANT_MANAGEMENT:EXPORT')"
          class="btn__green-1"
          icon="to-top"
          :disabled="!tableData.length"
          @click="handleExportExcel"
        >
          {{ $t("EXPORT") }}
        </a-button>
        <a-button
          v-if="hasAuth('TENANT_MANAGEMENT:UPDATE_OPEN_PLATFORM_DATA')"
          @click="handUpdate"
        >
          <a-icon type="redo" /> {{ $t("SYNC") }}
        </a-button>
      </a-row>
      <span slot="source" slot-scope="text, record">
        {{ formatData(tenastSource, record.source) }}
      </span>
      <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";
import { exportExcel } from "@/utils/index";

export default {
  data() {
    return {
      tableData: [],
      page: 1, // 页码
      total: 0, // 每页个数
      // 表格的配置项
      tableColumns: [
        {
          dataIndex: "tenantName",
          minWidth: 200,
          ellipsis: true,
          title: () => this.$t("TENANT_NAME"), // 租户名称
        },
        {
          dataIndex: "tenantAdminName",
          width: 220,
          ellipsis: true,
          sorter: false,
          title: () => this.$t("TENANT_ADMINISTRATOR"), // 租户管理员
        },
        {
          dataIndex: "source",
          width: 220,
          sorter: false,
          ellipsis: true,
          title: () => this.$t("COMPONENT_SOURCE"), // 来源
          scopedSlots: { customRender: "source" },
        },
        {
          dataIndex: "enableFlag",
          sorter: false,
          ellipsis: true,
          width: 80,
          title: () => this.$t("STATUS"), // 状态
          scopedSlots: { customRender: "enableFlag" },
        },
        {
          dataIndex: "updateTime", // 更新时间
          title: () => this.$t("UPDATE_TIME"),
          ellipsis: true,
          width: 200,
        },
      ],
      // 查询的表单的配置项
      queryParam: {
        tenantName: "",
      },
      stateList: [],
      tenastSource: [],
      actionButtons: [this.hasAuth("TENANT_MANAGEMENT:EDIT") && "edit"],
    };
  },
  computed: {
    // 表格搜索配置
    queryFormItem() {
      return this.$observable("queryFormItem", {
        tenantName: {
          itemType: "input",
          label: () => this.$t("TENANT_NAME"), // 租户名称
        },
      });
    },
  },
  methods: {
    beforeSearch() {
      this.getDictByCode("DIC:CORE:TENANT_SOURCE").then((res) => {
        this.tenastSource = res.data.data;
      });
      this.getDictByCode("DIC:COMMON:ENABLE_FLAG").then((res) => {
        this.stateList = res?.data?.data || [];
      });
    },
    // 启用、禁用
    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/tenant/enable/${id}/${status}`
            )
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 后台分页查询
    searchPageData(params) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/tenant/search`, {
          params: {
            ...params,
          },
        })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
    // 格式化数据
    formatData(data, status) {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
    // 点击新增
    handleAdd() {
      this.$router.push({
        path: "/upms/system/setting/tenant/add",
      });
    },
    handUpdate() {
      this.$axios
        .put(`${ApiConstant.PREFIX_CORE}/api/sys/tenant/refresh-tenant`)
        .then((res) => {
          this.$message.success(this.$t("SYNC_SUCCESS"));
        });
    },
    // 导出
    handleExportExcel() {
      const params = {
        page: this.page,
        size: this.$store.state.pagination.pageSize,
        ...this.queryParam,
      };
      this.$axios({
        url: `${ApiConstant.PREFIX_CORE}/api/sys/tenant/export`,
        method: "get",
        params,
        responseType: "blob",
      }).then((res) => {
        exportExcel(res.data, `${this.$t("TENANT_MANAGEMENT")}.xls`);
      });
    },
    // 点击表格行内的编辑
    handleEdit(row) {
      this.$router.push({
        path: "/upms/system/setting/tenant/edit",
        query: {
          id: row.id,
        },
      });
    },
  },
};
</script>
