<!--
 * @Author: ysh
 * @Date: 2024-03-07 13:44:39
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2026-05-22 09:55:39
-->

<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="flowDisabled ? 18 : 24" :xs="24">
        <h2 class="text-center">设备申请表</h2>
        <el-divider></el-divider>
        <el-form ref="deviceForm" :model="form" :rules="rules" :disabled="formDisabled" class="borrow-table-form">
          <div class="form-table-wrap">
            <table class="form-table">
              <tr>
                <td colspan="2" class="label-cell">申请人</td>
                <td colspan="2">
                  <el-form-item prop="user.nickName" class="table-form-item">
                    {{ form.applierUser ? form.applierUser.nickName : form.user.nickName }}
                  </el-form-item>
                </td>
                <td colspan="2" class="label-cell">所在部门</td>
                <td colspan="2">
                  <el-form-item prop="dept.deptName" class="table-form-item">
                    {{ form.dept.deptName }}
                  </el-form-item>
                </td>
                <td colspan="2" class="label-cell">申请时间</td>
                <td colspan="2">
                  <el-form-item prop="applyDate" class="table-form-item">
                    <el-date-picker style="width: 100%;" v-model="form.applyDate" value-format="yyyy-MM-dd" type="date"
                      placeholder="选择日期" disabled>
                    </el-date-picker>
                  </el-form-item>
                </td>
              </tr>
              <tr>
                <td colspan="2" class="label-cell">项目信息</td>
                <td colspan="10">
                  <el-button type="primary" size="mini" @click="openProject = true"
                    v-if="taskName == '设备申请'">选择项目</el-button>
                  <table class="inner-table" v-if="isSelect && chooseProject">
                    <tr>
                      <td class="label-cell">项目编号</td>
                      <td>{{ chooseProject.projectNumber }}</td>
                      <td class="label-cell">项目名称</td>
                      <td>{{ chooseProject.projectName }}</td>
                    </tr>
                    <tr>
                      <td class="label-cell">项目负责人</td>
                      <td>{{ chooseProject.projectLeaderUser ? chooseProject.projectLeaderUser.nickName : '' }}</td>
                      <td class="label-cell">承担部门</td>
                      <td>{{ chooseProject.undertakingDeptName }}</td>
                    </tr>
                    <tr>
                      <td class="label-cell">项目类型</td>
                      <td colspan="3">{{ chooseProject.projectType }}</td>
                    </tr>
                  </table>
                  <el-form-item prop="projectId" class="table-form-item" style="display: none;"></el-form-item>
                </td>
              </tr>
              <tr>
                <td colspan="2" class="label-cell">设备选择</td>
                <td colspan="10">
                  <el-form-item prop="devices" class="table-form-item">
                    <el-button type="primary" icon="el-icon-plus" size="mini" @click="openDevice = true"
                      :disabled="taskName != '设备申请'">选择设备</el-button>
                    <el-table class="embed-table" :data="deviceList" size="small" border>
                      <el-table-column label="序号" type="index" width="55" align="center" />
                      <el-table-column label="出厂编号" align="center" prop="code" min-width="100" />
                      <el-table-column label="设备品牌" align="center" prop="brand" min-width="90" />
                      <el-table-column label="设备名称" align="center" prop="name" min-width="100" />
                      <el-table-column label="规格型号" align="center" prop="series" min-width="90" />
                      <el-table-column label="存放地址" align="center" prop="place" min-width="100" />
                    </el-table>
                  </el-form-item>
                </td>
              </tr>
              <tr>
                <td colspan="2" class="label-cell">申领事由</td>
                <td colspan="10">
                  <el-form-item prop="applyReason" class="table-form-item">
                    <el-input type="textarea" :rows="3" placeholder="请输入申领事由" v-model="form.applyReason"
                      :disabled="taskName != '设备申请'">
                    </el-input>
                  </el-form-item>
                </td>
              </tr>
              <tr>
                <td colspan="2" class="label-cell">开始日期</td>
                <td colspan="2">
                  <el-form-item prop="beginDate" class="table-form-item">
                    <el-date-picker style="width: 100%;" v-model="form.beginDate" value-format="yyyy-MM-dd" type="date"
                      placeholder="选择日期" @change="calculateDay" :disabled="taskName != '设备申请'">
                    </el-date-picker>
                  </el-form-item>
                </td>
                <td colspan="2" class="label-cell">结束日期</td>
                <td colspan="2">
                  <el-form-item prop="endDate" class="table-form-item">
                    <el-date-picker style="width: 100%;" v-model="form.endDate" value-format="yyyy-MM-dd" type="date"
                      placeholder="选择日期" @change="calculateDay" :disabled="taskName != '设备申请'">
                    </el-date-picker>
                  </el-form-item>
                </td>
                <td colspan="2" class="label-cell">共计</td>
                <td colspan="2">{{ form.days }} 天</td>
              </tr>
              <tr>
                <td colspan="2" class="label-cell">拟发放设备</td>
                <td colspan="10">
                  <el-form-item prop="modifyDevices" class="table-form-item">
                    <el-table class="embed-table" :data="modifyDeviceList" size="small" border>
                      <el-table-column label="序号" type="index" width="55" align="center" />
                      <el-table-column label="出厂编号" align="center" prop="code" min-width="100" />
                      <el-table-column label="设备品牌" align="center" prop="brand" min-width="90" />
                      <el-table-column label="设备名称" align="center" prop="name" min-width="100" />
                      <el-table-column label="规格型号" align="center" prop="series" min-width="90" />
                      <el-table-column label="存放地址" align="center" prop="place" min-width="100" />
                      <el-table-column label="操作" align="center" width="140" v-if="taskName == '安排设备'">
                        <template slot-scope="scope">
                          <el-button type="text" @click="replaceRowData(scope.row, scope.$index)">重新选择</el-button>
                          <el-button type="text" style="color: #F56C6C;"
                            @click="deleteRowData(scope.row, scope.$index)">删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <el-button class="mt10" type="primary" size="mini" @click="addRowdata()" icon="el-icon-plus"
                      :disabled="taskName != '安排设备'">新增设备</el-button>
                  </el-form-item>
                </td>
              </tr>
              <tr>
                <td colspan="2" class="label-cell">安排设备意见</td>
                <td colspan="10">
                  <el-form-item prop="dispatchComment" class="table-form-item">
                    <el-input type="textarea" :rows="3" placeholder="请输入安排设备意见" v-model="form.dispatchComment"
                      :disabled="taskName != '安排设备'">
                    </el-input>
                  </el-form-item>
                  <el-row class="sign-line" v-if="taskName != '设备申请' || (taskName == '' && form.dispatchUser)">
                    <el-col :span="6" :offset="11">
                      签名：<span class="auditor">{{ form.dispatchUser ? form.dispatchUser.nickName : dispatchUser }}</span>
                    </el-col>
                    <el-col :span="6">
                      日期：<span>{{ form.dispatchTime ? form.dispatchTime : dispatchTime }}</span>
                    </el-col>
                  </el-row>
                </td>
              </tr>
              <tr>
                <td colspan="2" class="label-cell">分管审核意见</td>
                <td colspan="10">
                  <el-form-item prop="managerComment" class="table-form-item">
                    <el-input type="textarea" :rows="3" placeholder="请输入分管审核意见" v-model="form.managerComment"
                      :disabled="taskName != '分管审核'">
                    </el-input>
                  </el-form-item>
                  <el-row class="sign-line">
                    <el-col :span="6" :offset="11">
                      签名：<span class="auditor">{{ form.managerUser ? form.managerUser.nickName : managerUser }}</span>
                    </el-col>
                    <el-col :span="6">
                      日期：<span>{{ form.managerTime ? form.managerTime : managerTime }}</span>
                    </el-col>
                  </el-row>
                </td>
              </tr>
              <tr>
                <td colspan="2" class="label-cell">已归还设备</td>
                <td colspan="10">
                  <el-table ref="returnDevicesRef" class="embed-table" :data="returnDevicesList" size="small" border
                    row-key="deviceId" @selection-change="handleSelectionReturn">
                    <el-table-column v-if="taskName == '归还确认'" type="selection" width="55" :selectable="checkReturnSelectable" />
                    <el-table-column v-else label="归还状态" width="100" align="center">
                      <template slot-scope="scope">
                        <span class="return-status is-returned" v-if="isDeviceReturned(scope.row)">
                          <i class="el-icon-success"></i>已归还
                        </span>
                        <span class="return-status is-pending" v-else>
                          <i class="el-icon-remove-outline"></i>未归还
                        </span>
                      </template>
                    </el-table-column>
                    <el-table-column label="序号" type="index" width="55" align="center" />
                    <el-table-column label="出厂编号" align="center" prop="code" min-width="100" />
                    <el-table-column label="设备品牌" align="center" prop="brand" min-width="90" />
                    <el-table-column label="设备名称" align="center" prop="name" min-width="100" />
                    <el-table-column label="规格型号" align="center" prop="series" min-width="90" />
                    <el-table-column label="存放地址" align="center" prop="place" min-width="100" />
                  </el-table>
                </td>
              </tr>
              <tr>
                <td colspan="2" class="label-cell">需维修设备</td>
                <td colspan="10">
                  <el-form-item prop="repairDevices" class="table-form-item">
                    <el-select style="width: 100%;" v-model="form.repairDevices" filterable multiple placeholder="请选择"
                      clearable :disabled="taskName != '归还确认'">
                      <el-option v-for="item in modifyDeviceList" :key="item.deviceId"
                        :label="item.name + '【' + (item.brand != null ? item.brand : '') + (item.series != null ? '-' + item.series + '】' : '')
                          + (item.code != null ? '（设备编号：' + item.code + '）' : '') + '📍' + item.place"
                        :value="item.deviceId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </td>
              </tr>
              <tr>
                <td colspan="2" class="label-cell">备注</td>
                <td colspan="10">
                  <el-form-item prop="remark" class="table-form-item">
                    <el-input type="textarea" :rows="3" placeholder="请输入备注" v-model="form.remark"
                      :disabled="taskName != '归还确认'">
                    </el-input>
                  </el-form-item>
                </td>
              </tr>
              <tr>
                <td colspan="2" class="label-cell">归还日期</td>
                <td colspan="10">
                  <el-form-item prop="returnDate" class="table-form-item">
                    <el-date-picker style="width: 240px;" v-model="form.returnDate" value-format="yyyy-MM-dd" type="date"
                      placeholder="选择日期" :disabled="taskName != '归还确认'">
                    </el-date-picker>
                  </el-form-item>
                </td>
              </tr>
            </table>
          </div>
        </el-form>
        <div class="form-footer" v-if="taskName == '设备申请'">
          <el-button type="primary" @click="submit">提交申请</el-button>
        </div>
        <div class="form-footer" v-else-if="taskName">
          <el-button type="warning" @click="saves()">保存</el-button>
          <el-button type="primary" @click="completeApply()">完成审批</el-button>
        </div>
      </el-col>
      <el-col :span="6" :xs="24" v-if="flowDisabled">
        <el-card>
          <h2 style="text-align: center;">流程进度</h2>
          <div>
            <flow :flowData="flowData" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog title="选择项目" :visible.sync="openProject" width="70%" append-to-body>
      <project-choose @chooseProject="confirmProject"></project-choose>
    </el-dialog>
    <el-dialog title="选择仪器" :visible.sync="openDevice" width="70%" append-to-body>
      <choose-device :multiple="multiple" @chooseList="confirmDevice"></choose-device>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from "@/utils/ruoyi";
