<template>
  <div class="box-main">
    <MomTable
      ref="MomTable"
      row-key="id"
      :columns="tableColumns"
      :data-source="tableData"
      :query-param="queryForm"
      :query-param-item="queryFormItem"
      :action-buttons="tableAction"
      :loading="loading"
      :page.sync="page"
      :total="total"
      @search="searchPageData"
      @edit="handleEdit"
      @delete="handleDelete"
    >
      <template slot="status" slot-scope="text, record">
        {{ formatTransformation(record.status, "status") }}
      </template>
      <template slot="enableFlag" slot-scope="text, record">
        <a-switch
          v-model="record.enableFlag"
          @change="isEnableChange(record)"
        />
      </template>
      <template slot="type" slot-scope="text, record">
        {{ formatTransformation(record.type) }}
      </template>
    </MomTable>
  </div>
</template>

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

export default {
  data() {
    return {
      loading: false,
      // 查询的表单的配置项
      queryForm: {
        deviceId: "", // 	终端名称
        status: "", // 状态
        type: "", // 类型
      },
      sortParams: null,
      // 表格的配置项
      tableData: [],
      baseTerminalStatusList: [],
      baseTerminalTypeList: [],
      total: 0,
      page: 1,
      tableAction: [
        (h, value, a, b) => {
          const { text, record } = value;
          if (this.hasAuth("APP_TERMINAL_MANAGEMENT:EDIT")) {
            return (
              <span
                class="text-primary cursor-pointer"
                onClick={() => this.handleEdit(record)}>
                <a-icon type="edit" title={this.$t("EDIT")} />
              </span>
            );
          }
          return null;
        },
        (h, value, a, b) => {
          const { text, record } = value;
          if (
            record.enableFlag === false &&
            this.hasAuth("APP_TERMINAL_MANAGEMENT:DELETE")
          ) {
            return (
              <span
                class="text-error cursor-pointer"
                onClick={() => this.handleDelete(record)}>
                <a-icon type="delete" title={this.$t("DELETE")} />
              </span>
            );
          }
          return null;
        },
      ],
    };
  },
  computed: {
    queryFormItem() {
      return this.$observable("queryFormItem", {
        deviceId: {
          label: () => this.$t("CLIENT_CODE"), // 终端名称
        },
        status: {
          label: () => this.$t("CONNECTION_STATUS"), // 状态
          itemType: "select",
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
        },
        type: {
          label: () => this.$t("CLIENT_TYPE"), // 类型
          itemType: "select",
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
        },
      });
    },
    tableColumns() {
      return [
        {
          dataIndex: "deviceId",
          title: () => this.$t("CLIENT_CODE"),
          minWidth: 200,
        },
        {
          dataIndex: "stationName",
          title: () => this.$t("BINDING_STATION"),
          width: 140,
        },
        {
          dataIndex: "status",
          title: () => this.$t("CONNECTION_STATUS"),
          scopedSlots: { customRender: "status" },
          width: 120,
        },
        {
          dataIndex: "enableFlag",
          title: () => this.$t("ACTIVATE"),
          scopedSlots: { customRender: "enableFlag" },
          width: 120,
        },
        {
          dataIndex: "mac",
          title: () => this.$t("MAC_ADDRESS"),
          width: 160,
        },
        {
          dataIndex: "ip",
          title: () => this.$t("IP_ADDRESS"),
          width: 160,
        },
        {
          dataIndex: "type",
          title: () => this.$t("CLIENT_TYPE"),
          scopedSlots: { customRender: "type" },
          width: 120,
        },
        {
          dataIndex: "updateBy",
          title: () => this.$t("UPDATE_BY"),
          width: 120,
        },
        {
          dataIndex: "updateTime",
          title: () => this.$t("UPDATE_TIME"),
          width: 200,
        },
      ];
    },
  },
  async mounted() {
    await this.queryDictData();
  },
  methods: {
    formatTransformation(status, type) {
      if (type === "status") {
        const result = this.baseTerminalStatusList
          ? this.baseTerminalStatusList.find(
              (item) => item.value === status.toString()
            )
          : [];
        return result ? result.label : "";
      }
      const result = this.baseTerminalTypeList
        ? this.baseTerminalTypeList.find(
            (item) => item.value === status.toString()
          )
        : [];
      return result ? result.label : "";
    },
    // 数据字典查询来源类型
    queryDictData() {
      // DIC:ESOP:BASE_TERMINAL_STATUS 终端状态
      this.getDictByCode("DIC:ESOP:BASE_TERMINAL_STATUS").then((res) => {
        this.queryFormItem.status.options = res.data.data;
        this.baseTerminalStatusList = res.data.data;
      });
      // DIC:ESOP:BASE_TERMINAL_TYPE 终端类型
      this.getDictByCode("DIC:ESOP:BASE_TERMINAL_TYPE").then((res) => {
        this.queryFormItem.type.options = res.data.data;
        this.baseTerminalTypeList = res.data.data;
      });
    },
    // 后台分页查询
    searchPageData(params) {
      this.loading = true;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/app-terminal/search`, {
          params,
        })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.loading = false;
          this.tableData.forEach((item) => {
            if (item.enableFlag === "Y") {
              // eslint-disable-next-line no-param-reassign
              item.enableFlag = true;
            } else {
              // eslint-disable-next-line no-param-reassign
              item.enableFlag = false;
            }
          });
          this.total = res.data.data.total;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    isEnableChange(row) {
      this.$axios
        .put(
          `${ApiConstant.PREFIX_CORE}/api/sys/app-terminal/enable/${row.id}/${
            row.enableFlag === true ? "Y" : "N"
          }`
        )
        .then((res) => {
          this.$message.success(
            row.enableFlag === true
              ? this.$t("ENABLE_SUCCESS")
              : this.$t("DISABLE_SUCCESS")
          );
          this.$refs.MomTable?.query();
        });
    },
    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/app-terminal/${row.id}`)
            .then((res) => {
              this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    handleEdit(row) {
      this.$router.push({
        path: "/upms/system/setting/terminalManage/edit",
        query: {
          id: row.mac,
        },
      });
    },
  },
};
</script>
