<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="addPatrolPlanDialog"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    custom-class="ele-dialog-form"
    width="90%"
    v-loading="editLoading"
  >
    <div class="dialog_body">
      <el-form
        :model="addForm"
        ref="addFormRef"
        :rules="addFormRules"
        label-width="120px"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="计划单号" prop="code">
              <el-input
                v-model="addForm.code"
                placeholder="自动带出"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划名称" prop="name">
              <el-input v-model="addForm.name" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="自动派单" prop="autoOrder">
              <el-select v-model="addForm.autoOrder" style="width: 100%">
                <el-option :value="1" label="是"></el-option>
                <el-option :value="0" label="否"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="规则名称" prop="ruleId">
              <el-select
                v-model="addForm.ruleId"
                style="width: 100%"
                @change="handleRuleNameChange"
              >
                <el-option
                  v-for="item in ruleNameList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                  @click.native="handleClickRule(item)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划完成时长" prop="duration">
              <div style="display: flex">
                <el-input v-model="addForm.duration" placeholder="请输入">
                  <template #suffix>分钟</template>
                </el-input>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备分类" prop="categoryLevelId">
              <equipmentSelect
                v-model="addForm.categoryLevelId"
                @changeNode="chooseClassify"
                @setRootId="getRootId"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="设备类别" prop="categoryId">
              <el-select
                v-model="addForm.categoryId"
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="item in equipmentList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                  @click.native="handleEquipmentClassChange(item)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="审核人" prop="approvalUserId">
              <personSelect v-model="addForm.approvalUserId" />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="addForm.autoOrder">
            <el-form-item :label="formLabel + '部门'" prop="groupId">
              <deptSelect
                v-model="addForm.groupId"
                @change="searchDeptNodeClick"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="addForm.autoOrder">
            <el-form-item
              :label="formLabel + '人员'"
              prop="executorId"
              :rules="[
                { required: true, message: '请选择' + formLabel + '人员' }
              ]"
            >
              <personSelect
                ref="executorRef"
                v-model="addForm.executorId"
                :init="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                type="textarea"
                resize="none"
                v-model="addForm.remark"
                :rows="2"
                placeholder="请详细说明"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 设备分类 -->
      <div class="equipment_box">
        <div class="left_aside">
          <div class="equipment_list_title">设备列表</div>
          <div class="equipment_tree">
            <el-tree
              :data="planDeviceList"
              :props="defaultProps"
              ref="equiListTree"
              highlight-current
              node-key="id"
              @node-click="handleNodeClick"
              @check="handleCheck"
              show-checkbox
            ></el-tree>
          </div>
        </div>
        <div class="right_aside">
          <div class="equipment_info">
            <div class="item_info">
              <span class="item_label">设备编码</span>
              <span class="item_value">{{ equipmentInfo.equiCode }}</span>
            </div>
            <div class="item_info">
              <span class="item_label">设备名称</span>
              <span class="item_value">{{ equipmentInfo.equiName }}</span>
            </div>
            <div class="item_info">
              <span class="item_label">设备型号</span>
              <span class="item_value">{{ equipmentInfo.equiModel }}</span>
            </div>
            <div class="item_info">
              <span class="item_label">设备位置</span>
              <span class="item_value">{{ equipmentInfo.equiLocation }}</span>
            </div>
          </div>
          <!-- 添加操作事项 -->
          <div>
            <el-button type="text" @click="addOperationItems"
              >添加操作事项</el-button
            >
            <el-table
              :data="
                planDeviceList[currentEquItemIndex] &&
                planDeviceList[currentEquItemIndex].workItems
              "
              border
            >
              <el-table-column label="序号" align="center" width="60">
                <template slot-scope="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="事项" align="center" prop="name">
              </el-table-column>
              <el-table-column label="内容" align="center" prop="content">
              </el-table-column>
              <el-table-column label="标准" align="center" prop="norm">
              </el-table-column>
              <el-table-column label="操作" align="center" width="70">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    @click="handleDeleteOperationItem(scope.$index)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 添加备品备件 -->
          <div v-if="dialogTitle.includes('保养')">
            <el-button type="text" @click="addSpareItems"
              >添加备品备件</el-button
            >
            <el-table
              :data="
                planDeviceList[currentEquItemIndex] &&
                planDeviceList[currentEquItemIndex].sparePart
              "
              height="300"
              :key="currentEquItemIndex"
              border
            >
              <el-table-column label="序号" align="center" width="60">
                <template slot-scope="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="备件名称" align="center" prop="name">
              </el-table-column>
              <el-table-column label="规格型号" align="center" prop="modelType">
                <template slot-scope="{ row }">
                  <span>{{ row.specification }}/{{ row.modelType }}</span>
                </template>
              </el-table-column>
              <el-table-column label="所需数量" align="center" prop="needNum">
                <template slot-scope="scope">
                  <el-input
                    v-model.number="scope.row.needNum"
                    oninput="value=value.replace(/[^\d]/g,'')"
                    style="width: 100%"
                    placeholder="输入数量"
                    @input="changeNum"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="单位" align="center" prop="measuringUnit">
              </el-table-column>
              <el-table-column label="费用" align="center" prop="cost">
                <template slot-scope="scope">
                  {{ scope.row.cost
                  }}{{ scope.row.univalenceUnit == 'wanyuan' ? '万元' : '元' }}
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="70">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    @click="handleDeleteSpareItem(scope.$index)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <div style="text-align: center"
              >备件总费用：
              {{
                planDeviceList[currentEquItemIndex] &&
                planDeviceList[currentEquItemIndex].totalCost
                  ? planDeviceList[currentEquItemIndex].totalCost
                  : '-'
              }}
              元
            </div>
          </div>
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog_footer">
      <el-button type="primary" @click="submit">提交</el-button>
      <el-button @click="handleClose">关闭</el-button>
    </div>
    <RuleItemSelection
      ref="ruleItemSelectionRef"
      :selectedMatter="selectedMatter"
      :labelTitle="formLabel"
      @submit="ruleItemSelectionSubmit"
    />
    <AddSpareDialog
      ref="addSpareDialogRef"
      :selectedSpare="selectedSpare"
      @submit="spareItemSelectSubmit"
    />
  </el-dialog>
