<template>
  <div>
    <MomTable
      ref="MomTable"
      row-key="id"
      :row-selection="rowSelection"
      :query-param="queryForm"
      :query-param-item="queryFormItem"
      :columns="tableColumns"
      :data-source="dataSource"
      :total="total"
      :page.sync="page"
      :action-buttons="actionButtons"
      :mega-extend="{
        rowIndex: false,
      }"
      :show-enable-flag="hasAuth('EPMS:MAINTENANCE_CONTENT:ENABLED')"
      :enable-flag="enableFlag"
      @beforeSearch="beforeSearch"
      @copy="handleCopy"
      @search="search"
      @edit="handleEdit"
      @delete="handleDelete"
      @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'
          )
      "
    >
      <div slot="toolbar" class="button-top-table">
        <a-button
          v-if="hasAuth('EPMS:MAINTENANCE_CONTENT:ADD')"
          @click="handleAdd"
        >
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <MomCopyButton
          v-if="hasAuth('EPMS:MAINTENANCE_CONTENT:ADD')"
          :disabled="selectedRowKeys.length !== 1"
          :keys="selectedRowKeys"
          :data="dataSource"
          @copy="handleCopy"
        />
        <MomEditButton
          v-if="hasAuth('EPMS:MAINTENANCE_CONTENT:EDIT')"
          :disabled="selectedRowKeys.length !== 1"
          :keys="selectedRowKeys"
          :data="dataSource"
          @edit="handleEdit"
        />
        <span style="margin: 0 8px">
          <MomImportButton object-name="PM_ITEM" />
        </span>
        <a-button
          v-if="hasAuth('EPMS:MAINTENANCE_CONTENT:BATCH_ENABLED')"
          :disabled="selectedRowKeys.length === 0"
          @click="
            handleBatchDisabled(
              'Y',
              'ENABLED',
              'ENABLED_DATAS_INFO',
              'ENABLE_SUCCESS'
            )
          "
        >
          <i class="iconfont icon-queren text-success"></i>
          {{ $t("BATCH_ENABLED") }}
        </a-button>
        <a-button
          v-if="hasAuth('EPMS:MAINTENANCE_CONTENT:BATCH_DISABLED')"
          :disabled="selectedRowKeys.length === 0"
          @click="
            handleBatchDisabled(
              'N',
              'DISABLED',
              'DISABLED_DATAS_INFO',
              'DISABLE_SUCCESS'
            )
          "
        >
          <i class="iconfont icon-Group- text-error"></i>
          {{ $t("BATCH_DISABLED") }}
        </a-button>
        <a-button
          v-if="hasAuth('EPMS:MAINTENANCE_CONTENT:BATCH_DELETE')"
          :disabled="selectedRowKeys.length === 0"
          type="danger"
          ghost
          @click="handleBatchDelete"
        >
          <a-icon type="delete" />
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </div>
      <div slot="type" slot-scope="text, record">
        <span>{{ formatData(typeList, record.type) }}</span>
      </div>
      <div slot="itemName" slot-scope="text, record">
        <span class="view-name" @click="handleView(record)">
          {{ record.itemName }}
        </span>
      </div>
      <template slot="enableFlag" slot-scope="text, record">
        <span class="status-box" :class="'able' + text">{{
          formatData(stateList, record.enableFlag)
        }}</span>
      </template>
      <div slot="errorCodeType" slot-scope="text, record">
        <span>{{ formatData(errorCodeTypeList, record.errorCodeType) }}</span>
      </div>
    </MomTable>
  </div>
</template>

<script>
import { uniqBy } from "lodash";
import ApiConstant from "@/api/ApiConstant";
import MomCopyButton from "@/components/MomCopyButton";
import MomEditButton from "@/components/MomEditButton";
import FieldExtendMixin from "@/mixins/fieldExtend";
import MomImportButton from "@/components/MomImportButton";