import { listProject, getProject } from "@/api/oa/project/project";
import { listDevice, getDevice } from "@/api/oa/device/device";
import { listDeviceApproval, getDeviceApproval, updateDeviceApproval, submitDeviceApproval, modifyDeviceApproval } from '@/api/oa/device/deviceApproval'
import {
  complete, rejectTask, returnList, returnTask, getNextFlowNode, delegate, flowTaskForm,
} from "@/api/flowable/todo";
import { getUsersManageLeader } from '@/api/system/post.js'
import flow from '@/views/flowable/task/todo/detail/flow'
import { flowXmlAndNode } from "@/api/flowable/definition";
import { getUserByRole } from "@/api/system/role";
import { sendQyMessage } from "@/api/qywx/index";
import { getUser } from "@/api/system/user";
import projectChoose from '@/views/flowable/form/components/chooseProject.vue';
import ChooseDevice from '../budget/components/chooseDevice.vue';
export default {
  components: {
    flow,
    projectChoose,
    ChooseDevice
  },
  props:
  {
    taskName: {
      type: String,
      required: true
    },
    taskForm: {
      type: Object,
      required: true
    },
    flowDisabled: {
      type: Boolean,
      default: true
    },
    formDisabled: {
      type: Boolean,
      default: false
    }
  },
  created() {
    if (this.taskName == '分管审核') {
      this.managerUser = this.$store.getters.name;
      this.managerTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    if (this.taskName == '安排设备') {
      this.dispatchUser = this.$store.getters.name;
      this.dispatchTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    this.form.user.nickName = this.$store.getters.name;
    this.form.dept.deptName = this.$store.getters.deptName;
    this.getProjectList();
    // this.getDeviceList();
    if (this.flowDisabled)
      flowXmlAndNode({ procInsId: this.taskForm.procInsId, deployId: this.taskForm.deployId }).then(res => {
        this.flowData = res.data;
      })
  },
  data() {
    return {
      managerUser: '',
      dispatchUser: '',
      managerTime: undefined,
      dispatchTime: undefined,
      form: {
        user: {
          nickName: '',
        },
        dept: {
          deptName: '',
        },
        applyDate: new Date(),
        days: "",
        devices: [],
        modifyDevices: [],
      },
      projectList: [],
      chooseProject: {},
      flowData: {},
      isSelect: false,
      openProject: false,
      openDevice: false,
      rules: {
      },
      deviceList: [],
      grantDeviceList: [],
      modifyDeviceList: [],
      returnDevicesList: [],
      formTotal: 0,
      clicDevice: {},
      clickRowIndex: 0,
      multiple: true,
      isSyncingReturnSelection: false,
    }
  },
  watch: {
    'taskForm.formId'() {
      this.initForm();
    },
    returnDevicesList() {
      this.trySyncReturnDeviceSelection();
    },
    taskName(val) {
      if (val == '归还确认') {
        this.trySyncReturnDeviceSelection();
      }
    }
  },
  mounted() {
    this.initRules();
    this.initForm();
  },
  computed: {
    returnedDeviceIdSet() {
      const rd = this.form.returnDevices;
      if (!rd) {
        return new Set();
      }
      if (Array.isArray(rd)) {
        return new Set(rd.map(id => Number(id)));
      }
      if (typeof rd === 'string' && rd !== '') {
        return new Set(rd.split(',').map(id => Number(id)));
      }
      return new Set();
    }
  },
  methods: {
    isDeviceReturned(device) {
      return device && this.returnedDeviceIdSet.has(Number(device.deviceId));
    },
    parseIdList(value) {
      if (value == null || value === undefined || value === '') {
        return [];
      }
      if (Array.isArray(value)) {
        return value.map(id => Number(id));
      }
      return String(value).split(',').filter(id => id !== '').map(id => Number(id));
    },
    async loadDevicesByIds(ids) {
      if (!ids.length) {
        return [];
      }
      const devices = await Promise.all(
        ids.map(id => getDevice(id).then(result => result.data).catch(() => null))
      );
      return devices.filter(Boolean);
    },
    async initDeviceFormData(data) {
      const deviceIds = this.parseIdList(data.devices);
      const modifyIds = this.parseIdList(data.modifyDevices);

      if (deviceIds.length) {
        this.deviceList = await this.loadDevicesByIds(deviceIds);
        data.devices = deviceIds;
        this.form.devices = deviceIds;
      } else {
        data.devices = [];
        this.deviceList = [];
        this.form.devices = [];
      }

      const grantIds = modifyIds.length ? modifyIds : deviceIds;
      if (grantIds.length) {
        this.modifyDeviceList = await this.loadDevicesByIds(grantIds);
        data.modifyDevices = grantIds;
        this.form.modifyDevices = grantIds;
      } else {
        data.modifyDevices = [];
        this.modifyDeviceList = [];
        this.form.modifyDevices = [];
      }

      this.setupReturnDevicesList(data);

      if (data.repairDevices) {
        this.form.repairDevices = this.parseIdList(data.repairDevices);
      }
      if (data.projectId) {
        getProject(data.projectId).then(response => {
          this.chooseProject = response.data;
          this.isSelect = true;
        });
      }
    },
    setupReturnDevicesList(data) {
      this.returnDevicesList = [...this.modifyDeviceList];
      const returnIds = this.parseIdList(data.returnDevices);
      this.form.returnDevices = returnIds;
      this.trySyncReturnDeviceSelection();
    },
    checkReturnSelectable() {
      return this.taskName == '归还确认' && !this.formDisabled;
    },
    trySyncReturnDeviceSelection() {
      if (this.taskName != '归还确认' || !this.returnDevicesList.length) {
        return;
      }
      this.$nextTick(() => {
        this.syncReturnDeviceSelection();
      });
    },
    initRules() {
      if (this.taskName == '设备申请') {
        this.rules = {
          // projectId: [
          //   { required: true, message: '请选择项目', trigger: 'blur' },
          // ],
          devices: [
            { required: true, message: '请选择申请设备', trigger: 'change' },
          ],
          beginDate: [
            { required: true, message: '请选择开始日期', trigger: 'change' },
          ],
          endDate: [
            { required: true, message: '请选择结束日期', trigger: 'change' },
          ],
          applyReason: [
            { required: true, message: '请输入申领理由', trigger: 'blur' },
          ],
          devices: [
            { required: true, message: '请选择设备', trigger: 'blur' },
          ]
        }
      } else if (this.taskName == '分管审核') {
        this.rules = {
          managerComment: [
            { required: true, message: '请输入分管领导审核意见', trigger: 'blur' }
          ]
        }
      } else if (this.taskName == '安排设备') {
        this.rules = {
          dispatchComment: [
            { required: true, message: '请输入安排设备意见', trigger: 'blur' }
          ]
        }
      } else if (this.taskName == '归还确认') {
        this.rules = {
          returnDate: [
            { required: true, message: '请选择归还日期', trigger: 'change' }
          ]
        }
      }
    },
    // 初始化表单
    initForm() {
      getDeviceApproval(this.taskForm.formId).then(res => {
        if (this.isEmptyObject(res.data)) {
          this.formTotal = 0;
          this.form.user.nickName = this.$store.getters.name;
          this.form.applier = this.$store.getters.userId;
          this.form.dept.deptName = this.$store.getters.deptName;
          this.form.applyDate = new Date();
        } else {
          this.formTotal = 1;
          let data = res.data;
          this.form = data;
          this.initDeviceFormData(data);
        }
      })
    },
    async submit() {
      this.$refs['deviceForm'].validate(async (valid) => {
        if (valid) {
          let y1 = new Date(this.form.beginDate);
          let y2 = new Date(this.form.endDate);
          if (y2 < y1) {
            this.form.days = '';
            this.$message.error('结束日期不能小于开始日期');
            return
          }
          this.form.formId = this.taskForm.formId;
          let jsonForm = JSON.stringify(this.form);
          const params = { taskId: this.taskForm.taskId };
          if (this.formTotal != 0) {
            modifyDeviceApproval(jsonForm);
          } else {
            submitDeviceApproval(jsonForm);
          }
          // 获取下一个流程节点
          getNextFlowNode(params).then(async res => {
            const data = res.data;
            let userIds = await this.getNextFlowNodeApproval();
            // 发送企业微信消息
            let userString = [];
            let message = '';
            let formData = new FormData();

            for (let u of userIds) {
              let { data } = await getUser(u);
              if (data) {
                userString.push(data.pinyin);
              }
            }

            message = "您有一条新的设备申请:  \n>" +
              "申请人：<font color='info'>" + this.getUserName(this.form.applier) + "</font> \n>" +
              "开始日期：" + this.form.beginDate + " \n>" +
              "结束日期：" + this.form.endDate + " \n>" +
              "申请事由：" + this.form.applyReason + " \n>" +
              "\n>" +
              "已办流程：<font color='comment'>" + this.taskName + "</font> \n>";

            formData.append('message', message);
            formData.append('userString', userString.join('|') + '|YuSiHan|WangRongHua')

            if (userIds.length > 0) {
              await sendQyMessage(formData);
            }
          })
        } else {
          this.$message.error('必填项未填写完毕')
        }
      })
    },
    saves() {
      this.$refs['deviceForm'].validate((valid) => {
        if (valid) {
          this.form.formId = this.taskForm.formId;
          this.form.deviceApplyId = this.taskForm.formId;
          let jsonForm = JSON.stringify(this.form);
          if (this.formTotal != 0) {
            modifyDeviceApproval(jsonForm).then(res => {
              this.$message.success('保存成功')
            });
          }
        } else {
          this.$message.error('必填项未填写完毕')
        }
      })
    },
    async completeApply() {
      this.$refs['deviceForm'].validate(async (valid) => {
        if (valid) {
          this.form.formId = this.taskForm.formId;
          this.form.deviceApplyId = this.taskForm.formId;
          let jsonForm = JSON.stringify(this.form);
          modifyDeviceApproval(jsonForm);
          const params = { taskId: this.taskForm.taskId };
          // 获取下一个流程节点
          getNextFlowNode(params).then(async res => {
            const data = res.data;
            let userIds = await this.getNextFlowNodeApproval();
            // 发送企业微信消息
            let userString = [];
            let message = '';
            let formData = new FormData();

            for (let u of userIds) {
              let { data } = await getUser(u);
              if (data) {
                userString.push(data.pinyin);
              }
            }

            message = "您有一条新的设备申请:  \n>" +
              "申请人：<font color='info'>" + this.getUserName(this.form.applier) + "</font> \n>" +
              "开始日期：" + this.form.beginDate + " \n>" +
              "结束日期：" + this.form.endDate + " \n>" +
              "申请事由：" + this.form.applyReason + " \n>" +
              "\n>" +
              "已办流程：<font color='comment'>" + this.taskName + "</font> \n>";

            formData.append('message', message);
            formData.append('userString', userString.join('|') + '|YuSiHan|WangRongHua')

            if (userIds.length > 0) {
              await sendQyMessage(formData);
            }
          })
        } else {
          this.$message.error('必填项未填写完毕')
        }
      })
    },
    // 获取下一个审批人
    async getNextFlowNodeApproval() {
      let userIds = [];
      if (this.taskName == '设备申请') {
        const result = await getUserByRole({ roleId: 4 });
        userIds.push(result.data[0]);
        this.$set(this.taskForm.variables, "approval", result.data[0]);
        complete(this.taskForm).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.$emit('goBack')
        });
      } else if (this.taskName == '安排设备') {
        const res = await getUsersManageLeader({ userId: this.form.applier });
        res.data.forEach(user => {
          userIds.push(user.userId)
        })
        this.$set(this.taskForm.variables, "approvalList", userIds);
        complete(this.taskForm).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.$emit('goBack')
        });
      } else if (this.taskName == '分管审核') {
        const result = await getUserByRole({ roleId: 4 });
        this.$set(this.taskForm.variables, "approval", result.data[0]);
        complete(this.taskForm).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.$emit('goBack')
        });
      } else if (this.taskName == '归还确认') {
        this.$modal.confirm('最后一个节点，提交将结束流程，是否提交？').then(() => {
          complete(this.taskForm).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.$emit('goBack')
          });
        })
      }
      return userIds;
    },
    // 查询项目列表
    getProjectList() {
      this.loading = true
      listProject({
        pageNum: 1,
        pageSize: 99999999
      }).then(response => {
        this.projectList = response.rows;
      })
    },
    // 选择项目
    handleSelectProject(val) {
      if (val != "" && val != undefined && val != null) {
        getProject(val).then(res => {
          this.chooseProject = res.data;
          this.isSelect = true
        })
      } else {
        this.isSelect = false
      }
    },
    // 获取设备列表
    getDeviceList() {
      listDevice({
        pageNum: 1,
        pageSize: 99999999,
        type: '仪器设备'
      }).then(res => {
        this.deviceList = res.rows
      })
    },
    // 计算天数
    calculateDay() {
      if (this.form.beginDate && this.form.endDate) {
        let y1 = new Date(this.form.beginDate);
        let y2 = new Date(this.form.endDate);
        if (y2 < y1) {
          this.form.days = '';
          this.$message.error('结束日期不能小于开始日期');
          return
        }
        let sub = Math.abs(y2 - y1);
        let days = Math.floor(sub / (1000 * 60 * 60 * 24)) + 1;
        this.form.days = days;
      } else {
        this.form.days = '';
      }
    },
    isEmptyObject(obj) {
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          return false;
        }
      }
      return true;
    },
    showFormItem(name) {
      let isShow = false;
      if (name == '分管审核')
        isShow = (this.taskName == '设备申请' || this.taskName == '安排设备' || this.taskName == '分管审核') || (this.taskName == '归还确认' && this.form.managerUserId != null);
      else if (name == '分管审核签名')
        isShow = this.taskName == '分管审核' || ((this.taskName == '安排设备' || this.taskName == '归还确认') && this.form.managerUserId != null);
      return isShow;
    },
    confirmProject(val) {
      if (val.length > 1) {
        this.$message.error('请选择一个项目');
        return
      } else if (val.length == 1) {
        this.chooseProject = val[0]
        this.isSelect = true
        this.$set(this.form, 'projectId', val[0].projectId);
        this.$refs.deviceForm.validateField('projectId');
      }
      this.openProject = false
    },
    confirmDevice(val) {
      if (val) {
        let list = []
        if (this.taskName == '设备申请') {
          for (let v of val) {
            list.push(v.deviceId)
          }
          this.$set(this.form, 'devices', list);
          this.$refs.deviceForm.validateField('devices');
          this.deviceList = val;
        } else if (this.taskName == '安排设备') {
          if (!this.multiple) {
            this.$set(this.modifyDeviceList, this.clickRowIndex, val);
          } else {
            for (let i of val) {
              this.modifyDeviceList.push(i);
            }
          }
          for (let j of this.modifyDeviceList) {
            list.push(j.deviceId)
          }
          this.form.modifyDevices = list;
          this.returnDevicesList = [...this.modifyDeviceList];
        }
      }
      this.openDevice = false;
    },
    replaceRowData(row, rowIndex) {
      this.openDevice = true;
      this.clicDevice = row;
      this.clickRowIndex = rowIndex;
      this.multiple = false;
    },
    deleteRowData(row, rowIndex) {
      let list = [];
      this.modifyDeviceList = this.modifyDeviceList.slice(0, rowIndex).concat(this.modifyDeviceList.slice(rowIndex + 1));
      for (let j of this.modifyDeviceList) {
        list.push(j.deviceId)
      }
      this.form.modifyDevices = list;
      this.returnDevicesList = [...this.modifyDeviceList];
    },
    addRowdata() {
      this.openDevice = true;
      this.multiple = true;
    },
    // 选择已归还设备（仅归还确认节点）
    handleSelectionReturn(val) {
      if (this.taskName != '归还确认' || this.isSyncingReturnSelection) {
        return;
      }
      this.form.returnDevices = val.map(item => Number(item.deviceId));
    },
    syncReturnDeviceSelection() {
      const table = this.$refs.returnDevicesRef;
      if (this.taskName != '归还确认' || !table || !this.returnDevicesList.length) {
        return;
      }
      this.isSyncingReturnSelection = true;
      table.clearSelection();
      this.returnDevicesList.forEach(device => {
        if (this.isDeviceReturned(device)) {
          table.toggleRowSelection(device, true);
        }
      });
      this.$nextTick(() => {
        this.isSyncingReturnSelection = false;
      });
    }
  },
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/element-reset.scss";

