<!--
 * @Author: ysh
 * @Date: 2024-02-29 11:44:28
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-03-14 09:33:02
-->
<!--
 * @Author: wrh
 * @Date: 2024-02-29 17:24:39
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-03-07 13:43:50
-->

<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="18" :xs="24">
        <el-card>
          <h2 style="text-align: center;">用车申请表</h2>
          <div>
            <el-form ref="carForm" :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="date">
                    <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" v-if="taskForm.procDefName == '用车审批'">
                <el-select v-model="form.projectNumber" filterable placeholder="请选择" @change="handleSelectProject"
                  :disabled="taskName != '用车申请'" clearable>
                  <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="passengers">
                <el-input-number v-model="form.passengers" :min="1" :disabled="taskName != '用车申请'"></el-input-number>
              </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" v-if="taskForm.procDefName == '用车审批'">
                <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" v-if="taskForm.procDefName == '用车审批'">
                <el-input type="textarea" :rows="2" placeholder="请输入分管审核意见" v-model="form.managerComment"
                  :disabled="taskName != '分管审核'">
                </el-input>
              </el-form-item>
              <!-- 工会审核意见 -->
              <el-form-item label="工会审核意见：" prop="unionComment" label-width="120px" v-if="taskForm.procDefName == '用车审批（工会）'">
                <el-input type="textarea" :rows="2" placeholder="请输入工会审核意见" v-model="form.unionComment"
                  :disabled="taskName != '工会审核'">
                </el-input>
              </el-form-item>
              <!-- 安排用车意见 -->
              <el-form-item label="安排用车意见：" prop="dispatchComment" label-width="120px" v-if="taskForm.procDefName == '用车审批'">
                <el-input type="textarea" :rows="2" placeholder="请输入安排用车意见" v-model="form.dispatchComment"
                  :disabled="taskName != '安排用车'">
                </el-input>
              </el-form-item>
              <!-- 综合事务部管理人员填写 -->
              <el-form-item label="车牌号：">
                <el-checkbox-group v-model="form.cars" :disabled="taskName != '安排用车'">
                  <el-checkbox :label="item.carId" v-for="item in carList" :key="item.carId" :value="item.carId">
                    {{ item.licensePlate }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item label="驾驶员：">
                <el-checkbox-group v-model="form.drivers" :disabled="taskName != '安排用车'">
                  <el-checkbox :label="item.userId" v-for="item in driverList" :key="item.userId" :value="item.userId">
                    {{ item.nickName }}
                  </el-checkbox>
                </el-checkbox-group>
              </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 { listCar, getCar } from "@/api/oa/car/car";
import { listCarApproval, getCarApproval, updateCarApproval, submitCarApproval, modifyCarApproval } from '@/api/oa/car/carApproval'
import { listDriver } from "@/api/system/post";
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.getProjectList();
    this.getCarList();
    this.getDriverList();
    flowXmlAndNode({ procInsId: this.taskForm.procInsId, deployId: this.taskForm.deployId }).then(res => {
      this.flowData = res.data;
    })
  },
  data() {
    return {
      form: {
        days: '',
        drivers: [],
        user: '',
        applyDate: undefined,
        deptName: '',
        applier: '',
        cars: []
      },
      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' },
        ],
      },
      projectList: [],
      carList: [],
      driverList: [],
      chooseProject: {},
      isSelect: false,
      formTotal: 0,
      flowData: {}
    }
  },
  mounted() {
    this.initForm();
  },
  methods: {
    // 初始化表单
    initForm() {
      getCarApproval(this.taskForm.formId).then(res => {
        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;
          if (res.data.drivers == null || res.data.drivers == undefined || res.data.drivers == "") {
            data.drivers = []
          } else {
            let arr = []
            data.drivers = data.drivers.split(',');
            for (let driver of data.drivers) {
              arr.push(parseInt(driver))
            }
            data.drivers = arr
          }
          if (res.data.cars == null || res.data.cars == undefined || res.data.cars == "") {
            data.cars = []
          } else {
            data.cars = data.cars.split(',');
            let arr = []
            for (let d of data.cars) {
              arr.push(parseInt(d))
            }
            data.cars = arr;
          }
          this.form = data;
        }
      })
    },
    submit() {
      this.$refs['carForm'].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) {
            modifyCarApproval(formData);
          } else {
            submitCarApproval(formData);
          }
          // 获取下一个流程节点
          getNextFlowNode(params).then(res => {
            const data = res.data;
            this.taskForm.formData = formData;
            this.getNextFlowNodeApproval();
          })
        }
      })
    },
    completeApply() {
      this.form.formId = this.taskForm.formId;
      this.form.carApplyId = this.taskForm.formId;
      let formData = new FormData();
      let jsonForm = JSON.stringify(this.form);
      formData.append("form", jsonForm);
      modifyCarApproval(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;
          if (this.taskForm.procDefName == '用车审批') {
            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.taskName == '工会审核') {
        this.$set(this.taskForm.variables, "approvalList", [8,16]);
        complete(this.taskForm).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.$emit('goBack')
        });
      } else if (this.taskName == '安排用车' || this.taskName == '申请确认') {
        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
      }

    },
    // 查询车辆列表
    getCarList() {
      listCar({
        pageNum: 1,
        pageSize: 99999999
      }).then(response => {
        this.carList = response.rows;
      })
    },

    // 查询驾驶员列表
    getDriverList() {
      listDriver({
        pageNum: 1,
        pageSize: 99999999
      }).then(response => {
        this.driverList = response.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;
    }
  },
}
</script>

<style lang="scss" scoped></style>

<style>
.my-label {
  width: 100px;
  background: #E1F3D8;
}
::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>