<template>
  <div class="box_main">
    <div v-if="showMode === 'card'" class="change_box_type">
      <div
        v-for="(item, index) in changeTypeList"
        :key="index"
        class="change_item"
        :class="{ active: showTypeMode === item.type }"
        @click="handleTypeItem(item)"
      >
        {{ item.name }}
      </div>
    </div>
    <a-tabs default-active-key="1" @change="handleChangeTab">
      <a-tab-pane
        key="1"
        :tab="`${$t('MAINTENANCE_PLAN')}${$t('LIST_DISPLAY')}`"
      />
      <a-tab-pane
        key="2"
        :tab="`${$t('MAINTENANCE_PLAN')}${$t('CALENDAR')}`"
        force-render
      />
    </a-tabs>
    <!-- 卡片模式 开始 -->
    <div v-show="showMode === 'card'">
      <div class="card_list">
        <a-spin :spinning="loading">
          <full-calendar
            class="test-fc"
            locale="fr"
            :first-day="firstDay"
            :events="monthData"
            :lang="lang"
            :loading="cardLoading"
            :show-type-mode="showTypeMode"
            :table-data="tableData"
            :table-total="tableTotal"
            :table-page="tablePage"
            @changeMonth="changeMonth"
            @eventClick="eventClick"
            @dayClick="dayClick"
            @moreClick="moreClick"
            @moreScroll="moreScroll"
            @preview="handlePreview"
            @changeTable="changeTable"
          ></full-calendar>
        </a-spin>
      </div>
    </div>
    <!-- 卡片模式 结束 -->
    <!-- 列表模式 开始 -->
    <MomTable
      v-show="showMode === 'list'"
      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,
      }"
      @beforeSearch="beforeSearch"
      @copy="handleCopy"
      @search="search"
      @edit="handleEdit"
      @delete="handleDelete"
    >
      <div slot="toolbar" class="button-top-table">
        <a-button
          v-if="hasAuth('EPMS:MAINTENANCE_PLAN:ADD')"
          @click="handleAdd"
        >
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <MomCopyButton
          v-if="hasAuth('EPMS:MAINTENANCE_PLAN:ADD')"
          :disabled="selectedRowKeys.length !== 1"
          :keys="selectedRowKeys"
          :data="dataSource"
          @copy="handleCopy"
        />
        <MomEditButton
          v-if="hasAuth('EPMS:MAINTENANCE_PLAN:EDIT')"
          :disabled="selectedRowKeys.length !== 1"
          :keys="selectedRowKeys"
          :data="dataSource"
          @edit="handleEdit"
        />
        <a-button
          v-if="hasAuth('EPMS:MAINTENANCE_PLAN:BATCH_DISCONTINUE')"
          :disabled="selectedRowKeys.length === 0"
          @click="
            handleBatchDisabled(
              'N',
              'DISCONTINUE',
              'PLAN_DISCONTINUE_INFO',
              'OPERATION_SUCCESS'
            )
          "
        >
          <i class="iconfont icon-Group- text-error"></i>
          {{ $t("BATCH_DISCONTINUE") }}
        </a-button>
        <a-button
          v-if="hasAuth('EPMS:MAINTENANCE_PLAN:BATCH_DELETE')"
          :disabled="selectedRowKeys.length === 0"
          type="danger"
          ghost
          @click="handleBatchDelete"
        >
          <a-icon type="delete" />
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </div>
      <div slot="planType" slot-scope="text, record">
        <span>{{ getAttrValue(planTypeList, record.executeCycleType) }}</span>
      </div>
      <div slot="pmType" slot-scope="text, record">
        <span>{{ getAttrValue(pmTypeList, record.pmType) }}</span>
      </div>
      <div slot="pmPlanName" slot-scope="text, record">
        <span
          class="view-name"
          :title="record.pmPlanName"
          @click="handleView(record)"
        >
          {{ record.pmPlanName }}
        </span>
      </div>
      <template slot="enableFlag" slot-scope="text, record">
        <span class="status-box" :class="'able' + text">{{
          formatData(stateList, record.enableFlag)
        }}</span>
      </template>
    </MomTable>
    <!-- 列表模式 结束 -->
    <MegaModal
      :visible="modalVisible"
      :centered="true"
      :mask-closable="false"
      :title="modalForm.title"
      :width="'760px'"
      @cancel="handleCloseModal"
      @ok="modalVisible = false"
    >
      <a-form-model
        ref="modalForm"
        :model="modalForm"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-row>
          <a-col :span="24">
            <a-form-model-item
              :label="`${$t('MAINTENANCE_FORM')}${$t('NAME')}`"
            >
              {{ modalForm.pmFrmName }}
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item :label="`${$t('EQUIPMENT_NAME')}`">
              {{ modalForm.pmEqpName }}
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item :label="`${$t('PLAN')}${$t('HANDLE_TIME')}`">
              {{ modalForm.planStartTime }} - {{ modalForm.planEndTime }}
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item :label="`${$t('TASK')}${$t('STATUS')}`">
              <div
                class="btn_status mt-2 flex justify-center items-center"
                :class="{
                  'is-doing': modalForm.status === 'EXECUTING',
                  'is-expired': modalForm.status === 'OVERDUE',
                  'is-end': modalForm.status === 'ALREADY_FINISH',
                }"
              >
                {{ getAttrValue(statusList, modalForm.status) }}
              </div>
            </a-form-model-item>
          </a-col>
          <a-col v-if="modalForm.overdueFlag === 'Y'" :span="24">
            <a-form-model-item :label="`${$t('OVERDUE')}`">
              <span style="color: rgba(255, 0, 0, 1)">{{
                $t("BE_OVERDUE")
              }}</span>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <template slot="footer">
        <a-button type="primary" @click="modalVisible = false">{{
          $t("CONFIRM")
        }}</a-button>
        <a-button @click="handleCloseModal">{{ $t("CANCEL") }}</a-button>
      </template>
    </MegaModal>
  </div>
