<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('MAINTENANCE_PLAN_CODE')}`"
                  prop="pmPlanCode"
                  allow-clear
                >
                  <a-input
                    v-model="form.pmPlanCode"
                    :placeholder="`${$t('SYSTEM_DEFAULT_CODE')}BYJH+${$t(
                      'NUMBER'
                    )}`"
                    @change="
                      form.pmPlanCode = form.pmPlanCode.slice(0, 50).trim()
                    "
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="`${$t('PLAN')}${$t('NAME')}`"
                  prop="pmPlanName"
                  allow-clear
                >
                  <a-input
                    v-model="form.pmPlanName"
                    :placeholder="$t('PLACEENTER')"
                    @change="
                      form.pmPlanName = form.pmPlanName.slice(0, 50).trim()
                    "
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('MAINTENANCE_TYPE')"
                  prop="pmCategoryId"
                >
                  <SelectSearch
                    :show-multiple="false"
                    request-api="/api/epm/pmm/pm-category/search"
                    option-label="pmCategoryName"
                    query-list-key="pmCategoryName"
                    :default-selected-keys="form.pmCategoryId"
                    :default-selected-names="form.pmCategoryName"
                    :is-show-add="true"
                    @change="onSelectSearchChange"
                    @add="onAddMaintainType"
                  >
                  </SelectSearch>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :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="planUserList"
                >
                  <template>
                    <div style="position: relative">
                      <select-user
                        ref="selectUser"
                        v-model="form.planUserList"
                        :multiple="true"
                        show-key="name"
                        :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"
              :whole="false"
              :auto-adaptive-width="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="pmFrmId" slot-scope="text, row, index">
                <SelectSearch
                  :show-multiple="false"
                  request-api="/api/epm/pmm/pm-frm/search"
                  option-label="pmFrmName,pmFrmVersion"
                  query-list-key="searchKey"
                  :default-selected-keys="row.pmFrmId"
                  :default-selected-names="row.pmFrmName"
                  @change="onSelectSearchChangePmForm($event, index)"
                >
                </SelectSearch>
              </template>
              <template slot="pmEquipmentName" slot-scope="text, row, index">
                <div style="position: relative">
                  <select-equipment
                    :key="row.key"
                    ref="SelectEquipment"
                    v-model="row.pmEquipmentName"
                    row-key="id"
                    show-key="eqpName"
                    :default-selected-rows="row.defaultSelectedRows"
                    :current-index="index"
                    @confirm="getReturnDataEquipment"
                  />
                </div>
              </template>
              <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"
                  @change="onSelectSearchChangeForm($event, index)"
                >
                </SelectSearch>
              </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-col
                :span="24"
                :label-col="{ span: 0 }"
                :wrapper-col="{ span: 24 }"
              >
                <div class="method-box flex">
                  <div
                    v-for="(item, index) in typeList"
                    :key="index"
                    class="method-card flex items-center justify-center"
                    :class="{ 'method-active': form.pmType === item.value }"
                    @click="onMethodChange(item.value)"
                  >
                    <div
                      v-if="item.value === 'TIME'"
                      class="method-icon iconfont icon-zhouqi"
                    ></div>
                    <div
                      v-if="item.value === 'USE_LIFE'"
                      class="method-icon iconfont icon-a-shouming2"
                    ></div>
                    <div>
                      {{ item.label }}
                      <div v-show="form.pmType === item.value" class="icon-box">
                        <div class="iconfont icon-gougou"></div>
                      </div>
                    </div>
                  </div>
                </div>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-form-model-item
                v-if="form.pmType === 'TIME'"
                :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
              v-if="form.pmType === 'TIME'"
              :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("MAINTENANCE_TASK") }}
                      </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") }} {{ $t("TODO") }}
                      </div>
                      <a-input-number
                        v-model="form.executeCycleNumWeek"
                        :min="0"
                      />
                      <div class="ml-5">
                        {{ $t("FREQUENCY") }}{{ $t("MAINTENANCE_TASK") }}
                      </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") }}{{ $t("TODO") }}
                      </div>
                      <a-input-number
                        v-model="form.executeCycleNumMonth"
                        :min="0"
                      />
                      <div class="ml-5">
                        {{ $t("FREQUENCY") }}{{ $t("MAINTENANCE_TASK") }}
                      </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-row v-if="form.pmType === 'USE_LIFE'" :gutter="24">
              <a-form-model-item
                :label="`${$t('EXECUTE_CYCLE')}`"
                :label-col="{ span: 2 }"
                :wrapper-col="{ span: 21 }"
                allow-clear
              >
                <div class="item flex">
                  <div class="item_con flex">
                    <div class="mr-5">{{ $t("EQUIPMENT_LIFE_REMAINING") }}</div>
                    <a-input-number
                      v-model="form.remainMonth"
                      :min="0"
                      :max="12"
                    />
                    <div class="ml-5 mr-5">{{ $t("MONTH") }}，</div>
                    <div class="ml-5 mr-5">
                      {{ $t("TASK") }}{{ $t("EFFECT_TIME") }}
                    </div>
                    <a-input-number v-model="form.expireDays" :min="0" />
                    <div class="ml-2">
                      {{ $t("DAY") }}
                    </div>
                  </div>
                </div>
              </a-form-model-item>
            </a-row>
          </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>
    <MegaDrawer
      width="520"
      :title="$t('ADD')"
      :visible="dialogVisble"
      :confirm-loading="confirmLoading"
      @close="dialogVisble = false"
      @cancel="dialogVisble = false"
      @ok="onSave"
    >
      <a-form-model
        slot="main"
        ref="dialogRuleForm"
        layout="vertical"
        :model="dialogForm"
        :rules="dialogRules"
      >
        <a-form-model-item :label="$t('CATEGORY_CODE')" prop="pmCategoryCode">
          <a-input
            v-model="dialogForm.pmCategoryCode"
            :placeholder="$t('PLACEENTER')"
            :disabled="dialogForm.id ? true : false"
            @change="
              dialogForm.pmCategoryCode = dialogForm.pmCategoryCode
                .slice(0, 50)
                .trim()
            "
          />
        </a-form-model-item>
        <a-form-model-item :label="$t('CATEGORY_NAME')" prop="pmCategoryName">
          <a-input
            v-model="dialogForm.pmCategoryName"
            :placeholder="$t('PLACEENTER')"
            @change="
              dialogForm.pmCategoryName = dialogForm.pmCategoryName
                .slice(0, 50)
                .trim()
            "
          />
        </a-form-model-item>
      </a-form-model>
    </MegaDrawer>
  </div>
</template>

<script>
import { mapState } from "vuex";
import moment from "moment";
import { Drawer as MegaDrawer } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import breadcrumb from "@/components/breadcrumb";
import SelectEquipment from "@/components/SelectEquipment";

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

export default {
  components: {
    breadcrumb,
    MegaDrawer,
    SelectEquipment,
    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",
      dialogVisble: false,
      confirmLoading: false,
      dataSource: [],
      columns: [
        {
          dataIndex: "pmFrmId", // 保养表单
          title: () => this.$t("MAINTENANCE_FORM"),
          sorter: false,
          scopedSlots: { customRender: "pmFrmId" },
        },
        {
          dataIndex: "pcFrmId", // 点检表单
          title: () => this.$t("CHECK_FORM"),
          sorter: false,
          scopedSlots: { customRender: "pcFrmId" },
        },
        {
          dataIndex: "pmEquipmentName", // 保养设备清单
          title: () => this.$t("EQUIPMENT_LIST"),
          sorter: false,
          scopedSlots: { customRender: "pmEquipmentName" },
        },
      ],
      form: {
        pmPlanCode: "", // 编码
        pmPlanName: "", // 名称
        pmCategoryId: "", // 点检分类
        planUserList: [], // 执行人
        responsibleDeptId: "", // 部门
        pmType: "", // 保养类型
        rangeDate: [], // 生效时间
        executeCycleType: "D", // 执行周期类型：日(D);周(W);月(M);单次(S)
        executeCycleIntervalDay: "0", // 执行周期间隔：单位：天
        executeCycleIntervalWeek: "0", // 执行周期间隔：单位：周
        executeCycleIntervalMonth: "0", // 执行周期间隔：单位：月
        executeCycleNumWeek: "", // 执行任务次数 周
        executeCycleNumMonth: "", // 执行任务次数 月
        remainMonth: "", // 引起触发生成任务使用寿命剩余月数
        expireDays: "", // 按寿命生成的任务执行期限
      },
      // 保养表单列表
      planFrmList: [],
      planFrmItem: {
        pmFrmId: "", // 保养表单id
        pmFrmName: "",
        pcFrmId: "", // 点检表单id
        pcFrmName: "",
        pmEquipmentName: "", // 保养设备名称
        pmEquipmentList: [], // 保养设备列表
        defaultSelectedRows: [], // 默认选中数据
      },
      // 对象展示字段列表
      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>
        ),
      ],
      selectedUser: [],
      treeData: [],
      treeProps: {
        value: "id",
        children: "children",
        label: "label",
      },
      typeList: [], // 保养类型列表
      searchParams: {
        deptId: "",
      },
      dialogForm: {
        id: null,
        pmCategoryCode: "",
        pmCategoryName: "",
      },
    };
  },
  computed: {
    ...mapState("setting", ["multiPage"]),
    dialogRules() {
      return {
        pmCategoryName: [
          {
            required: true,
            max: 50,
            message: this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
      };
    },
    rules() {
      return {
        pmPlanName: [
          {
            required: true,
            max: 50,
            message: () => this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        pmCategoryId: [
          {
            required: false,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        rangeDate: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
      };
    },
  },
  mounted() {
    const { id } = this.$route.query;
    if (id) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/pmm/plan/get-by-id/${id}`)
        .then((detailRes) => {
          /* eslint-disable */
          const {
            effectTime,
            expireTime,
            executeCycleType,
            executeCycleInterval,
            executeCycleNum,
            planFrmList,
            planUserList,
            planUserNameList,
          } = detailRes.data?.data;
          this.searchParams.deptId =
            detailRes.data?.data?.responsibleDeptId || "";
          this.form = { ...detailRes.data?.data, rangeDate: [] };
          this.form.id = "";
          this.form.pmPlanCode = "";
          // 保养表单列表 开始
          if (planFrmList && planFrmList.length > 0) {
            const planFrmItem = {
              ...this.planFrmItem,
            };
            // const arrList = this.checkSameData(planFrmList);
            const arrList = [...planFrmList];
            let pcFormIdArr = [];
            arrList.forEach((item) => {
              const findex = pcFormIdArr.findIndex(
                (itemA) => itemA.pmFrmId === item.pmFrmId
              );
              if (findex > -1) {
                pcFormIdArr[findex].pmEquipmentList.push({
                  id: item.pmEqpId,
                  eqpCode: item.pmEqpCode,
                  eqpName: item.pmEqpName,
                });
              } else {
                pcFormIdArr.push({
                  pmFrmId: item.pmFrmId,
                  pmFrmName: item.pmFrmName,
                  pcFrmId: item.pcFrmId,
                  pcFrmName: item.pcFrmName,
                  pmEquipmentList: [
                    {
                      id: item.pmEqpId,
                      eqpCode: item.pmEqpCode,
                      eqpName: item.pmEqpName,
                    },
                  ],
                });
              }
            });
            this.planFrmList = pcFormIdArr.map((item) => {
              item.defaultSelectedRows = item.pmEquipmentList;
              return item;
            });
          }
          // 保养表单 结束
          // 保养人员 开始
          if (planUserList && planUserList.length > 0) {
            let tempObj;
            this.selectedUser = planUserList.map((item, uIdx) => {
              tempObj = {
                userName: item,
                name: planUserNameList[uIdx],
              };
              return tempObj;
            });
          }
          // 保养人员 结束
          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,
              };
              this.form.executeCycleNumWeek = executeCycleNum;
              break;
            case "M":
              tempObj = {
                executeCycleType,
                executeCycleIntervalMonth: executeCycleInterval,
              };
              this.form.executeCycleNumMonth = executeCycleNum;
              break;
          }
          this.form = Object.assign(this.form, tempObj);
          this.$forceUpdate();
          /* eslint-enable */
        });
    }
    // 初始化数据
    this.init();
  },
  methods: {
    disabledDate(current) {
      return current < moment().subtract(1, "day"); // 当天之前的不可选，不包括当天
    },
    // 获取返回数据，点检分类
    onSelectSearchChange(e) {
      this.form.pmCategoryId = e;
    },
    onAddMaintainType() {
      this.dialogForm = {
        id: null,
        pmCategoryCode: "",
        pmCategoryName: "",
      };
      this.dialogVisble = true;
    },
    // 获取返回数据，保养表单
    onSelectSearchChangePmForm(e, index) {
      this.planFrmList[index].pmFrmId = e;
    },
    // 获取返回数据，点检表单
    onSelectSearchChangeForm(e, index) {
      this.planFrmList[index].pcFrmId = e;
    },
    // 获取选择用户组件返回数据
    getReturnData(selectedKeys, selectedRows) {
      this.form.planUserList = selectedKeys;
      this.selectedUser = selectedRows;
    },
    // 获取选择保养设备组件返回数据
    getReturnDataEquipment(selectedKeys, selectedRows, currentIndex) {
      this.planFrmList[currentIndex].defaultSelectedRows = selectedRows;
      /* eslint-disable */
      if (selectedRows.length > 0) {
        this.planFrmList[currentIndex].pmEquipmentName = selectedKeys.join(",");
        this.planFrmList[currentIndex].pmEquipmentList = [...selectedRows];
      } else {
        this.planFrmList[currentIndex].pmEquipmentName = "";
        this.planFrmList[currentIndex].pmEquipmentList = [];
      }
      /* 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,
        }), // 部门树结构
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:PM_TYPE`
        ), // 保养方式
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/epm/ebs/switch-config/get-config/ENABLE_PM_WITH_PC`
        ), // 功能配置
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/epm/ebs/switch-config/get-config/ENABLE_PM_BY_LIFE`
        ), // 功能配置
      ]).then(([treeRes, typeRes, configRes, pmLifeRes]) => {
        this.treeData = treeRes.data.data;
        this.form.pmType = typeRes.data.data[0]?.value;
        this.typeList = typeRes.data.data;
        if (!configRes?.data?.data) {
          this.columns.splice(1, 1);
        }
        if (!pmLifeRes?.data?.data) {
          this.typeList.splice(1, 1);
        }
      });
    },
    // 监听增加保养表单、保养设备点击事件
    handleAdd() {
      this.planFrmList.push({
        key: this.planFrmList.length,
        ...this.planFrmItem,
      });
    },
    // 监听删除接口参数事件
    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);
        },
      });
    },
    // 监听选择保养表单组件
    handleSelectEquipment() {
      this.$refs.SelectEquipment.openDialog();
    },
    onMethodChange(e) {
      this.form.pmType = e;
    },
    // 监听弹框保存事件
    onSave() {
      this.$refs.dialogRuleForm.validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          this.$axios
            .post(
              `${ApiConstant.PREFIX_CORE}/api/epm/pmm/pm-category`,
              this.dialogForm
            )
            .then(({ data }) => {
              this.$message.success(this.$t("ADD_SUCCESS"));
              this.form.pmCategoryId = data.data;
              this.form.pmCategoryName = this.dialogForm.pmCategoryName;
              this.dialogVisble = false;
              this.confirmLoading = false;
              this.$refs.ruleForm.validateField("pmCategoryId");
            })
            .catch((e) => {
              this.confirmLoading = false;
            });
        }
      });
    },
    // 监听保存按钮点击事件
    handleSave(type) {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const {
            pmPlanCode,
            pmPlanName,
            pmCategoryId,
            pmType,
            executeCycleNumWeek,
            executeCycleNumMonth,
            planUserList,
            responsibleDeptId,
            executeCycleType,
            remainMonth,
            expireDays,
          } = this.form;
          const ids = this.planFrmList.map((item) => item.pmFrmId);
          const idsSet = new Set(ids);
          if (idsSet.size !== ids.length) {
            this.$message.warning(
              `${this.$t("CONTAINS_DUPLICATE")}${this.$t("MAINTENANCE_FORM")}`
            );
            return;
          }
          const arr = [];
          let tempObj;
          let tempReault = true;
          if (this.planFrmList.length > 0) {
            this.planFrmList.forEach((item) => {
              if (item.pmEquipmentList.length > 0) {
                if (item.pmEquipmentList.some((val) => val.pmFrmId === "")) {
                  this.$message.warning(
                    `${this.$t("PLACEENTER")}${this.$t("MAINTENANCE_FORM")}`
                  );
                  return;
                }
                if (
                  item.pmEquipmentList.some((val) => val.pmEquipmentName === "")
                ) {
                  this.$message.warning(
                    `${this.$t("PLACESELECT")}${this.$t("EQUIPMENT_LIST")}`
                  );
                  return;
                }
                item.pmEquipmentList.forEach((ele) => {
                  tempObj = {
                    pmFrmId: item.pmFrmId,
                    pcFrmId: item.pcFrmId,
                    pmEqpId: ele.id,
                    pmEqpCode: ele.eqpCode,
                    pmEqpName: ele.eqpName,
                  };
                  arr.push(tempObj);
                });
              } else {
                tempReault = false;
              }
            });
          }
          if (!tempReault) {
            this.$message.warning(
              `${this.$t("PLACESELECT")}${this.$t("EQUIPMENT_LIST")}`
            );
            return;
          }
          let executeCycleInterval = "";
          let executeCycleNum = "1";
          /* eslint-disable */
          switch (executeCycleType) {
            case "D":
              executeCycleInterval = this.form.executeCycleIntervalDay;
              break;
            case "W":
              executeCycleInterval = this.form.executeCycleIntervalWeek;
              executeCycleNum = executeCycleNumWeek;
              break;
            case "M":
              executeCycleInterval = this.form.executeCycleIntervalMonth;
              executeCycleNum = executeCycleNumMonth;
              break;
            case "S":
              executeCycleInterval = "";
              break;
          }
          const rangeDate = JSON.parse(JSON.stringify(this.form.rangeDate));
          /* eslint-enable */
          const params = {
            pmPlanCode,
            pmPlanName,
            pmCategoryId,
            pmType,
            executeCycleNum,
            planUserList,
            executeCycleType,
            responsibleDeptId,
            executeCycleInterval,
            planFrmList: arr,
            effectTime:
              `${moment(rangeDate[0]).format("YYYY-MM-DD")} 00:00:00` || null,
            expireTime:
              `${moment(rangeDate[1]).format("YYYY-MM-DD")} 00:00:00` || null,
            remainMonth,
            expireDays,
          };
          this.confirmLoading = true;
          this.$axios
            .post(`${ApiConstant.PREFIX_CORE}/api/epm/pmm/plan`, params)
            .then(() => {
              this.confirmLoading = false;
              this.$message.success(this.$t("SAVE_SUCCESS"));
              if (type === "saveAndAdd") {
                // this.form = {
                //   id: null,
                //   pmPlanCode: "", // 编码
                //   pmPlanName: "", // 名称
                //   pmCategoryId: "", // 点检分类
                //   planUserList: [], // 执行人
                //   responsibleDeptId: "", // 部门
                //   pmType: this.typeList[0]?.value, // 保养类型
                //   rangeDate: [], // 生效时间
                //   executeCycleType: "D", // 执行周期类型：日(D);周(W);月(M);单次(S)
                //   executeCycleIntervalDay: "0", // 执行周期间隔：单位：天
                //   executeCycleIntervalWeek: "0", // 执行周期间隔：单位：周
                //   executeCycleIntervalMonth: "0", // 执行周期间隔：单位：月
                //   executeCycleNumWeek: "", // 执行任务次数 周
                //   executeCycleNumMonth: "", // 执行任务次数 月
                //   remainMonth: "", // 引起触发生成任务使用寿命剩余月数
                //   expireDays: "", // 按寿命生成的任务执行期限
                // };
                // this.planFrmList = [];
                // this.selectedUser = [];
              } else {
                this.handleCancel();
              }
            })
            .catch((e) => {
              this.confirmLoading = false;
            });
        }
      });
    },
    // 监听取消按钮点击事件
    handleCancel() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: {
          path: "/eam/eqp_maintain/maintenance_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;
  }
}
</style>

<style lang="less">
.method-box {
  margin: 30px 0;
  margin-left: 100px;
}
.method-card {
  position: relative;
  margin-right: 50px;
  width: 200px;
  height: 80px;
  background: #fff;
  color: #c0c4cc;
  border: 1px solid #c0c4cc;
  opacity: 1;
  border-radius: 4px;
  cursor: pointer;
}
.method-active {
  border: 1px solid #006896;
  color: #006896;
}
.method-icon {
  font-size: 50px;
  margin-right: 20px;
}
</style>
