<!--
 * @Author: ysh
 * @Date: 2024-03-07 13:44:39
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-03-11 16:34:24
-->

<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="18" :xs="24">
        <el-card>
          <h2 style="text-align: center;">设备申请表</h2>
          <div>
            <el-form ref="deviceForm" :model="form" label-width="100px" :rules="rules">
              <!-- 申请人填写 -->
              <el-row :gutter="20">
                <el-col :span="6" :xs="24">
                  <el-form-item label="申请人：" prop="user">
                    <!-- <el-input v-model="form.user"></el-input> -->
                    {{ form.user }}
                  </el-form-item>
                </el-col>
                <el-col :span="6" :xs="24">
                  <el-form-item label="所在部门：" prop="deptName">
                    <!-- <el-input v-model="form.deptName"></el-input> -->
                    {{ form.deptName }}
                  </el-form-item>
                </el-col>
                <el-col :span="6" :xs="24">
                  <el-form-item label="申请时间：" prop="applyDate">
                    <el-date-picker style="width:140px;" 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="projectNumber">
                <el-select v-model="form.projectNumber" filterable allow-create placeholder="请选择"
                  @change="handleSelectProject" clearable :disabled="taskName != '设备申请'">
                  <el-option v-for="item in projectList" :key="item.value" :label="item.projectNumber"
                    :value="item.projectId">
                  </el-option>
                </el-select>
                <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.projectLeader
                    }}</el-descriptions-item>
                  <el-descriptions-item label="承担部门" label-class-name="my-label">
                    <el-tag size="small">{{ chooseProject.undertakingDept }}</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="applyReason">
                <el-input type="textarea" :rows="2" 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:140px;" 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:140px;" 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="部门审核意见：" prop="deptComment" label-width="120px">
                <el-input type="textarea" :rows="2" placeholder="请输入部门审核意见" v-model="form.deptComment" :disabled="taskName != '部门审核'">
                </el-input>
              </el-form-item>
              <!-- 分管审核意见 -->
              <el-form-item label="分管审核意见：" prop="managerComment" label-width="120px">
                <el-input type="textarea" :rows="2" placeholder="请输入分管审核意见" v-model="form.managerComment" :disabled="taskName != '分管审核'">
                </el-input>
              </el-form-item>
              <!-- 安排设备意见 -->
              <el-form-item label="安排设备意见：" prop="dispatchComment" label-width="120px">
                <el-input type="textarea" :rows="2" placeholder="请输入安排设备意见" v-model="form.dispatchComment" :disabled="taskName != '安排设备'">
                </el-input>
              </el-form-item>
              <!-- 设备安排 -->
              <el-form-item label-width="120px" label="设备选择：">
                <el-select v-model="form.devices" filterable placeholder="请选择" @change="handleSelectDevice" clearable :disabled="taskName != '安排设备'">
                  <el-option v-for="item in deviceList" :key="item.code" :label="item.code" :value="item.code">
                  </el-option>
                </el-select>
                <el-descriptions border v-if="isDeviceSelect" style="margin-top: 10px;" :column="1">
                  <el-descriptions-item label="设备编号" label-class-name="my-label">{{ chooseDevice.code
                    }}</el-descriptions-item>
                  <el-descriptions-item label="设备类别" label-class-name="my-label">{{ chooseDevice.type
                    }}</el-descriptions-item>
                  <el-descriptions-item label="设备系列" label-class-name="my-label">{{ chooseDevice.series
                    }}</el-descriptions-item>
                </el-descriptions>
              </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="primary" @click="completeApply">{{ taskName == '申请确认' ? "确认" : "完成审批" }}</el-button>
            </el-row>
          </div>
        </el-card>

      </el-col>
      <el-col :span="6" :xs="24">
        <el-card>
          <h2 style="text-align: center;">流程进度</h2>
          <div>
            <flow :flowData="flowData" />
          </div>
        </el-card>

      </el-col>
    </el-row>

  </div>
</template>

<script>
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 { getUsersDeptLeader, getUsersManageLeader } from '@/api/system/post.js'
import flow from '@/views/flowable/task/todo/detail/flow'
import { flowXmlAndNode } from "@/api/flowable/definition";
export default {
  components: {
    flow
  },
  props: {
    taskName: {
      type: String,
      required: true
    },
    taskForm: {
      type: Object,
      required: true
    }
  },
  created() {
    this.form.user = this.$store.getters.name;
    this.form.deptName = this.$store.getters.deptName;
    this.getProjectList();
    flowXmlAndNode({ procInsId: this.taskForm.procInsId, deployId: this.taskForm.deployId }).then(res => {
      this.flowData = res.data;
    })
  },
  data() {
    return {
      form: {
        applyDate: new Date(),
        days: ""
      },
      projectList: [],
      chooseProject: {},
      flowData: {},
      isSelect: false,
      rules: {
        projectNumber: [
          { required: true, message: '请选择项目编号', trigger: 'change' },
        ],
        passengers: [
          { required: true, message: '请选择输入乘车人数', trigger: 'change' },
        ],
        beginDate: [
          { required: true, message: '请选择开始日期', trigger: 'change' },
        ],
        endDate: [
          { required: true, message: '请选择结束日期', trigger: 'change' },
        ],
        applyReason: [
          { required: true, message: '请输入用车理由', trigger: 'blur' },
        ],
      },
      deviceList: [],
      chooseDevice: {},
      isDeviceSelect: false,
      formTotal: 0
    }
  },
  mounted() {
    this.initForm();
  },
  methods: {
    // 初始化表单
    initForm() {
      getDeviceApproval(this.taskForm.formId).then(res => {
        debugger
        if (this.isEmptyObject(res.data)) {
          this.formTotal = 0;
          this.form.user = this.$store.getters.name;
          this.form.applier = this.$store.getters.userId;
          this.form.deptName = this.$store.getters.deptName;
          this.form.applyDate = new Date();
        } else {
          this.formTotal = 1;
          let data = res.data;
          this.form = data;
          getProject(data.projectNumber).then(response => {
            this.chooseProject = response.data;
            this.isSelect = true
          })
        }
      })
    },
    submit() {
      this.$refs['deviceForm'].validate((valid) => {
        if (valid) {
          debugger
          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();
          })
        }
      })
    },
    completeApply() {
      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();
      })
    },
    // 获取下一个审批人
    getNextFlowNodeApproval() {
      if (this.taskName == '设备申请') {
        getUsersDeptLeader({ userId: this.$store.getters.userId }).then(res => {
          let userId = res.data.userId;
          this.$set(this.taskForm.variables, "approval", userId);
          complete(this.taskForm).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.$emit('goBack')
          });
        })
      } else if (this.taskName == '部门审核') {
        getUsersManageLeader({ userId: this.$store.getters.userId }).then(res => {
          let userId = res.data.userId;
          this.$set(this.taskForm.variables, "approval", userId);
          complete(this.taskForm).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.$emit('goBack')
          });
        })
      } else if (this.taskName == '分管审核') {
        this.$set(this.taskForm.variables, "approval", 16);
        complete(this.taskForm).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.$emit('goBack')
        });
      } else if (this.taskName == '安排设备') {
        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: 9999999999
      }).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: 9999999999
      }).then(res => {
        this.deviceList = res.rows
      })
    },
    // 选择设备
    handleSelectDevice(val) {
      if (val != "" && val != undefined && val != null) {
        getDevice(val).then(res => {
          this.chooseDevice = res.data;
          this.isDeviceSelect = true
        })
      } else {
        this.isDeviceSelect = false
      }
    },
    // 计算天数
    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;
    }
  },
}
</script>

<style lang="scss" scoped>
::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>