$border-light: #dcdfe6;
$border-soft: #e4e7ed;
$label-bg: #f0f2f5;
$label-color: #606266;
$text-primary: #303133;
$accent: #409eff;

.borrow-table-form {
  margin-top: 16px;

  .table-form-item {
    margin-bottom: 0;

    ::v-deep .el-form-item__content {
      margin-left: 0 !important;
      line-height: normal;
    }

    ::v-deep .el-form-item__error {
      position: relative;
      padding-top: 2px;
    }
  }

  ::v-deep .el-input__inner,
  ::v-deep .el-textarea__inner {
    border-color: $border-light;
    border-radius: 6px;
    transition: border-color 0.2s, box-shadow 0.2s;

    &:hover {
      border-color: #c0c4cc;
    }

    &:focus {
      border-color: $accent;
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.12);
    }
  }

  ::v-deep .el-input.is-disabled .el-input__inner,
  ::v-deep .el-textarea.is-disabled .el-textarea__inner {
    background-color: #f5f7fa;
    color: #606266;
  }

  .embed-table {
    width: 100%;
    margin-top: 10px;
  }

  .return-status {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    font-size: 13px;
    font-weight: 500;
    line-height: 1;

    i {
      font-size: 16px;
    }

    &.is-returned {
      color: #67c23a;
    }

    &.is-pending {
      color: #909399;
    }
  }
}