export default {
  components: { MomImportButton, MomCopyButton, MomEditButton },
  mixins: [FieldExtendMixin],
  data() {
    return {
      enableFlag: {
        prop: "enableFlag",
        defaultValue: "Y",
        enableValue: "Y",
        options: [
          { label: "全部", value: "" },
          { label: "启用", value: "Y" },
          { label: "禁用", value: "N" },
        ],
        optionsProps: {
          label: "label",
          value: "value",
        },
      },
      tableNameList: [
        {
          key: "epm_pm_item",
          tab: "保养项目",
        },
      ],
      dataAttr: {
        tableColumns: "tableColumns",
        queryFormItem: "queryFormItem",
        queryForm: "queryForm",
      },
      loading: false, // 表格loading
      confirmLoading: false,
      // 查询的表单的配置项
      queryForm: {
        itemName: "",
      },
      total: 0,
      page: 1,
      actionButtons: [
        this.hasAuth("EPMS:MAINTENANCE_CONTENT:ADD") && "copy",
        this.hasAuth("EPMS:MAINTENANCE_CONTENT:EDIT") && "edit",
        this.hasAuth("EPMS:MAINTENANCE_CONTENT:DELETE") && "delete",
      ],
      dataSource: [],
      drawerVisible: false,
      form: {
        id: null,
        errorCodeType: "",
        errorCategoryName: "",
      },
      stateList: [],
      typeList: [],
      selectedRowKeys: [], // 选中行 key 数据
      selectedRows: [], // 选中行 数据
      errorCodeTypeList: [], // 代码类型列表
    };
  },
  computed: {
    // 表格搜索配置
    queryFormItem() {
      return this.$observable("queryFormItem", {
        itemName: {
          label: () => `${this.$t("MAINTENANCE_CONTENT")}${this.$t("NAME")}`,
          placeholder: () => this.$t("ENTER_MAINTENANCE_CONTENT_NAME_KEYWORD"),
        },
      });
    },
    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;
          }
        },
      };
    },
    // 唯一选中时，编辑操作项
    onlySelectedRow() {
      const row = this.selectedRowKeys.length
        ? this.dataSource.find((data) => data.id === this.selectedRowKeys[0])
        : {};
      return row;
    },
    tableColumns() {
      return this.$observable("tableColumns", [
        {
          dataIndex: "itemCode", // 保养项编码
          title: () => `${this.$t("PM_ITEM_CODE")}`,
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "itemName", // 保养项名称
          title: () => `${this.$t("PM_ITEM_NAME")}`,
          ellipsis: true,
          width: 200,
          scopedSlots: { customRender: "itemName" },
        },
        {
          dataIndex: "enableFlag",
          align: "left",
          sorter: false,
          ellipsis: true,
          width: 200,
          title: () => this.$t("STATUS"), // 状态
          scopedSlots: { customRender: "enableFlag" },
        },
        {
          dataIndex: "updateBy", // 更新人员
          sorter: false,
          ellipsis: true,
          title: () => this.$t("UPDATE_BY"),
        },
        {
          dataIndex: "updateTime", // 更新时间
          ellipsis: true,
          title: () => this.$t("UPDATE_TIME"),
        },
      ]);
    },
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:ENABLE_STATUS`
        ), // 禁用启用
      ]).then(([enableStatus]) => {
        this.stateList = enableStatus.data?.data;
      });
    },
    formatData(data, status) {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
    beforeSearch() {
      return this.queryFieldExtend().then((res) => {
        if (res.data.data.fieldHiddenConfigList?.length) {
          const obj = {};
          res.data.data.fieldHiddenConfigList.forEach((item) => {
            obj[item.fieldName] = true;
          });
          // 处理查询条件的字段的隐藏和显示
          Object.keys(this.queryFormItem).forEach((item) => {
            this.hasFunction(obj, item);
          });
          // 处理表格的字段的隐藏和显示
          const arr = JSON.parse(JSON.stringify(this.tableColumns));
          arr.forEach((item) => {
            this.tableColumnsFunction(obj, item.dataIndex);
          });
        }
      });
    },
    tableColumnsFunction(obj, val) {
      // eslint-disable-next-line no-prototype-builtins
      if (obj.hasOwnProperty(val)) {
        if (obj[val]) {
          this.tableColumns.forEach((item, index) => {
            if (item.dataIndex === val) {
              this.tableColumns.splice(index, 1);
            }
          });
        }
      }
    },
    hasFunction(obj, val) {
      // eslint-disable-next-line no-prototype-builtins
      if (obj.hasOwnProperty(val)) {
        if (obj[val]) {
          delete this.queryFormItem[val];
          delete this.queryForm[val];
        }
      }
    },
    search(params) {
      this.selectedRowKeys = [];
      this.selectedRows = [];
      const searchParams = {
        ...params,
      };
      this.loading = true;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/pmm/pm-item/search`, {
          params: searchParams,
        })
        .then((res) => {
          this.dataSource = this.fieldExResDataFn(res.data.data.records);
          this.total = res.data.data.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 监听新增点击事件
    handleAdd() {
      this.$router.push({
        path: "/eam/eqp_maintain/maintenance_content/add",
      });
    },
    // 监听编辑点击事件
    handleCopy(row) {
      this.$router.push({
        path: "/eam/eqp_maintain/maintenance_content/add",
        query: {
          id: row.id,
        },
      });
    },
    // 点击表格行内的编辑
    handleEdit(row) {
      this.$router.push({
        query: {
          id: row.id,
        },
        path: "/eam/eqp_maintain/maintenance_content/edit",
      });
    },
    handleView(row) {
      this.$router.push({
        query: {
          id: row.id,
        },
        path: "/eam/eqp_maintain/maintenance_content/view",
      });
    },
    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/epm/pmm/pm-item/${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"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(
              `${ApiConstant.PREFIX_CORE}/api/epm/pmm/pm-item/delete-batch`,
              {
                data: params,
              }
            )
            .then(() => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.selectedRowKeys = [];
              this.selectedRows = [];
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    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/epm/pmm/pm-item/enable/${id}/${status}`
            )
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    handleBatchDisabled(status, titleText, contentText, tips) {
      if (this.selectedRowKeys.length < 1) {
        this.$message.warning(this.$t("SELECT_ONE_DATA"));
        return;
      }
      const tempArr = [];
      this.dataSource.forEach((item) => {
        this.selectedRowKeys.forEach((ele) => {
          if (item.id === ele && item.enableFlag !== status) {
            tempArr.push(item);
          }
        });
      });
      if (tempArr.length < 1) {
        const content =
          status === "Y" ? "NO_DATA_TO_ENABLE" : "NO_DATA_TO_DISABLE";
        this.$confirm({
          title: this.$t(titleText),
          content: this.$t(content),
          okText: this.$t("CONFIRM"),
          cancelText: this.$t("CANCEL"),
          centered: false,
          icon: "exclamation-circle",
          onOk: () => {},
        });
        return;
      }
      const params = {
        status,
        ids: this.selectedRowKeys,
      };
      this.$confirm({
        title: this.$t(titleText),
        content: this.$t(contentText),
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "exclamation-circle",
        onOk: () => {
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/epm/pmm/pm-item/enable-batch`,
              params
            )
            .then(() => {
              this.$message.success(this.$t(tips));
              this.selectedRowKeys = [];
              this.selectedRows = [];
              this.$refs.MomTable?.query();
            });
        },
      });
    },
  },
};
</script>
<style lang="less" scoped>
@import "@/assets/css/status_epms.less";
/deep/ .el-upload__input {
  display: none !important;
}
/deep/ .error-type .ant-form-item-children {
  display: flex;
}
.tips-icon {
  width: 50px;
  text-align: center;
  font-size: 20px;
  color: #ff9041;
}
</style>