</template>

<script>
  import equipmentSelect from '@/components/CommomSelect/equipment-select.vue';
  import personSelect from '@/components/CommomSelect/person-select.vue';
  import deptSelect from '@/components/CommomSelect/dept-select.vue';
  import RuleItemSelection from '@/components/ruleItemSelection';
  import AddSpareDialog from '@/components/addSpareDialog';
  import {
    getRule,
    getCategory,
    getAssetList,
    getInfoById
  } from '@/api/ruleManagement/plan';
  import { getDetail, getCode } from '@/api/ruleManagement/matter';
  import { saveOrUpdate } from '@/api/maintenance/patrol_maintenance';
  import { deepClone } from '@/utils';
  import { getById } from '@/api/maintenance/patrol_maintenance';
  import { getList } from '@/api/classifyManage/itemInformation';
  import { planConfigPage } from '@/api/ruleManagement/plan';
  import { getTreeByType } from '@/api/classifyManage';
  export default {
    name: 'addPatrolPlanDialog',
    components: {
      // SelectTree,
      personSelect,
      deptSelect,
      equipmentSelect,
      RuleItemSelection,
      AddSpareDialog
    },
    props: {},
    data() {
      return {
        planCheckNodes: [],
        defaultProps: {
          label: 'showName'
        },
        addPatrolPlanDialog: false,
        equipmentInfo: {},
        clickedTreeNode: false,
        selectedMatter: [],
        selectedSpare: [],
        uerList: [],
        deptList: [],
        executorList: [],
        currentEquItemIndex: 0,
        formLabel: '',
        planRuleTypeObj: {
          1: 'PATROL',
          2: 'MAINTAIN',
          4: 'INVENTORY'
        },
        addForm: {
          assetDict: '1',
          assetsName: '生产设备',
          // code: getRuleNo('PL'), // 计划单号
          cycleType: 0,
          name: '', // 计划名称
          autoOrder: 1, // 自动派单
          ruleId: '', // 规则id
          ruleName: '', // 规则名称
          duration: '', // 计划完成时长
          categoryLevelId: '', // 设备分类Id
          bizTypeName: '', // 设备分类name
          approvalUserId: '', // 审核人id
          approvalUserName: '', // 审核人name
          groupId: '', // 巡点检部门code
          executorId: '', // 巡点检人员id
          remark: '', // 备注
          categoryId: '', //
          planType: 'PATROL' // 计划规则类型 巡点检: 'PATROL', 保养: 'MAINTAIN', 盘点: 'INVENTORY'
        },
        // 计划规则设备列表
        planDeviceList: [
          // {
          //   equiTypeId: '', // 设备分类Id
          //   equiTypeName: '', // 设备分类名字
          //   equiCode: '', // 设备编码 equCode
          //   equiName: '', // 设备名称 name
          //   equiModel: '', // 设备型号 specifications
          //   equiLocation: '', // 设备位置
          //   equiLocationCode: '', // 设备位置code
          //   // 设备备品备件 - 巡点检不需要备品备件，保养需要
          //   sparePart: [],
          //   totalCost: 0
          // }
        ],
        addFormRules: {
          name: [{ required: true, message: '请输入计划配置名称' }],
          autoOrder: [{ required: true, message: '请选择是否自动派单' }],
          ruleId: [{ required: true, message: '请选择规则名称' }],
          duration: [{ required: true, message: '请输入计划完成时长' }],
          categoryLevelId: [
            { required: true, message: '请选择设备分类', trigger: 'change' }
          ],
          approvalUserId: [
            { required: false, message: '请选择审核人', trigger: 'change' }
          ],
          groupId: [
            {
              required: true,
              message: '请选择选择巡点检部门',
              trigger: 'change'
            }
          ],
          categoryId: [
            { required: true, message: '请选择设备类别', trigger: 'change' }
          ]
        },
        ruleNameList: [],
        equipmentList: [],
        currentNode: null,
        rootId: null,
        dialogTitle: '新增保养计划配置',
        editLoading: false,
        rootData: []
      };
    },
    computed: {},
    async created() {},
    methods: {
      async open(title, row) {
        this.dialogTitle = title;
        this.formLabel = this.dialogTitle.includes('巡点检')
          ? '巡点检'
          : this.dialogTitle.includes('保养')
          ? '保养'
          : '盘点';
        const planRuleTypeObj = {
          巡点检: 'PATROL',
          保养: 'MAINTAIN',
          盘点: 'INVENTORY'
        };

        if (row?.id) {
          // 编辑
          this.addForm.id = row.id;

          await this.getInfo(this.addForm.id);

          const res = await getTreeByType(0); //设备数据
          this.rootData = res.data;
        } else {
          // 新增
          this.addForm.planType = planRuleTypeObj[this.formLabel];
          this.getOrderCode(this.dialogTitle);
        }
        // 获取规则名称
        this._getRuleNameList();
        this.addPatrolPlanDialog = true;
      },
      // 编辑详情
      async getInfo(id) {
        this.editLoading = true;
        const res = await getById(id).finally(() => {
          this.editLoading = false;
        });
        if (res?.data) {
          let data = res.data;
          if (data.executor && data.executor.length) {
            data.groupId = data.executor[0].groupName;
          }
          this.addForm = data;
          const params = { groupId: this.addForm.executor[0].groupId };
          setTimeout(async () => {
            await this.$refs.executorRef.getList(params);
            await this.chooseClassify(this.addForm.categoryLevelId);
          }, 100);
          this.categoryEquipment(this.addForm.categoryLevelId);

          if (this.dialogTitle == '编辑保养计划') {
            return;
          }
          if (this.rootId) {
            this._getEquipmentList();
          } else {
            const unwatch = this.$watch('rootId', () => {
              this._getEquipmentList();
              unwatch();
            });
          }
        }
      },
      // 获取计划配置单号
      async getOrderCode(tips) {
        if (tips.includes('巡点检')) {
          const data = await getCode('partrol_code');
          this.$set(this.addForm, 'code', data);
        }
        if (tips.includes('保养')) {
          const code = await getCode('maintenance_code');
          this.$set(this.addForm, 'code', code);
        }
      },
      // 获取规则名列表
      async _getRuleNameList() {
        if (this.dialogTitle == '新增巡点检计划') {
          console.log('巡点检计划');
          const res = await getRule({ type: 1, pageNum: 1, size: -1 });
          this.ruleNameList = res.list || [];
        }
        if (
          this.dialogTitle == '新增保养计划' ||
          this.dialogTitle == '编辑保养计划'
        ) {
          console.log('保养计划');
          // const res = await getRule({ type: 2, pageNum: 1, size: -1 });
          const res = await planConfigPage({
            pageNum: 1,
            size: -1,
            ruleType: 2
          });
          this.ruleNameList = res.list || [];
        }
      },
      handleClose() {
        this.addPatrolPlanDialog = false;
        this.$refs.addFormRef.resetFields();
        if (this.$refs.searchTree) {
          this.$refs.searchTree.clearHandle();
        }
        this.currentEquItemIndex = 0;
        this.equipmentInfo = {};
        this.addForm = {
          assetDict: '1',
          assetsName: '生产设备',
          // code: getRuleNo('PL'), // 计划单号
          cycleType: 0,
          name: '', // 计划名称
          autoOrder: 1, // 自动派单
          ruleId: '', // 规则id
          duration: null, // 计划完成时长
          categoryLevelId: '', // 设备分类Id
          bizTypeName: '', // 设备分类name
          approvalUserId: '', // 审核人id
          approvalUserName: '', // 审核人name
          groupId: '', // 巡点检部门code
          executorId: '', // 巡点检人员id
          remark: '', // 备注
          planType: 'PATROL' // 计划规则类型 巡点检: 'PATROL', 保养: 'MAINTAIN', 盘点: 'INVENTORY'
        };
      },
      getRootId(val, data) {
        // this.rootId = val;
        this.rootData = data;
      },
      // 设备分类选择
      async handleEquipmentClassChange(item) {
        this.clickedTreeNode = true;
        this.equipmentInfo = {};
        this._getEquipmentList(item.id);
      },

      // 获取设备分类数据
      async categoryEquipment(id) {
        const params = {
          searchKey: '',
          categoryLevelId: id,
          pageNum: 1,
          size: 99
        };
        const data = await getList(params);
        this.equipmentList = data.list;
      },
      // 分类树的选择
      chooseClassify(val) {
        this.clickedTreeNode = true;
        const id = this.findTopLevelAncestorId(this.rootData, val);
        this.rootId = id;
        this._getEquipmentList(val, this.isBindPlan);
        // this.categoryEquipment(val);
      },
      findTopLevelAncestorId(dataArray, targetId) {
        for (const item of dataArray) {
          const result = this.findTopLevelAncestorIdRecursive(
            item,
            targetId,
            item.id
          );
          if (result) {
            return result; // 返回找到的最顶层祖先的 ID
          }
        }

        return null;
      },

      findTopLevelAncestorIdRecursive(dataItem, targetId, topLevelAncestorId) {
        if (dataItem.id === targetId) {
          return topLevelAncestorId;
        }

        if (dataItem.children) {
          for (const child of dataItem.children) {
            const result = this.findTopLevelAncestorIdRecursive(
              child,
              targetId,
              topLevelAncestorId
            );
            if (result) {
              return result; // 返回找到的最顶层祖先的 ID
            }
          }
        }

        return null;
      },
      // 封装 - 获取设备分类列表
      async _getEquipmentList(val) {
        const params = {
          pageNum: 1,
          size: 999,
          categoryLevelId: val || this.addForm.categoryId,
          rootCategoryLevelId: this.rootId ? this.rootId : ''
        };
        try {
          const res = await getAssetList(params);
          this.addForm.categoryId = res.list[0]?.categoryId;
          this.planDeviceList = res.list;
          this.planDeviceList.map((item) => {
            item.showName = item.name + '(' + item.code + ')';
          });
          this.currentEquItemIndex = 0;
          const item = this.planDeviceList[0];
          const { equiLocation, equiLocationCode } = this.getEquiLocation(item);
          this.$nextTick(() => {
            this.$refs.equiListTree.setCurrentKey(item.id);
            this.equipmentInfo = {
              equiTypeId: this.addForm.categoryId,
              equiCode: item.code,
              equiName: item.name,
              equiModel: item.category.modelType,
              equiLocation: equiLocation,
              equiLocationCode: equiLocationCode
            };
            this.currentEquItemIndex = 0;
            this.planDeviceList[0]['equiLocation'] = equiLocation;
            this.planDeviceList[0]['equiLocationCode'] = equiLocationCode;

            // 对比详情返回的数据和设备分类下面所有的设备列表，将sparePart同步过去
            if (this.addForm.planDeviceList) {
              for (let i = 0; i < this.planDeviceList.length; i++) {
                for (let j = 0; j < this.addForm.planDeviceList.length; j++) {
                  if (
                    this.planDeviceList[i].id ===
                    this.addForm.planDeviceList[j].deviceId
                  ) {
                    this.$refs.equiListTree.setChecked(
                      this.planDeviceList[i].id,
                      true
                    );
                    this.planDeviceList[i]['workItems'] =
                      this.addForm.planDeviceList[j]['workItems'];
                    this.planDeviceList[i]['sparePart'] =
                      this.addForm.planDeviceList[j]['sparePart'];
                    this.$set(
                      this.planDeviceList[i],
                      'totalCost',
                      this.addForm.planDeviceList[j]['totalCost']
                    );
                    this.planDeviceList[i]['totalCost'] =
                      this.addForm.planDeviceList[j]['totalCost'];
                  }
                }
              }
            }
          });
        } catch (error) {
          this.planDeviceList = [];
        }
      },
      //选择部门(搜索)
      searchDeptNodeClick(info) {
        console.log('==info', info);
        // 根据部门获取人员
        const params = { groupId: info };
        this.$nextTick(() => {
          this.$refs.executorRef.getList(params);
        });
      },
      // 封装 - 获取设备位置名称和code方法
      getEquiLocation(data) {
        // 设备位置编码
        const equiLocationCode = data.position[0].pathIds;
        // 设备位置名称
        const equiLocation = data.position[0].pathName;
        return { equiLocation, equiLocationCode };
      },
      // 设备列表树点击
      handleNodeClick(data, node) {
        const { equiLocation, equiLocationCode } = this.getEquiLocation(data);
        this.equipmentInfo = {
          equiCode: data.code,
          equiName: data.name,
          deviceId: data.id,
          equiModel: data.category.modelType,
          equiLocation: equiLocation,
          equiLocationCode: equiLocationCode
        };
        // 保存当前点击的设备列表某节点的index，在添加操作事项的时候，可以将事项list放到对应的节点对象中，以及切换节点的时候回显事项list
        this.currentEquItemIndex = this.planDeviceList.findIndex(
          (item) => item.code === data.code
        );
        this.clickedTreeNode = true;
        this.planDeviceList[this.currentEquItemIndex]['equiLocation'] =
          equiLocation;
        this.planDeviceList[this.currentEquItemIndex]['equiLocationCode'] =
          equiLocationCode;
        console.log(this.planDeviceList);
      },
      // 规则名称下拉触发
      handleRuleNameChange(val) {
        console.log(val);
        // this._getMatterRulesDetails(val);
        this.$refs.ruleItemSelectionRef._getMatterRulesDetails(val);
      },

      // 从事项弹窗将数据丢到事项配置
      ruleItemSelectionSubmit(list) {
        if (list) {
          if (!this.planDeviceList[this.currentEquItemIndex]['workItems']) {
            this.planDeviceList[this.currentEquItemIndex]['workItems'] = [];
          }
          console.log('===', this.currentEquItemIndex);
          // this.planDeviceList[this.currentEquItemIndex]['workItems'] = list.map(
          //   (item) => {
          //     return {
          //       id: item.id,
          //       name: item.name,
          //       content: item.content,
          //       norm: item.norm
          //     };
          //   }
          // );
          this.planDeviceList.map((item) => {
            item.workItems = list;
          });
          console.log('submit', this.planDeviceList);
          this.$forceUpdate();
        }
      },

      // 添加操作事项
      addOperationItems() {
        if (!this.clickedTreeNode) {
          return this.$message.warning('请选择设备分类！');
        }
        if (!this.addForm.ruleId) {
          return this.$message.warning('请选择规则名称！');
        }
        if (this.planDeviceList[this.currentEquItemIndex]['workItems']) {
          this.selectedMatter =
            this.planDeviceList[this.currentEquItemIndex]['workItems'];
        } else {
          this.selectedMatter = [];
        }
        this.$refs.ruleItemSelectionRef.open();
      },

      // 删除操作事项
      handleDeleteOperationItem(index) {
        if (this.planDeviceList[this.currentEquItemIndex]['workItems']) {
          this.planDeviceList[this.currentEquItemIndex]['workItems'].splice(
            index,
            1
          );
        }
      },

      // 添加备品备件
      addSpareItems() {
        if (!this.clickedTreeNode) {
          return this.$message.warning('请选择设备分类！');
        }
        if (!this.addForm.ruleId) {
          return this.$message.warning('请选择规则名称！');
        }
        if (!this.addForm.ruleId) {
          return this.$message.warning('请选择规则名称！');
        }
        this.$refs.addSpareDialogRef.open();
        if (this.planDeviceList[this.currentEquItemIndex]['sparePart']) {
          this.selectedSpare =
            this.planDeviceList[this.currentEquItemIndex]['sparePart'];
        } else {
          this.selectedSpare = [];
        }
      },

      // 从备品备件弹窗将数据丢到备品备件配置
      spareItemSelectSubmit(list) {
        // console.log('备品备件：', list)
        // this.planDeviceList[this.currentEquItemIndex]['sparePart'] =
        //   list.map(item => {
        //     return {
        //       id: item.id,
        //       code: item.code,
        //       name: item.name,
        //       model: item.model,
        //       needNum: item.needNum,
        //       unit: item.unit,
        //       amount: item.amount
        //     }
        //   })
        this.planDeviceList[this.currentEquItemIndex]['sparePart'] = [
          ...deepClone(list)
        ];
        this.$forceUpdate();
      },

      // 删除备品备件
      handleDeleteSpareItem(index) {
        this.planDeviceList[this.currentEquItemIndex]['sparePart'].splice(
          index,
          1
        );
        this.changeNum();
      },
      handleClickRule(item) {
        console.log(item);
        this.addForm.ruleName = item.name;
        this.addForm.planConfigId = item.id;
      },
      // 改变input数据重新计算总费用
      changeNum() {
        let applayList =
          this.planDeviceList[this.currentEquItemIndex].sparePart;
        let total = 0;
        applayList.map((item, index) => {
          if (item.hasOwnProperty('needNum') && item.needNum != '') {
            switch (item.univalenceUnit) {
              case 'wanyuan': {
                item.chengs = 10000;
                break;
              }
              case 'yuan': {
                item.chengs = 1;
                break;
              }
              default:
                break;
            }
            const cost = item.needNum * item.univalence;

            this.$set(
              this.planDeviceList[this.currentEquItemIndex].sparePart[index],
              'cost',
              cost
            );

            total = total + cost * item.chengs;
          }
        });
        this.$set(
          this.planDeviceList[this.currentEquItemIndex],
          'totalCost',
          total
        );
      },
      handleCheck(val, row) {
        console.log(val);
        console.log(row);
        // this.planDeviceList = row.checkedNodes;
        this.planCheckNodes = row.checkedNodes;
      },
      // 提交
      submit() {
        console.log(this.planDeviceList);
        console.log('thi', this.planCheckNodes);
        // const items = this.planDeviceList[0].workItems;
        this.planDeviceList.forEach((item) => {
          // 判断是否存在 workItems 属性，如果不存在则添加一个空数组
          if (!item.workItems) {
            item.workItems = [];
          }

          // 判断 workItems 是否为空数组，如果为空则添加有数据的 workItems
          if (item.workItems.length === 0) {
            item.workItems.push(/* 添加有数据的 workItems，可以根据需求添加具体的数据 */);
          }
        });
        console.log('x修改', this.planDeviceList);
        if (
          this.dialogTitle == '编辑保养计划' &&
          this.planCheckNodes.length == 0
        ) {
          let arr = [];
          this.planDeviceList.map((item) => {
            this.addForm.planDeviceList.map((iem) => {
              if (item.id == iem.deviceId) {
                arr.push(item);
              }
            });
          });
          this.planCheckNodes = arr;
        }

        this.$refs.addFormRef.validate(async (valid) => {
          if (valid) {
            try {
              let workItemsChecked = true;
              const selectList = this.$refs.equiListTree.getCheckedNodes();
              if (!selectList.length) {
                this.$message.warning('请选择设备！');
                return;
              }
              const planDeviceList = selectList.map((item) => {
                const obj = this.planCheckNodes.find(
                  (itm) => itm.id === item.id
                );

                console.log('obj.workItems:', obj);
                if (!obj.workItems?.length) {
                  console.log(111);
                  workItemsChecked = false;
                }

                const { equiLocation, equiLocationCode } =
                  this.getEquiLocation(item);
                return {
                  equiCode: item.code,
                  equiName: item.name,
                  deviceId: item.id,
                  equiModel: item.modelType,
                  equiLocation: equiLocation,
                  equiLocationCode: equiLocationCode,
                  workItems: obj.workItems ? obj.workItems : [],
                  sparePart: obj.sparePart ? obj.sparePart : []
                };
              });
              if (!workItemsChecked || !selectList.length) {
                this.$message.warning('请添加操作事项！');
                return;
              }
              if (this.addForm.planType instanceof Object) {
                this.addForm.planType =
                  this.planRuleTypeObj[this.addForm.planType.code];
              }

              // 将newData拼接成一个新数组赋值给后端接收字段
              const params = this.addForm;
              params.planDeviceList = planDeviceList.map((item) => {
                item.sparePart = item.sparePart.map((item) => ({
                  categoryId: item.id,
                  categoryName: item.name,
                  cost: item.cost,
                  model: item.modelType,
                  needNum: item.needNum,
                  parValue: item.univalenceUnit,
                  specification: item.specification,
                  unit: item.measuringUnit,
                  unitPrice: item.univalence
                }));

                return item;
              });

              params.urgent = 1;

              params.type = this.dialogTitle.includes('巡点检')
                ? 1
                : this.dialogTitle.includes('保养')
                ? 2
                : 3;
              console.log('params', params);
              params.imageUrl = { ...params.imageUrl };
              await saveOrUpdate(params);
              const type = this.dialogTitle.includes('新增') ? '新增' : '编辑';
              this.handleClose();
              this.$message.success(type + '成功！');
              this.$emit('refreshList');
            } catch (error) {
              console.log(error);
            }
          }
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  ::v-deep .el-form {
    .el-form-item__error {
      padding-top: 0;
    }
  }
  .equipment_box {
    display: flex;
    .left_aside {
      width: 300px;
      border: 1px solid #797979;
      margin-right: 5px;
      .equipment_list_title {
        height: 24px;
        line-height: 24px;
        text-align: center;
        background-color: #d7d7d7;
        color: #000;
        font-weight: 700;
      }
      .equipment_tree {
        height: 510px;
        overflow: auto;
      }
      ::v-deep .el-tree-node__expand-icon.el-icon-caret-right {
        padding: 0;
      }
      ::v-deep
        .el-tree--highlight-current
        .el-tree-node.is-current
        > .el-tree-node__content {
        background-color: #d7f1fd !important;
      }
    }
    .right_aside {
      flex: 1;
      border: 1px solid #797979;
      padding: 10px;
      .equipment_info {
        display: flex;
        flex-wrap: wrap;
        border: 1px solid #ddd;
        .item_info {
          width: 33%;
          height: 24px;
          line-height: 24px;
          display: flex;
          .item_label {
            width: 90px;
            text-align: center;
            background-color: #f2f2f2;
            font-weight: 700;
          }
          .item_value {
            border-bottom: 1px solid #f2f2f2;
            flex: 1;
            padding-left: 5px;
          }
          &:last-child {
            width: 100%;
            .item_value {
              border: 0;
            }
          }
        }
      }
    }
  }
  .dialog_footer {
    text-align: center;
  }
</style>