.form-table-wrap {
  border: 1px solid $border-soft;
  border-radius: 10px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

.form-table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
  font-size: 14px;
  color: $text-primary;

  tr {
    transition: background-color 0.15s;
  }

  tr:hover td:not(.label-cell) {
    background-color: #fafcff;
  }

  td {
    padding: 12px 14px;
    border-bottom: 1px solid $border-light;
    vertical-align: middle;
    word-break: break-word;
    background: #fff;
  }

  tr:last-child td {
    border-bottom: none;
  }

  .label-cell {
    width: 110px;
    text-align: right;
    font-size: 13px;
    font-weight: 600;
    color: $label-color;
    background-color: $label-bg;
    border-right: 1px solid $border-light;
    white-space: nowrap;
  }
}

.inner-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  margin-top: 8px;
  font-size: 13px;
  border: 1px solid $border-light;
  border-radius: 8px;
  overflow: hidden;

  td {
    padding: 8px 12px;
    border-bottom: 1px solid $border-light;
    border-right: 1px solid $border-light;
    vertical-align: middle;
    background: #fff;
  }

  tr:last-child td {
    border-bottom: none;
  }

  td:last-child {
    border-right: none;
  }

  .label-cell {
    text-align: center;
    font-weight: 600;
    font-size: 12px;
    color: $label-color;
    background-color: $label-bg;
    white-space: nowrap;
  }
}

.sign-line {
  margin-top: 12px;
  padding-top: 10px;
  border-top: 1px solid $border-light;
  font-size: 13px;
  color: $label-color;
  line-height: 26px;

  .auditor {
    color: $text-primary;
    font-weight: 500;
  }
}

.form-footer {
  margin-top: 24px;
  padding-bottom: 20px;
  text-align: center;
}
</style>

<style>
::v-deep .el-input.is-disabled .el-input__inner {
  color: #121212 !important;
}

::v-deep .el-textarea.is-disabled .el-textarea__inner {
  color: #121212 !important;
}
</style>