<template>
  <div>
    <MomTable
      ref="MomTable"
      row-key="id"
      :row-selection="rowSelection"
      :query-param="queryParam"
      :query-param-item="queryParamItem"
      :columns="columns"
      :data-source="dataSource"
      :total="total"
      :page.sync="page"
      :action-buttons="actionButtons"
      :mega-extend="{
        rowIndex: false,
      }"
      @copy="handleCopy"
      @search="search"
      @edit="handleEdit"
      @delete="handleDelete"
      @reset="handleReset"
    >
      <div slot="toolbar" class="button-top-table">
        <a-button v-if="hasAuth('EPMS:EQP_TYPE:ADD')" @click="handleAdd">
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <MomCopyButton
          v-if="hasAuth('EPMS:EQP_TYPE:ADD')"
          :disabled="selectedRowKeys.length !== 1"
          :keys="selectedRowKeys"
          :data="dataSource"
          @copy="handleCopy"
        />
        <MomEditButton
          v-if="hasAuth('EPMS:EQP_TYPE:EDIT')"
          :disabled="selectedRowKeys.length !== 1"
          :keys="selectedRowKeys"
          :data="dataSource"
          @edit="handleEdit"
        />
        <span style="margin: 0 8px">
          <MomImportButton object-name="EQUIPMENT_TYPE" />
        </span>
        <a-button
          v-if="hasAuth('EPMS:EQP_TYPE:BATCH_DELETE')"
          :disabled="selectedRowKeys.length === 0"
          type="danger"
          ghost
          @click="handleBatchDelete"
        >
          <a-icon type="delete" />
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </div>
    </MomTable>
  </div>
</template>

<script>
import { uniqBy } from "lodash";
import { mapState } from "vuex";
import ApiConstant from "@/api/ApiConstant";
import MomCopyButton from "@/components/MomCopyButton";
import MomEditButton from "@/components/MomEditButton";
import MomImportButton from "@/components/MomImportButton";

import SelectSearch from "@/components/epms/SelectSearch";

export default {
  components: {
    MomImportButton,
    MomCopyButton,
    MomEditButton,
  },
  data() {
    return {
      modalVisible: false,
      isEdit: false,
      isView: false,
      editId: null,
      loading: false, // 表格loading
      confirmLoading: false,
      // 查询的表单的配置项
      queryParam: {
        eqpTypeNameList: "",
      },
      columns: [
        {
          dataIndex: "homeCode", // 编码
          title: () => `${this.$t("HOME_PAGE")}${this.$t("CODE")}`,
          ellipsis: true,
          width: 200,
          // scopedSlots: { customRender: "eqpTypeCode" },
        },
        {
          dataIndex: "homeName", // 名称
          title: () => `${this.$t("HOME_PAGE")}${this.$t("NAME")}`,
          sorter: false,
          ellipsis: true,
        },
        {
          dataIndex: "roleDetail", // 角色
          title: () => this.$t("ROLE"),
          sorter: false,
          ellipsis: true,
        },
        {
          dataIndex: "updateBy", // 更新人员
          sorter: false,
          ellipsis: true,
          title: () => this.$t("UPDATE_BY"),
          width: 120,
        },
        {
          dataIndex: "updateTime", // 更新时间
          ellipsis: true,
          title: () => this.$t("UPDATE_TIME"),
          width: 200,
        },
      ],
      total: 0,
      page: 1,
      actionButtons: [
        this.hasAuth("EPMS:HOME_EDITOR:ADD") && "copy",
        this.hasAuth("EPMS:HOME_EDITOR:EDIT") && "edit",
        this.hasAuth("EPMS:HOME_EDITOR:DELETE") && "delete",
      ],
      dataSource: [],
      stateList: [],
      yesNoList: [],
      selectedRowKeys: [], // 选中行 key 数据
      selectedRows: [], // 选中行 数据
      isReset: false, // 是否重置SelectSearch组件value
    };
  },
  computed: {
    // 表格搜索配置
    queryParamItem() {
      return this.$observable("queryParamItem", {
        eqpTypeNameList: {
          itemType: "custom",
          label: () => `${this.$t("HOME_PAGE")}${this.$t("NAME")}`,
          customRender: () => {
            return (
              <SelectSearch
                isReset={this.isReset}
                queryListKey="homeName"
                requestApi={"/api/home/search"}
                option-label={"homeName"}
                needDisabled={false}
                onChange={this.onSelectSearchChange}
              ></SelectSearch>
            );
          },
        },
      });
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
          if (this.selectedRowKeys.length) {
            this.selectedRows = uniqBy(this.selectedRows.concat(selectedRows));
          } else {
            this.selectedRows = selectedRows;
          }
        },
      };
    },
  },
  created() {
    this.init();
  },
  methods: {
    // 重置搜索监听事件
    handleReset() {
      this.isReset = true;
      this.$refs.MomTable?.search();
    },
    onSelectSearchChange(e, list) {
      this.isReset = false;
      this.queryParam.eqpTypeNameList = e.join(",");
    },
    // 初始化数据
    init() {
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:COMMON:WHETHER_CHAR`
        ), // 是否
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:ENABLE_STATUS`
        ), // 禁用启用
      ]).then(([yesNoRes, enableStatus]) => {
        this.yesNoList = yesNoRes.data.data;
        this.stateList = enableStatus.data.data;
      });
    },
    formatData(data, status) {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
    // 监听搜索事件
    search(params) {
      this.selectedRowKeys = [];
      this.selectedRows = [];
      this.loading = true;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/home/search`, {
          params,
        })
        .then((res) => {
          const { records, total } = { ...res?.data?.data };
          this.dataSource = records;
          this.total = total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 监听新增点击事件
    handleAdd() {
      this.$router.push({
        path: "/eam/home/add",
      });
    },
    // 监听编辑点击事件
    handleCopy(row) {
      this.$router.push({
        path: "/eam/home/add",
        query: {
          id: row.id,
        },
      });
    },
    // 点击表格行内的编辑
    handleEdit({ id }) {
      this.$router.push({
        path: "/eam/home/edit",
        query: {
          id,
        },
      });
    },
    handleDelete(row) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okText: this.$t("DELETE"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(`${ApiConstant.PREFIX_CORE}/api/home/${row.id}`)
            .then(() => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    handleBatchDelete() {
      if (this.selectedRowKeys.length < 1) {
        this.$message.warning(this.$t("SELECT_ONE_DATA"));
        return;
      }
      const params = {
        ids: this.selectedRowKeys,
      };
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okText: this.$t("DELETE"),
        cancelText: this.$t("CANCEL"),
        icon: "close-circle",
        centered: true,
        onOk: () => {
          this.$axios
            .delete(`${ApiConstant.PREFIX_CORE}/api/home/delete-batch`, {
              data: params,
            })
            .then(() => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
  },
};
</script>
<style lang="less">
@import "@/assets/css/status_epms.less";
.eqpTypeSty {
  color: rgba(14, 168, 208, 1);
  cursor: pointer;
  display: block;
}
.wrapClass .ant-modal {
  top: 0;
  padding-bottom: 0;
  .ant-modal-content {
    min-height: 100vh;
    border-left: 8px solid #f0f2f5;
    border-right: 8px solid #f0f2f5;
    .ant-modal-header {
      background: #fff;
      margin: 0 -8px;
      border-radius: 0;
    }
    .ant-modal-body {
      padding: 0;
      border-top: 8px solid #f0f2f5;
      .page-bottom-op {
        width: 100%;
      }
    }
  }
}
</style>
