<!--
 * @Author: ysh
 * @Date: 2024-03-07 13:44:39
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-07-29 15:41:35
-->

<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="flowDisabled ? 18 : 24" :xs="24">
        <el-card>
          <h2 style="text-align: center;">设备申请表</h2>
          <div>
            <el-form ref="deviceForm" :model="form" label-width="120px" :rules="rules">
              <!-- 申请人填写 -->
              <el-divider></el-divider>
              <el-row :gutter="20">
                <el-col :span="6" :xs="24">
                  <el-form-item label="申请人：" prop="user.nickName">
                    {{ form.applierUser ? form.applierUser.nickName : form.user.nickName }}
                  </el-form-item>
                </el-col>
                <el-col :span="6" :xs="24">
                  <el-form-item label="所在部门：" prop="dept.deptName">
                    {{ form.dept.deptName }}
                  </el-form-item>
                </el-col>
                <el-col :span="6" :xs="24">
                  <el-form-item label="申请时间：" prop="applyDate">
                    <el-date-picker style="width:170px;" v-model="form.applyDate" value-format="yyyy-MM-dd" type="date"
                      placeholder="选择日期" :disabled="taskName != '设备申请'">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="项目编号：" prop="projectId">
                <el-button type="primary" size="mini" @click="openProject = true"
                  v-if="taskName == '设备申请'">选择项目</el-button>
                <el-descriptions border v-if="isSelect" style="margin-top: 10px;" :column="1">
                  <el-descriptions-item label="项目编号" label-class-name="my-label">{{ chooseProject.projectNumber
                    }}</el-descriptions-item>
                  <el-descriptions-item label="项目名称" label-class-name="my-label">{{ chooseProject.projectName
                    }}</el-descriptions-item>
                  <el-descriptions-item label="项目负责人" label-class-name="my-label">{{ chooseProject.projectLeaderUser ?
      chooseProject.projectLeaderUser.nickName : ''
                    }}</el-descriptions-item>
                  <el-descriptions-item label="承担部门" label-class-name="my-label">
                    <el-tag size="small">{{ chooseProject.undertakingDeptName }}</el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item label="项目类型" label-class-name="my-label">{{ chooseProject.projectType
                    }}</el-descriptions-item>
                </el-descriptions>
              </el-form-item>
              <el-form-item label="设备选择：" prop="devices">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="openDevice = true"
                  :disabled="taskName != '设备申请'">选择设备</el-button>
                <el-table :data="deviceList">
                  <el-table-column label="序号" type="index" />
                  <el-table-column label="出厂编号" align="center" prop="code" />
                  <el-table-column label="设备品牌" align="center" prop="brand" />
                  <el-table-column label="设备名称" align="center" prop="name" />
                  <el-table-column label="规格型号" align="center" prop="series" />
                  <el-table-column label="存放地址" align="center" prop="place" />
                </el-table>
              </el-form-item>
              <el-form-item label="申领事由：" prop="applyReason">
                <el-input type="textarea" :rows="3" placeholder="请输入申领事由" v-model="form.applyReason"
                  :disabled="taskName != '设备申请'">
                </el-input>
              </el-form-item>
              <el-row>
                <el-col :span="6" :xs="24">
                  <el-form-item label="开始日期：" prop="beginDate">
                    <el-date-picker style="width:170px;" v-model="form.beginDate" value-format="yyyy-MM-dd" type="date"
                      placeholder="选择日期" @change="calculateDay" :disabled="taskName != '设备申请'">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="6" :xs="24">
                  <el-form-item label="结束日期：" prop="endDate">
                    <el-date-picker style="width:170px;" v-model="form.endDate" value-format="yyyy-MM-dd" type="date"
                      placeholder="选择日期" @change="calculateDay" :disabled="taskName != '设备申请'">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="8" :xs="24">
                  <el-form-item label="共计:">
                    {{ form.days + '天' }}
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- 安排设备意见 -->
              <el-divider></el-divider>
              <el-form-item label-width="120px" label="拟发放设备：" prop="modifyDevices">
                <el-table :data="modifyDeviceList">
                  <el-table-column label="序号" type="index" />
                  <el-table-column label="出厂编号" align="center" prop="code" />
                  <el-table-column label="设备品牌" align="center" prop="brand" />
                  <el-table-column label="设备名称" align="center" prop="name" />
                  <el-table-column label="规格型号" align="center" prop="series" />
                  <el-table-column label="存放地址" align="center" prop="place" />
                  <el-table-column label="操作" align="center" v-if="taskName == '安排设备'">
                    <template slot-scope="scope">
                      <el-button type="text" primary @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>
              <el-form-item label="安排设备意见：" prop="dispatchComment" label-width="125px">
                <el-input type="textarea" :rows="3" placeholder="请输入安排设备意见" v-model="form.dispatchComment"
                  :disabled="taskName != '安排设备'">
                </el-input>
              </el-form-item>
              <el-row>
                <el-col :span="6" :xs="24" :offset="12">
                  <el-form-item label="签名：" label-width="120px" v-if="taskName != '设备申请'">
                    <span class="auditor"> {{ form.dispatchUser ? form.dispatchUser.nickName : dispatchUser }} </span>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="日期：" label-width="120px" v-if="taskName != '设备申请'">
                    <span> {{ form.dispatchTime ? form.dispatchTime : dispatchTime }} </span>
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- 分管审核意见 -->
              <el-divider></el-divider>
              <el-form-item label="分管审核意见：" prop="managerComment" label-width="125px">
                <el-input type="textarea" :rows="3" placeholder="请输入分管审核意见" v-model="form.managerComment"
                  :disabled="taskName != '分管审核'">
                </el-input>
              </el-form-item>
              <el-row>
                <el-col :span="6" :xs="24" :offset="12">
                  <el-form-item label="签名：" label-width="120px">
                    <span class="auditor"> {{ form.managerUser ? form.managerUser.nickName : managerUser }} </span>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="日期：" label-width="120px">
                    <span> {{ form.managerTime ? form.managerTime : managerTime }} </span>
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- 归还确认 -->
              <el-divider></el-divider>
              <el-form-item label="需维修设备：" prop="state" label-width="120px">
                <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>
              <el-form-item label="备注：" prop="remark" label-width="120px">
                <el-input type="textarea" :rows="3" placeholder="请输入备注" v-model="form.remark"
                  :disabled="taskName != '归还确认'">
                </el-input>
              </el-form-item>
              <el-form-item label="归还日期：" style="margin-left:20px" prop="returnDate">
                <el-date-picker style="width:170px;" v-model="form.returnDate" value-format="yyyy-MM-dd" type="date"
                  placeholder="选择日期" :disabled="taskName != '归还确认'">
                </el-date-picker>
              </el-form-item>
            </el-form>
            <el-row style="text-align: center;" v-if="taskName == '设备申请'">
              <el-button type="primary" @click="submit">提交申请</el-button>
            </el-row>
            <el-row style="text-align: center;" v-else>
              <el-button type="warning" @click="saves()">保存</el-button>
              <el-button type="primary" @click="completeApply()" v-if="taskName">完成审批</el-button>
            </el-row>
          </div>
        </el-card>

      </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 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
    }
  },
  watch: {
    'taskForm.formId'() {
      this.initForm();
    }
  },
  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: [],
      formTotal: 0,
      clicDevice: {},
      clickRowIndex: 0,
      multiple: true,
    }
  },
  mounted() {
    this.initRules();
    this.initForm();
  },
  methods: {
    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;
          if (res.data.devices == null || res.data.devices == undefined || res.data.devices == "") {
            data.devices = []
          } else {
            data.devices = data.devices.split(',');
            let arr = []
            this.deviceList = []
            for (let d of data.devices) {
              arr.push(parseInt(d));
              getDevice(d).then(result => {
                this.deviceList.push(result.data);
              })
            }
            data.devices = arr;
          }
          if (res.data.modifyDevices == null || res.data.modifyDevices == undefined || res.data.modifyDevices == "") {
            data.modifyDevices = []
            this.modifyDeviceList = this.deviceList
          } else {
            data.modifyDevices = data.modifyDevices.split(',');
            let arr = []
            this.modifyDeviceList = []
            for (let d of data.modifyDevices) {
              arr.push(parseInt(d));
              getDevice(d).then(result => {
                this.modifyDeviceList.push(result.data);
              })
            }
            data.modifyDevices = arr;
          }
          this.form = data;
          if (data.projectId) {
            getProject(data.projectId).then(response => {
              this.chooseProject = response.data;
              this.isSelect = true
            })
          }
        }
      })
    },
    submit() {
      this.$refs['deviceForm'].validate((valid) => {
        if (valid) {
          this.form.formId = this.taskForm.formId;
          let formData = new FormData();
          let jsonForm = JSON.stringify(this.form);
          formData.append("form", jsonForm);
          const params = { taskId: this.taskForm.taskId };
          if (this.formTotal != 0) {
            modifyDeviceApproval(formData);
          } else {
            submitDeviceApproval(formData);
          }
          // 获取下一个流程节点
          getNextFlowNode(params).then(res => {
            const data = res.data;
            this.taskForm.formData = formData;
            this.getNextFlowNodeApproval();
          })
        } 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 formData = new FormData();
          let jsonForm = JSON.stringify(this.form);
          formData.append("form", jsonForm);
          if (this.formTotal != 0) {
            modifyDeviceApproval(formData).then(res => {
              this.$message.success('保存成功')
            });
          }
        } else {
          this.$message.error('必填项未填写完毕')
        }
      })
    },
    completeApply() {
      this.$refs['deviceForm'].validate((valid) => {
        if (valid) {
          this.form.formId = this.taskForm.formId;
          this.form.deviceApplyId = this.taskForm.formId;
          let formData = new FormData();
          let jsonForm = JSON.stringify(this.form);
          formData.append("form", jsonForm);
          modifyDeviceApproval(formData);
          const params = { taskId: this.taskForm.taskId };
          // 获取下一个流程节点
          getNextFlowNode(params).then(res => {
            const data = res.data;
            this.taskForm.formData = formData;
            this.getNextFlowNodeApproval();
          })
        } else {
          this.$message.error('必填项未填写完毕')
        }
      })
    },
    // 获取下一个审批人
    getNextFlowNodeApproval() {
      if (this.taskName == '设备申请') {
        getUserByRole({ roleId: 4 }).then(result => {
          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 == '安排设备') {
        getUsersManageLeader({ userId: this.form.applier }).then(res => {
          let userId = [];
          res.data.forEach(user => {
            userId.push(user.userId)
          })
          this.$set(this.taskForm.variables, "approvalList", userId);
          complete(this.taskForm).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.$emit('goBack')
          });
        })
      } else if (this.taskName == '分管审核') {
        getUserByRole({ roleId: 4 }).then(result => {
          this.$set(this.taskForm.variables, "approval", result.data[0]);
          complete(this.taskForm).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.$emit('goBack')
          });
        });
      } else {
        complete(this.taskForm).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.$emit('goBack')
        });
      }

    },
    // 查询项目列表
    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 = '';
          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.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;
    },
    addRowdata() {
      this.openDevice = true;
      this.multiple = true;
    }
  },
}
</script>

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

::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>