<!--
 * @Author: ysh
 * @Date: 2024-03-07 13:44:39
 * @LastEditors: wrh
 * @LastEditTime: 2024-03-29 10:23:41
-->

<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.nickName">
                    <!-- <el-input v-model="form.user"></el-input> -->
                    {{ 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">
                    <!-- <el-input v-model="form.deptName"></el-input> -->
                    {{ 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: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="projectId">
                <el-select v-model="form.projectId" 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.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="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 multiple placeholder="请选择" @change="handleSelectDevice" clearable :disabled="taskName != '安排设备'">
                  <el-option v-for="item in deviceList" :key="item.deviceId" :label="item.brand + item.series + item.name + item.code" :value="item.deviceId">
                  </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.name
                    }}</el-descriptions-item>
                  <el-descriptions-item label="设备品牌" label-class-name="my-label">{{ chooseDevice.brand
                    }}</el-descriptions-item>
                  <el-descriptions-item label="规格型号" label-class-name="my-label">{{ chooseDevice.series
                    }}</el-descriptions-item>
                  <el-descriptions-item label="存放地点" label-class-name="my-label">{{ chooseDevice.place
                    }}</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.nickName = this.$store.getters.name;
    this.form.dept.deptName = this.$store.getters.deptName;
    this.getProjectList();
    this.getDeviceList();
    flowXmlAndNode({ procInsId: this.taskForm.procInsId, deployId: this.taskForm.deployId }).then(res => {
      this.flowData = res.data;
    })
  },
  data() {
    return {
      form: {
        user: {
          nickName: '',
        },
        dept: {
          deptName: '',
        },
        applyDate: new Date(),
        days: "",
        devices: []
      },
      projectList: [],
      chooseProject: {},
      flowData: {},
      isSelect: false,
      rules: {
        projectId: [
          { 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 => {
        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 = []
            for (let d of data.devices) {
              arr.push(parseInt(d))
            }
            data.devices = arr;
          }
          this.form = data;
          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();
          })
        }
      })
    },
    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 == '分管审核') {
        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: 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
      }).then(res => {
        this.deviceList = res.rows
      })
    },
    // 选择设备
    handleSelectDevice(val) {
      if (val != "" && val != undefined && val != null) {
        getDevice(val[val.length - 1]).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>