</template>

<script>
import { uniqBy } from "lodash";
import { mapState } from "vuex";
import {
  Modal as MegaModal,
  TableQueryFilter as MegaTableQueryFilter,
} from "@mega-design/ui-vue";
import { Icon } from "ant-design-vue";
import moment from "moment";
import { getDuration } from "@/utils/epmsUtilsIndex";
import ApiConstant from "@/api/ApiConstant";
import MomCopyButton from "@/components/MomCopyButton";
import MomEditButton from "@/components/MomEditButton";
import FullCalendar from "@/components/fullcalendar";

export default {
  components: {
    FullCalendar,
    MegaModal,
    MomCopyButton,
    MomEditButton,
  },
  data() {
    return {
      showMode: "list",
      modalVisible: false,
      noEnableFlag: false,
      enableFlag: {
        prop: "enableFlag",
        defaultValue: "Y",
        enableValue: "Y",
        options: [
          { label: "全部", value: "" },
          { label: "启用", value: "Y" },
          { label: "禁用", value: "N" },
        ],
        optionsProps: {
          label: "label",
          value: "value",
        },
      },
      loading: false, // 表格loading
      cardLoading: false,
      confirmLoading: false,
      options: {
        allowDuplicateUploads: true,
        target: "/core/api/mom-file/update-one",
        testChunks: true,
        single: true,
        chunkSize: 10 * 1024 * 1024,
      },
      // 查询的表单的配置项
      queryParam: {
        pmPlanName: "",
        enableFlag: "",
      },
      columns: [
        {
          dataIndex: "pmPlanCode", // 保养计划编码
          title: () => `${this.$t("MAINTENANCE_PLAN_CODE")}`,
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "pmPlanName", // 保养计划名称
          title: () => `${this.$t("MAINTENANCE_PLAN")}${this.$t("NAME")}`,
          ellipsis: true,
          width: 200,
          scopedSlots: { customRender: "pmPlanName" },
        },
        {
          dataIndex: "planFrmNames", // 保养表单
          ellipsis: true,
          sorter: false,
          width: 200,
          title: () => `${this.$t("MAINTENANCE_FORM")}`,
        },
        {
          dataIndex: "executeCycleType", // 执行周期类型
          ellipsis: true,
          sorter: false,
          width: 200,
          title: () => this.$t("EXECUTE_CYCLE_TYPE"),
          scopedSlots: { customRender: "planType" },
        },
        {
          dataIndex: "effectTime", // 生效时间
          ellipsis: true,
          sorter: false,
          width: 200,
          title: () => this.$t("EFFECT_TIME"),
        },
        {
          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"),
        },
      ],
      total: 0,
      page: 1,
      actionButtons: [
        this.hasAuth("EPMS:MAINTENANCE_PLAN:ADD") && "copy",
        this.hasAuth("EPMS:MAINTENANCE_PLAN:EDIT") && "edit",
        this.hasAuth("EPMS:MAINTENANCE_PLAN:DELETE") && "delete",
        (h, { record, index }) =>
          this.hasAuth("EPMS:MAINTENANCE_PLAN:DISCONTINUE") &&
          record.enableFlag === "Y" && (
            <Icon
              type="stop"
              title={this.$t("DISCONTINUE")}
              onClick={() =>
                this.handleStatus(
                  { status: "N", id: record.id },
                  "DISCONTINUE",
                  "PLAN_DISCONTINUE_INFO",
                  "OPERATION_SUCCESS"
                )
              }
            />
          ),
      ],
      dataSource: [],
      drawerVisible: false,
      form: {
        id: null,
        checkObjectCode: "",
        pmPlanName: "",
        type: "",
      },
      selectedRowKeys: [], // 选中行 key 数据
      selectedRows: [], // 选中行 数据
      yesNoList: [], // 是否列表
      statusList: [], // 状态列表
      stateList: [], // 启用状态列表
      planTypeList: [], // 计划类型列表
      pmTypeList: [], // 计划类型列表
      year: new Date().getFullYear(), // 当前年
      month: new Date().getMonth(), // 当前月
      pmTaskCalendarCountList: [],
      dayTotals: {}, // 周时每日的总数集合
      monthData: [],
      modalForm: {},
      changeTypeList: [
        {
          type: "D",
          name: "日",
        },
        {
          type: "W",
          name: "周",
        },
        {
          type: "M",
          name: "月",
        },
        {
          type: "S",
          name: "单",
        },
      ],
      showTypeMode: "D",
      executeCycleType: "D", // 执行周期类型：日(D);周(W);月(M);单次(S)
      tableData: [],
      tableTotal: 0,
      tablePage: 1,
      firstDay: 0,
    };
  },
  computed: {
    ...mapState({
      lang: (state) => state.app.locale,
      systemConfig: (state) => state.app.systemConfig,
    }),
    rules() {
      return {
        pmPlanName: [
          {
            required: true,
            max: 50,
            message: this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
      };
    },
    // 表格搜索配置
    queryParamItem() {
      return this.$observable("queryParamItem", {
        pmPlanName: {
          label: () => `${this.$t("MAINTENANCE_PLAN")}${this.$t("NAME")}`,
          placeholder: () => this.$t("ENTER_MAINTENANCE_PLAN_NAME_KEYWORD"),
        },
        enableFlag: {
          itemType: "select",
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
          label: () => this.$t("PLAN_STATUS"),
          on: {
            change: () => {
              this.$forceUpdate();
            },
          },
        },
      });
    },
    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;
          }
        },
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.enableFlag === "N",
          },
        }),
      };
    },
  },
  created() {
    this.firstDay =
      parseFloat(this.systemConfig.FIRST_DAY_OF_WEEK) < 7
        ? this.systemConfig.FIRST_DAY_OF_WEEK
        : 0; // 周日转换为0
    this.init();
  },
  methods: {
    // 监听tab切换事件
    handleChangeTab(e) {
      if (e === "1") {
        this.showMode = "list";
        setTimeout(() => {
          this.$refs.MomTable?.search();
        }, 500);
      } else {
        this.showMode = "card";
        setTimeout(() => {
          this.queryList();
        }, 500);
      }
    },
    // 类型切换
    handleTypeItem(item) {
      this.showTypeMode = item.type;
      this.executeCycleType = item.type;
      // this.queryList();
    },
    // 选择月份
    changeMonth(start, end, current) {
      this.year = new Date(current).getFullYear();
      this.month = new Date(current).getMonth() + 1;
      if (this.showMode === "card") {
        this.queryList();
      }
    },
    // 点击事件
    eventClick(event, jsEvent, pos) {
      this.getPlanDetail(event.id, event.title);
    },
    // 点击表格行内的预览
    handlePreview(row) {
      this.getPlanDetail(row.id, row.title);
    },
    changeTable(page) {
      this.setMonthData({}, page);
    },
    // 点击当天
    dayClick(day, jsEvent) {},
    // 查看更多
    moreClick(day, events, jsEvent) {},
    moreScroll(selectDay, page) {
      let countItem = {};
      if (this.executeCycleType === "D" || this.executeCycleType === "M") {
        const curDate = selectDay.curMonth || selectDay.monthDay;
        countItem = this.pmTaskCalendarCountList.find(
          (ele) => String(ele.groupName) === String(curDate)
        );
        if (!countItem) return;
        const {
          executingCount = 0,
          expireCount = 0,
          finishCount = 0,
          waitCount = 0,
        } = countItem;
        const totalCount =
          Number(executingCount) +
          Number(expireCount) +
          Number(finishCount) +
          Number(waitCount);
        if (totalCount <= selectDay.events.length && totalCount) return;
        this.setMonthData(countItem, page);
      } else if (this.executeCycleType === "W") {
        const week = moment(selectDay.fullDate).week() + 1;
        countItem = this.pmTaskCalendarCountList.find(
          (ele) => String(ele.groupName) === String(week)
        );
        if (!countItem) return;
        if (this.dayTotals[selectDay.fullDate]) {
          const totalCount = Number(this.dayTotals[selectDay.fullDate]);
          if (totalCount <= selectDay.events.length && totalCount) return;
          this.setMonthData(countItem, page, selectDay.fullDate);
        } else {
          const params = {
            page: 1,
            size: 10,
            executeCycleType: "W",
            isCancelApiLoad: true,
            yearWeek: countItem.groupName,
            yearDay: selectDay.fullDate,
          };
          this.$axios
            .get(
              `${ApiConstant.PREFIX_CORE}/api/epm/pmm/plan/page-for-calendar`,
              {
                params,
              }
            )
            .then(({ data }) => {
              const totalCount = Number(data.data?.total);
              this.dayTotals[selectDay.fullDate] = selectDay.fullDate;
              if (totalCount <= selectDay.events.length && totalCount) return;
              this.setMonthData(countItem, page, selectDay.fullDate);
            });
        }
      }
    },
    queryList() {
      const { executeCycleType, year, month } = this;
      let params = {
        executeCycleType,
      };
      if (executeCycleType !== "S") {
        const { firstYearDay, lastYearDay } = getDuration(
          executeCycleType,
          year,
          month
        );
        params = {
          ...params,
          firstYearDay,
          lastYearDay,
        };
      } else {
        this.tableData = [];
        this.setMonthData();
        return;
      }
      this.monthData = [];
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/epm/pmm/plan/page-for-calendar-count`,
          {
            params,
          }
        )
        .then(({ data }) => {
          const pmTaskCalendarCountList = data?.data || [];
          this.pmTaskCalendarCountList = [...pmTaskCalendarCountList];
          pmTaskCalendarCountList.forEach((list) => {
            this.setMonthData(list, 1, "", false);
          });
        });
    },
    setMonthData(list, page = 1, yearDayParam = "", isCancelApiLoad = true) {
      this.cardLoading = true;
      const { year, month, executeCycleType } = this;
      const size =
        executeCycleType === "S" ? this.$store.state.pagination.pageSize : 10;
      let params = {
        page,
        size,
        executeCycleType,
        isCancelApiLoad,
      };
      if (["S"].includes(executeCycleType)) {
        const { firstYearDay, lastYearDay } = getDuration(
          executeCycleType,
          year,
          month
        );
        params = {
          ...params,
          firstYearDay,
          lastYearDay,
        };
        delete params.isCancelApiLoad;
      } else if (["M"].includes(executeCycleType)) {
        const monthP = list.groupName;
        const { firstYearDay, lastYearDay } = getDuration("", year, monthP);
        params = {
          ...params,
          firstYearDay,
          lastYearDay,
        };
      } else if (["W"].includes(executeCycleType)) {
        const yearWeek = list.groupName;
        params = {
          ...params,
          year,
          yearWeek,
        };
        if (yearDayParam) {
          params.yearDay = yearDayParam;
        }
      } else {
        const yearDay = moment(
          `${this.year}-${this.month}-${list.groupName}`
        ).format("YYYY-MM-DD");
        params = {
          ...params,
          yearDay,
        };
      }
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/pmm/plan/page-for-calendar`, {
          params,
        })
        .then(({ data }) => {
          const pmTaskCalendarList = data.data?.records || [];
          if (pmTaskCalendarList.length > 0) {
            if (this.showTypeMode === "S") {
              this.tableData = pmTaskCalendarList;
              this.tableTotal = Number(data.data?.total);
              this.tablePage = Number(page);
            } else {
              let tempObj;
              const listData = pmTaskCalendarList.map((item) => {
                switch (item.status) {
                  case "WAIT_FINISH":
                    // eslint-disable-next-line no-param-reassign
                    item.cssClass = "is-start-bg";
                    break;
                  case "EXECUTING":
                    // eslint-disable-next-line no-param-reassign
                    item.cssClass = "is-doing-bg";
                    break;
                  case "ALREADY_FINISH":
                    // eslint-disable-next-line no-param-reassign
                    item.cssClass = "is-end-bg";
                    break;
                  default:
                    break;
                }
                if (item.overDueFlag === "Y") {
                  // eslint-disable-next-line no-param-reassign
                  item.cssClass = "is-expired";
                }
                const { executingCount, expireCount, finishCount, waitCount } =
                  list;
                let tempNum = 0;
                if (parseFloat(executingCount) > 0) {
                  tempNum += 1;
                }
                if (parseFloat(expireCount) > 0) {
                  tempNum += 1;
                }
                if (parseFloat(finishCount) > 0) {
                  tempNum += 1;
                }
                if (parseFloat(waitCount) > 0) {
                  tempNum += 1;
                }
                tempObj = {
                  id: item.id,
                  type: "pm",
                  start: item.yearDay,
                  title: item.pmPlanName,
                  pmEqpName: item.pmEqpName,
                  cssClass: item.cssClass,
                  end: item.planEndTime,
                  status: item.status,
                  executingCount: parseFloat(executingCount),
                  expireCount: parseFloat(expireCount),
                  finishCount: parseFloat(finishCount),
                  waitCount: parseFloat(waitCount),
                  countLength: tempNum,
                };
                return tempObj;
              });
              this.monthData = [...this.monthData, ...listData];
            }
          }
          this.cardLoading = false;
        })
        .catch(() => {
          this.cardLoading = false;
        });
    },
    getPlanDetail(id, title) {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/epm/pmm/pm-task/get-detail-by-id`,
          {
            params: {
              id,
            },
          }
        )
        .then(({ data }) => {
          this.modalForm = {
            title,
            ...data.data,
            pmFrmName: data.data?.pmFrmTaskItemBPO?.pmFrmName,
            pmEqpName: data.data?.pmEqpName,
          };
          this.modalVisible = true;
        });
    },
    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:PC_STATUS`
        ), // 状态数据字典
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:PLAN_STATUS`
        ), // 启用状态数据字典
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:PM_EXE_TYPE`
        ), // 计划类型
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:PM_TYPE`
        ), // 保养周期类型
      ]).then(([yesNoRes, statusRes, enableStatus, planTypeRes, pmTypeRes]) => {
        this.yesNoList = yesNoRes.data?.data;
        this.statusList = statusRes.data?.data;
        this.stateList = enableStatus.data?.data;
        this.planTypeList = planTypeRes.data?.data;
        this.pmTypeList = pmTypeRes.data?.data;
        if (enableStatus.data?.data && enableStatus.data?.data.length > 0) {
          this.queryParam.enableFlag = enableStatus.data?.data[0].value;
        }
        const arr = [{ label: "全部", value: "" }];
        const list = enableStatus.data?.data || [];
        this.queryParamItem.enableFlag.options = [...arr, ...list];
      });
    },
    beforeSearch() {},
    formatData(data, status) {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
    // 表格查询
    search(params) {
      this.selectedRowKeys = [];
      this.selectedRows = [];
      const searchParams = {
        ...params,
        enableFlag: this.queryParam.enableFlag,
      };
      this.loading = true;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/pmm/plan/search`, {
          params: searchParams,
        })
        .then((res) => {
          this.dataSource = 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_plan/add",
      });
    },
    // 监听编辑点击事件
    handleCopy(row) {
      this.$router.push({
        path: "/eam/eqp_maintain/maintenance_plan/add",
        query: {
          id: row.id,
        },
      });
    },
    // 监听编辑点击事件
    handleEdit({ id }) {
      this.$router.push({
        query: {
          id,
        },
        path: "/eam/eqp_maintain/maintenance_plan/edit",
      });
    },
    handleView({ id }) {
      this.$router.push({
        query: {
          id,
        },
        path: "/eam/eqp_maintain/maintenance_plan/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/plan/${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/plan/delete-batch`,
              {
                data: params,
              }
            )
            .then(() => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              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 } = record;
          this.$axios
            .put(`${ApiConstant.PREFIX_CORE}/api/epm/pmm/plan/stop/${id}`)
            .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/plan/stop-batch`,
              params
            )
            .then(() => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 关闭弹框
    handleCloseModal() {
      this.$refs.modalForm.clearValidate();
      this.modalVisible = false;
    },
  },
};
</script>
<style lang="less" scoped>
@import "@/assets/css/status_epms.less";
// .box_main {
//   height: calc(100vh - 50px - 44px - 12px);
//   overflow-y: auto;
// }
.change_box {
  display: flex;
  justify-content: space-between;
  height: 32px;
  position: absolute;
  top: 95px;
  right: 15px;
  cursor: pointer;
  z-index: 999;
  .change_item {
    min-width: 98px;
    height: 100%;
    border-radius: 4px;
    background: #fff;
    border: 1px solid #006896;
    font-size: 14px;
    font-weight: 400;
    color: #006896;
    padding: 0 5px;
    margin: 0 5px;
    .anticon {
      color: #006896;
      margin: 2px 6px 0 0;
    }
    &.active {
      color: #fff;
      background: #006896;
      .anticon {
        color: #fff;
      }
    }
  }
}
.change_box_type {
  width: 162px;
  height: 32px;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #dce5e8;
  position: absolute;
  top: 57px;
  right: 22px;
  display: inline-block;
  overflow: hidden;
  cursor: pointer;
  z-index: 999;
  .change_item {
    width: 40px;
    height: 100%;
    line-height: 30px;
    border-radius: unset;
    border-right: 1px solid #dce5e8;
    background: none;
    float: left;
    text-align: center;
    &.active {
      background: #006896;
      color: #fff;
    }
    &:last-child {
      border-right: none;
    }
  }
}
.card_list {
  padding: 0 20px 20px;
}
</style>
