<template>
  <div class="page-wrapper">
    <breadcrumb v-if="!multiPage" :breadcrumb-data="breadcrumbData" />
    <div class="page-container">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="{ span: 7 }"
        :wrapper-col="{ span: 17 }"
      >
        <a-collapse
          v-model="activeKey"
          expand-icon-position="right"
          class="collapse-header-divide"
        >
          <a-collapse-panel key="a" :header="$t('BASE_INFO')">
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item
                  :label="`${$t('PARTOL_CHECK_PLAN')}${$t('CODE')}`"
                  prop="pcPlanCode"
                  allow-clear
                >
                  <a-input
                    v-model="form.pcPlanCode"
                    :placeholder="`${$t('SYSTEM_DEFAULT_CODE')}DJJH+${$t(
                      'NUMBER'
                    )}`"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="`${$t('PARTOL_CHECK_PLAN')}${$t('NAME')}`"
                  prop="pcPlanName"
                  allow-clear
                >
                  <a-input
                    v-model="form.pcPlanName"
                    :placeholder="$t('PLACEENTER')"
                    @change="
                      form.pcPlanName = form.pcPlanName.slice(0, 50).trim()
                    "
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('CHECK_TYPE')"
                  prop="pcCategoryId"
                >
                  <SelectCheckType
                    :pc-category-id="form.pcCategoryId"
                    :pc-category-name="form.pcCategoryName"
                    @change="onSelectSearchChange"
                  >
                  </SelectCheckType>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row v-if="false" :gutter="24">
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('DEPARTMENTCODE')"
                  prop="responsibleDeptId"
                >
                  <a-tree-select
                    v-model="form.responsibleDeptId"
                    :replace-fields="treeProps"
                    tree-check-strictly
                    :tree-data="treeData"
                    allow-clear
                    @change="handChangeDep"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('LEADER_NAME')"
                  prop="responsibleUser"
                >
                  <template>
                    <div style="position: relative">
                      <select-user
                        ref="selectUser"
                        v-model="form.responsibleUser"
                        :multiple="false"
                        :default-selected-rows="selectedUser"
                        :search-params="searchParams"
                        @confirm="getReturnData"
                      />
                    </div>
                  </template>
                </a-form-model-item>
              </a-col>
            </a-row>
            <MomTable
              row-key="key"
              :columns="columns"
              :data-source="planFrmList"
              :action-buttons="actionButtons"
              :show-util-operator="false"
              :pagination="false"
              @delete="handleDelete"
            >
              <a-row slot="toolbar" class="button-top-table">
                <a-button @click="handleAdd">
                  <a-icon type="plus" /> {{ $t("ADD") }}
                </a-button>
              </a-row>
              <template slot="pcFrmId" slot-scope="text, row, index">
                <SelectSearch
                  :show-multiple="false"
                  request-api="/api/epm/pcm/pc-frm/search"
                  option-label="pcFrmName,pcFrmVersion"
                  query-list-key="searchKey"
                  :default-selected-keys="row.pcFrmId"
                  :default-selected-names="row.pcFrmName"
                  :search-params="selectSearchParams"
                  @change="onSelectSearchChangeForm($event, index)"
                >
                </SelectSearch>
              </template>
              <template slot="pcObjectName" slot-scope="text, row, index">
                <div style="position: relative">
                  <select-check-object
                    :key="row.key"
                    ref="SelectCheckObject"
                    v-model="row.pcObjectName"
                    row-key="id"
                    show-key="name"
                    :default-selected-rows="row.defaultSelectedRows"
                    :current-index="index"
                    :pc-category-id="form.pcCategoryId"
                    :pc-object-source-id-item="row.pcObjectSourceIdItem"
                    @confirm="getReturnDataCheckObject"
                  />
                </div>
              </template>
            </MomTable>
          </a-collapse-panel>
        </a-collapse>
        <a-collapse
          v-model="activeKeyB"
          expand-icon-position="right"
          class="collapse-header-divide"
        >
          <a-collapse-panel key="b" :header="$t('PLAN')">
            <a-row :gutter="24">
              <a-form-model-item
                :label="`${$t('EFFECT_DATE')}`"
                :label-col="{ span: 2 }"
                :wrapper-col="{ span: 22 }"
                prop="rangeDate"
                allow-clear
              >
                <a-range-picker
                  v-model="form.rangeDate"
                  :disabled-date="disabledDate"
                  format="YYYY-MM-DD"
                  :placeholder="[
                    $t('PLACESELECT') + $t('EFFECT_DATE'),
                    $t('PLACESELECT') + $t('FAILURE_DATE'),
                  ]"
                />
              </a-form-model-item>
            </a-row>
            <a-row
              :gutter="24"
              style="
                background: rgba(245, 247, 250, 1);
                padding: 10px 0;
                margin-bottom: 10px;
              "
            >
              <a-form-model-item
                :label="`${$t('EXECUTE_CYCLE')}`"
                :label-col="{ span: 2 }"
                :wrapper-col="{ span: 21 }"
                allow-clear
              >
                <a-radio-group
                  v-model="form.executeCycleType"
                  style="width: 100%"
                >
                  <div
                    class="item flex"
                    :class="{ active: form.executeCycleType === 'D' }"
                  >
                    <a-radio :value="'D'">{{ $t("BY_DAY") }}</a-radio>
                    <div class="item_con flex">
                      <div class="mr-5">{{ $t("EVERY_OTHER") }}</div>
                      <a-input-number
                        v-model="form.executeCycleIntervalDay"
                        :min="0"
                        :max="10"
                      />
                      <div class="ml-5">
                        {{ $t("DAY") }}{{ $t("TODO") }}{{ $t("CHECK_PLAN") }}
                      </div>
                    </div>
                  </div>
                  <div
                    class="item flex"
                    :class="{ active: form.executeCycleType === 'W' }"
                  >
                    <a-radio :value="'W'">{{ $t("BY_WEEK") }}</a-radio>
                    <div class="item_con flex">
                      <div class="mr-5">{{ $t("EVERY_OTHER") }}</div>
                      <a-input-number
                        v-model="form.executeCycleIntervalWeek"
                        :min="0"
                        :max="12"
                      />
                      <div class="ml-5 mr-5">{{ $t("WEEK") }}</div>
                      <a-select
                        v-model="form.executeCycleDayWeek"
                        class="sitemore"
                        mode="multiple"
                        style="width: 260px"
                        :placeholder="$t('PLACESELECT')"
                      >
                        <a-select-option
                          v-for="(item, index) in weekList"
                          :key="index"
                          :value="item.id"
                        >
                          {{ item.name }}
                        </a-select-option>
                      </a-select>
                      <div class="ml-5">
                        {{ $t("TODO") }}{{ $t("CHECK_PLAN") }}
                      </div>
                    </div>
                  </div>
                  <div
                    class="item flex"
                    :class="{ active: form.executeCycleType === 'M' }"
                  >
                    <a-radio :value="'M'">{{ $t("BY_MONTH") }}</a-radio>
                    <div class="item_con flex">
                      <div class="mr-5">{{ $t("EVERY_OTHER") }}</div>
                      <a-input-number
                        v-model="form.executeCycleIntervalMonth"
                        :min="0"
                        :max="12"
                      />
                      <div class="ml-5 mr-5">{{ $t("MONTH") }}</div>
                      <a-select
                        v-model="form.executeCycleDayMonth"
                        class="sitemore"
                        mode="multiple"
                        style="width: 260px"
                        :placeholder="$t('PLACESELECT')"
                      >
                        <a-select-option
                          v-for="(item, index) in monthList"
                          :key="index"
                          :value="item.id"
                        >
                          {{ item.name }}
                        </a-select-option>
                      </a-select>
                      <div class="ml-5">
                        {{ $t("TODO") }}{{ $t("CHECK_PLAN") }}
                      </div>
                    </div>
                  </div>
                  <div
                    class="item flex"
                    :class="{ active: form.executeCycleType === 'S' }"
                  >
                    <a-radio :value="'S'">{{ $t("SINGLE_ENTTRY") }}</a-radio>
                  </div>
                </a-radio-group>
              </a-form-model-item>
            </a-row>
            <a-form-model
              v-for="(item, index) in planTimeList"
              :key="index"
              :ref="`ruleForm${index}`"
              :model="item"
              :label-col="{ span: 7 }"
              :wrapper-col="{ span: 17 }"
            >
              <a-row :gutter="24">
                <a-col :span="8">
                  <a-form-model-item
                    :label="`${$t('TODO')}${$t('START_TIME')}`"
                    prop="planStartTime"
                    allow-clear
                    :rules="[
                      {
                        required: true,
                        message: $t('PLACESELECT'),
                      },
                    ]"
                  >
                    <a-time-picker
                      v-model="item.planStartTime"
                      :disabled-hours="handleDisabledStartHours(item)"
                      :disabled-minutes="handleDisableStartMinutes(item)"
                      :show-time="{ format: 'HH:mm' }"
                      format="HH:mm"
                      :placeholder="$t('PLACESELECT')"
                      @change="handleChangeEndTime(item)"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item
                    :label="`${$t('TODO')}${$t('END_TIME')}`"
                    prop="planEndTime"
                    allow-clear
                    :rules="[
                      {
                        required: true,
                        message: $t('PLACESELECT'),
                      },
                    ]"
                  >
                    <a-time-picker
                      v-model="item.planEndTime"
                      :disabled-hours="handleDisabledHours(item)"
                      :disabled-minutes="handleDisabledMinutes(item)"
                      :show-time="{ format: 'HH:mm' }"
                      format="HH:mm"
                      :placeholder="$t('PLACESELECT')"
                      @change="handleChangeEndTime(item)"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <div class="flex" style="padding-top: 2px">
                    <div
                      v-if="planTimeList.length > 1"
                      class="btn_opearte flex items-center justify-center cursor-pointer"
                      style="margin-right: 10px"
                      @click="handleDeleteItem(index)"
                    >
                      <i class="iconfont icon-jian mr-1" />
                      <span>{{ $t("DELETE") }}</span>
                    </div>
                    <div
                      v-if="index === planTimeList.length - 1"
                      class="btn_opearte flex items-center justify-center cursor-pointer"
                      @click="handleAddItem()"
                    >
                      <i class="iconfont icon-jia mr-1" />
                      <span>{{ $t("ADD") }}</span>
                    </div>
                  </div>
                </a-col>
              </a-row>
            </a-form-model>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
    </div>
    <div class="page-bottom-op">
      <a-button
        type="primary"
        :loading="confirmLoading"
        @click="handleSave('save')"
      >
        <i class="iconfont icon-baocun"></i>
        {{ $t("SAVE") }}
      </a-button>
      <a-button
        :loading="confirmLoading"
        type="primary"
        @click="handleSave('saveAndAdd')"
      >
        <i class="iconfont icon-baocun"></i>
        {{ $t("SAVE_AND_ADD_NEXT") }}
      </a-button>
      <a-button @click="handleCancel">
        <i class="iconfont icon-quxiao"></i>
        {{ $t("CANCEL") }}
      </a-button>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import moment from "moment";
import ApiConstant from "@/api/ApiConstant";
import breadcrumb from "@/components/breadcrumb";
import SelectCheckObject from "@/components/SelectPartolCheckObject";
import SelectCheckType from "@/components/SelectCheckType";

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

export default {
  components: {
    breadcrumb,
    SelectCheckObject,
    SelectCheckType,
    SelectSearch,
    SelectUser,
  },
  data() {
    return {
      date: new Date().getTime(),
      breadcrumbData: [
        {
          name: this.$t("CHECK_OBJECT_SOURCES"),
          url: "/eam/basic_setting/check/object_source",
        },
        { name: this.$t("CHECK_OBJECT_SOURCE_ADD"), url: "" },
      ],
      activeKey: "a",
      activeKeyB: "b",
      activeKeyC: "c",
      confirmLoading: false,
      dataSource: [],
      columns: [
        {
          dataIndex: "pcFrmId", // 点检表单
          title: () => this.$t("CHECK_FORM"),
          minWidth: 260,
          sorter: false,
          scopedSlots: { customRender: "pcFrmId" },
        },
        {
          dataIndex: "pcObjectName", // 点检对象
          title: () => `${this.$t("CHECK_OBJECT")}&${this.$t("PARTOL_ROUTE")}`,
          // maxWidth: 260,
          sorter: false,
          scopedSlots: { customRender: "pcObjectName" },
        },
      ],
      form: {
        pcPlanCode: "",
        pcPlanName: "", // 名称
        pcCategoryId: "", // 点检分类
        responsibleUser: "", // 执行人
        responsibleDeptId: "", // 部门
        rangeDate: [], // 生效时间
        executeCycleType: "D", // 执行周期类型：日(D);周(W);月(M);单次(S)
        executeCycleIntervalDay: "0", // 执行周期间隔：单位：天
        executeCycleIntervalWeek: "0", // 执行周期间隔：单位：周
        executeCycleIntervalMonth: "0", // 执行周期间隔：单位：月
        executeCycleDayWeek: [], // 执行周期具体执行日期：周几
        executeCycleDayMonth: [], // 执行周期具体执行日期：几号
      },
      // 点检表单列表
      planFrmList: [],
      planFrmItem: {
        pcFrmId: "", // 点检表单id
        pcFrmName: "",
        pcObjectName: "", // 点检对象名称
        pcObjectSourceIdItem: "", // 点检对象来源id
        pcObjectList: [], // 点检对象列表
        defaultSelectedRows: [], // 默认选中数据
      },
      // 执行时间列表
      planTimeList: [
        {
          planStartTime: "", // 计划开始时间
          planEndTime: "", // 计划结束时间
        },
      ],
      // 对象展示字段列表
      actionButtons: [
        (h, { record, index }) => (
          <a-button
            type="link"
            onClick={() => this.handleDelete(record, index)}
          >
            <i
              class="operation-icon iconfont icon-delete"
              style="font-size:18px;color:#d45f5f"
              title={this.$t("DELETE")}
            />
          </a-button>
        ),
      ],
      curIndex: 0,
      selectedUser: [],
      treeData: [],
      treeProps: {
        value: "id",
        children: "children",
        label: "label",
      },
      weekList: [],
      monthList: [],
      pcObjectSourceId: "", // 点检对象来源id
      searchParams: {
        deptId: "",
      },
      selectSearchParams: {
        pcCategoryId: "",
      },
    };
  },
  computed: {
    ...mapState("setting", ["multiPage"]),
    rules() {
      return {
        pcPlanName: [
          {
            required: true,
            max: 50,
            message: () => this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        rangeDate: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
      };
    },
  },
  mounted() {
    this.weekList = ApiConstant.weekList;
    this.monthList = ApiConstant.monthList;
    const { id } = this.$route.query;
    if (id) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/pcm/plan/get-by-id/${id}`)
        .then((detailRes) => {
          /* eslint-disable */
          const {
            effectTime,
            expireTime,
            executeCycleType,
            executeCycleInterval,
            executeCycleDay,
            planFrmList,
            planTimeList,
            responsibleDeptId,
          } = detailRes.data?.data;
          this.searchParams.deptId = responsibleDeptId || "";
          this.form = { ...detailRes.data?.data, rangeDate: [] };
          this.form.id = "";
          this.form.pcPlanCode = "";
          this.selectedUser = [{ userName: this.form.responsibleUser }];
          if (planFrmList && planFrmList.length > 0) {
            const planFrmItem = {
              ...this.planFrmItem,
            };
            // const arrList = this.checkSameData(planFrmList);
            const arrList = [...planFrmList];
            let pcFormIdArr = [];
            let tempObj;
            arrList.forEach((item) => {
              const findex = pcFormIdArr.findIndex(
                (itemA) => itemA.pcFrmId === item.pcFrmId
              );
              if (findex > -1) {
                pcFormIdArr[findex].pcObjectList.push({
                  id: item.pcObjectId,
                  code: item.pcObjectCode,
                  name: item.pcObjectName,
                  pcObjectSourceId: item.pcObjectSourceId,
                });
              } else {
                pcFormIdArr.push({
                  pcFrmId: item.pcFrmId,
                  pcFrmName: item.pcFrmName,
                  pcObjectGroupId: item.pcObjectGroupId,
                  pcObjectGroupName: item.pcObjectGroupName,
                  pcObjectSourceId: item.pcObjectSourceId,
                  pcObjectList: [
                    {
                      id: item.pcObjectGroupId,
                      name: item.pcObjectGroupName,
                    },
                  ],
                });
              }
            });
            this.planFrmList = pcFormIdArr.map((item) => {
              item.defaultSelectedRows = item.pcObjectList;
              return item;
            });
          }
          let rangeDate = [];
          rangeDate.push(effectTime);
          rangeDate.push(expireTime);
          this.form = Object.assign(this.form, { rangeDate: rangeDate });
          let tempObj;
          switch (executeCycleType) {
            case "D":
              tempObj = {
                executeCycleType,
                executeCycleIntervalDay: executeCycleInterval,
              };
              break;
            case "W":
              tempObj = {
                executeCycleType,
                executeCycleIntervalWeek: executeCycleInterval,
                executeCycleDayWeek: executeCycleDay.split(","),
              };
              break;
            case "M":
              tempObj = {
                executeCycleType,
                executeCycleIntervalMonth: executeCycleInterval,
                executeCycleDayMonth: executeCycleDay.split(","),
              };
              break;
          }
          this.form = Object.assign(this.form, tempObj);
          if (planTimeList && planTimeList.length > 0) {
            planTimeList.forEach((item) => {
              item.planStartTime = moment(item.planStartTime, "HH:mm");
              item.planEndTime = moment(item.planEndTime, "HH:mm");
            });
          }
          this.planTimeList = planTimeList;
          this.$forceUpdate();
          /* eslint-enable */
        });
    }
    // 初始化数据
    this.init();
  },
  methods: {
    disabledDate(current) {
      return current < moment().subtract(1, "day"); // 当天之前的不可选，不包括当天
    },
    // 获取返回数据，点检分类
    onSelectSearchChange(pcCategoryId, pcCategoryName) {
      this.selectSearchParams.pcCategoryId = pcCategoryId;
      this.form.pcCategoryId = pcCategoryId;
      this.form.pcCategoryName = pcCategoryName;
    },
    // 获取返回数据，点检表单
    onSelectSearchChangeForm(e, index) {
      this.planFrmList[index].pcFrmId = e;
    },
    // 获取选择用户组件返回数据
    getReturnData(selectedKeys, selectedRows) {
      this.form.responsibleUser = selectedRows[0]?.userName;
      this.selectedUser = selectedRows;
    },
    // 获取选择点检对象组件返回数据
    getReturnDataCheckObject(
      selectedKeys,
      selectedRows,
      pcObjectSourceId,
      currentIndex,
      returnId,
      returnName
    ) {
      const tempObj = {
        id: returnId,
        name: returnName,
        pcObjectSourceId,
      };
      this.planFrmList[currentIndex].defaultSelectedRows = [tempObj];
      this.planFrmList[currentIndex].pcObjectName = returnName;
      this.planFrmList[currentIndex].pcObjectGroupId = returnId;
      this.planFrmList[currentIndex].pcObjectSourceId = pcObjectSourceId;
      this.$forceUpdate();
      // this.planFrmList[currentIndex].pcObjectSourceIdItem =
      //   pcObjectSourceId || "";
      /* eslint-disable */
      // if (selectedRows.length > 0) {
      //   this.planFrmList[currentIndex].pcObjectName = selectedKeys.join(",");
      //   this.planFrmList[currentIndex].pcObjectList = [...selectedRows];
      //   this.planFrmList[currentIndex].pcObjectList.map((item) => {
      //     item.pcObjectSourceId = pcObjectSourceId;
      //     return item;
      //   });
      // }
      /* eslint-enable */
    },
    // 监听选择部门组件返回数据
    handChangeDep(val) {
      this.searchParams.deptId = val;
    },
    // 初始化数据
    init() {
      const params = {
        enableFlag: "Y",
      };
      return Promise.all([
        this.$axios.get(`${ApiConstant.PREFIX_CORE}/api/sys/org/tree`, {
          params,
        }), // 部门树结构
      ]).then(([treeRes]) => {
        this.treeData = treeRes.data.data;
      });
    },
    // 增加开始时间，结束时间
    handleAddItem() {
      const len = this.planTimeList.length;
      const tempObj = {
        planStartTime: "",
        planEndTime: "",
      };
      if (len > 0 && !this.planTimeList[len - 1].planEndTime) {
        this.$message.warning(
          `${this.$t("PLACESELECT")}${this.$t("TODO")}${this.$t("END_TIME")}`
        );
        return;
      }
      if (len > 0) {
        tempObj.planStartTime = this.planTimeList[len - 1].planEndTime;
      }
      this.planTimeList.push(tempObj);
    },
    // 删除增加对象展示字段
    handleDeleteItem(index) {
      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.planTimeList.splice(index, 1);
          if (this.planTimeList.length === 0) {
            this.planTimeList = [
              {
                planEndTime: "",
                planStartTime: "",
              },
            ];
          }
        },
      });
    },
    // 监听增加点检表单、点检对象点击事件
    handleAdd() {
      this.planFrmList.push({
        key: this.planFrmList.length,
        ...this.planFrmItem,
        pcObjectName: "xxx",
      });
    },
    // 监听删除接口参数事件
    handleDelete(item, index) {
      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.planFrmList.splice(index, 1);
        },
      });
    },
    // 监听选择点检表单组件
    handleSelectCheckObject() {
      this.$refs.SelectCheckObject.openDialog();
    },
    handleDisabledStartHours(item) {
      const hours = [];
      const time = moment(item.planEndTime).format("HH:mm");
      const timeArr = time.split(":");
      /* eslint-disable */
      for (let i = 0; i < 24; i++) {
        if (i > parseInt(timeArr[0])) {
          hours.push(i);
        }
      }
      /* eslint-enable */
      return () => hours;
    },
    // 监听禁用小时
    handleDisabledHours(item) {
      const hours = [];
      const time = moment(item.planStartTime).format("HH:mm");
      const timeArr = time.split(":");
      /* eslint-disable */
      for (let i = 0; i < parseInt(timeArr[0]); i++) {
        hours.push(i);
      }
      /* eslint-enable */
      return () => hours;
    },
    handleDisableStartMinutes(item) {
      const minutes = [];
      const time = moment(item.planStartTime).format("HH:mm");
      const endTime = moment(item.planEndTime).format("HH:mm");
      const timeArr = time.split(":");
      const endTimeArr = endTime.split(":");
      if (endTimeArr[0] === timeArr[0]) {
        /* eslint-disable */
        for (let i = 0; i < 60; i++) {
          if (i > parseInt(endTimeArr[1])) {
            minutes.push(i);
          }
        }
        /* eslint-enable */
      }
      return () => minutes;
    },
    // 监听禁用分钟
    handleDisabledMinutes(item) {
      const minutes = [];
      const time = moment(item.planStartTime).format("HH:mm");
      const endTime = moment(item.planEndTime).format("HH:mm");
      const timeArr = time.split(":");
      const endTimeArr = endTime.split(":");
      if (endTimeArr[0] === timeArr[0]) {
        /* eslint-disable */
        for (let i = 0; i < parseInt(timeArr[1]); i++) {
          minutes.push(i);
        }
        /* eslint-enable */
      }
      return () => minutes;
    },
    // 获取禁用时间，小时
    handleChangeEndTime(item) {
      if (item.planStartTime && item.planEndTime) {
        const startTime = moment(item.planStartTime).format("HH:mm");
        const endTime = moment(item.planEndTime).format("HH:mm");
        const startHour = startTime.split(":")[0];
        const startMin = startTime.split(":")[1];
        const endHour = endTime.split(":")[0];
        const endMin = endTime.split(":")[1];
        if (endHour < startHour) {
          this.$message.warning(this.$t("TODO_END_TIME_TIP"));
        } else if (endHour === startHour) {
          if (endMin < startMin) {
            this.$message.warning(this.$t("TODO_END_TIME_TIP"));
          }
        }
      }
    },
    // 监听保存按钮点击事件
    handleSave(type) {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const {
            pcPlanCode,
            pcPlanName,
            pcCategoryId,
            responsibleUser,
            responsibleDeptId,
            executeCycleType,
          } = this.form;
          const p = this.planTimeList.map((item, index) =>
            this.$refs[`ruleForm${index}`][0].validate()
          );
          Promise.all([...p]).then((res) => {
            if (res.every((item) => item)) {
              const ids = this.planFrmList.map((item) => item.pcFrmId);
              const idsSet = new Set(ids);
              if (idsSet.size !== ids.length) {
                this.$message.warning(
                  `${this.$t("CONTAINS_DUPLICATE")}${this.$t("CHECK_FORM")}`
                );
                return;
              }
              let executeCycleInterval = "";
              let executeCycleDay = "";
              /* eslint-disable */
              switch (executeCycleType) {
                case "D":
                  executeCycleInterval = this.form.executeCycleIntervalDay;
                  executeCycleDay = "";
                  break;
                case "W":
                  executeCycleInterval = this.form.executeCycleIntervalWeek;
                  executeCycleDay = this.form.executeCycleDayWeek.join(",");
                  break;
                case "M":
                  executeCycleInterval = this.form.executeCycleIntervalMonth;
                  executeCycleDay = this.form.executeCycleDayMonth.join(",");
                  break;
                case "S":
                  executeCycleInterval = "";
                  executeCycleDay = "";
                  break;
              }
              const planTimeList = [];
              this.planTimeList.forEach((item) => {
                planTimeList.push({
                  planStartTime: moment(item.planStartTime).format("HH:mm"),
                  planEndTime: moment(item.planEndTime).format("HH:mm"),
                });
              });
              const rangeDate = JSON.parse(JSON.stringify(this.form.rangeDate));
              /* eslint-enable */
              const params = {
                pcPlanCode,
                pcPlanName,
                pcCategoryId,
                responsibleUser,
                executeCycleType,
                responsibleDeptId,
                executeCycleInterval,
                executeCycleDay,
                planTimeList,
                planFrmList: this.planFrmList,
                effectTime:
                  `${moment(rangeDate[0]).format("YYYY-MM-DD")} 00:00:00` ||
                  null,
                expireTime:
                  `${moment(rangeDate[1]).format("YYYY-MM-DD")} 00:00:00` ||
                  null,
                type: "INSPECTION",
              };
              this.confirmLoading = true;
              this.$axios
                .post(`${ApiConstant.PREFIX_CORE}/api/epm/pcm/plan`, params)
                .then(() => {
                  this.confirmLoading = false;
                  this.$message.success(this.$t("SAVE_SUCCESS"));
                  if (type === "saveAndAdd") {
                    // this.form = {
                    //   pcPlanCode: "",
                    //   pcPlanName: "", // 名称
                    //   pcCategoryId: "", // 点检分类
                    //   responsibleUser: "", // 执行人
                    //   responsibleDeptId: "", // 部门
                    //   rangeDate: [], // 生效时间
                    //   executeCycleType: "D", // 执行周期类型：日(D);周(W);月(M);单次(S)
                    //   executeCycleIntervalDay: "0", // 执行周期间隔：单位：天
                    //   executeCycleIntervalWeek: "0", // 执行周期间隔：单位：周
                    //   executeCycleIntervalMonth: "0", // 执行周期间隔：单位：月
                    //   executeCycleDayWeek: [], // 执行周期具体执行日期：周几
                    //   executeCycleDayMonth: [], // 执行周期具体执行日期：几号
                    // };
                    // this.planFrmList = [];
                    // this.planTimeList = [];
                  } else {
                    this.handleCancel();
                  }
                })
                .catch((e) => {
                  this.confirmLoading = false;
                });
            }
          });
        }
      });
    },
    // 监听取消按钮点击事件
    handleCancel() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: {
          path: "/eam/eqp_check/partol_check_plan",
        },
        vm: this,
      });
    },
    // 页面埋点
    handleFuncUseRate(data) {
      this.$axios
        .put(`${ApiConstant.PREFIX_CORE}/api/epm/eam/use`, data)
        .then(() => {});
    },
  },
};
</script>
<style lang="less" scoped>
@import "@/assets/css/fault_repair.less";
/deep/ .mega-design-business-table .mega-design-pro-table {
  padding: 0 !important;
  margin-bottom: 24px;
}
/deep/ .ant-form-item-label {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.item {
  align-items: center;
  height: 56px;
  border: 2px dashed #dee9ec;
  padding: 20px 24px;
  margin: 0 0 24px 0;
  &:first-child {
    margin-top: 10px;
  }
  &:last-child {
    margin: 0;
  }
  &.active {
    border: 2px dashed #006896;
  }
  .item_con {
    align-items: center;
  }
}
/deep/ .ant-select.sitemore {
  height: 40px;
  line-height: 40px;
  margin-top: calc((40px - @input-height-base) / 2);
  .ant-select-selection--multiple {
    width: 100%;
    height: 32px;
    .ant-select-selection__rendered {
      height: 100%;
      ul {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow-y: hidden;
        display: -webkit-box;
        &::-webkit-scrollbar {
          width: 5px;
          height: 5px;
        }
        &::-webkit-scrollbar-track {
          background-color: #dedede;
          -webkit-border-radius: 1em;
          -moz-border-radius: 1em;
          border-radius: 1em;
        }
        &::-webkit-scrollbar-thumb {
          background-color: #bfbfbf;
          -webkit-border-radius: 1em;
          -moz-border-radius: 1em;
          border-radius: 1em;
        }
        & > li {
          padding: 0 18px 0 5px;
          box-sizing: border-box;
          min-width: 75px;
          float: unset;
        }
      }
    }
  }
}
</style>

<style lang="less">
.icon-bianji2 {
  color: @primary-color !important;
}
</style>
