<!--
 * @Author: ysh
 * @Date: 2024-09-19 13:45:43
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-10-08 09:55:20
-->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="isFlow ? 18 : 24" :xs="24">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px" :disabled="taskName == ''">
          <h2 style="text-align: center;">采购申请表</h2>
          <el-row :gutter="20">
            <el-col :span="7" :xs="24">
              <el-form-item label="申请人：" prop="applier">
                {{ getUserName(form.applier) }}
              </el-form-item>
            </el-col>
            <el-col :span="7" :xs="24">
              <el-form-item label="申请部门：" prop="applyDept">
                {{ getDeptName(form.applyDept) }}
              </el-form-item>
            </el-col>
            <el-col :span="7" :xs="24">
              <el-form-item label="申请时间：" prop="date">
                {{ form.applyTime }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="购置说明：" prop="applyReason">
            <el-input type="textarea" v-model="form.applyReason" :autosize="{ minRows: 4 }"
              :disabled="taskName != '采购申请'"></el-input>
          </el-form-item>
          <el-form-item label="采购计划表：">
            <plan ref="planRef" :procureApplyId="form.procureApplyId" :taskName="taskName"></plan>
          </el-form-item>
          <el-form-item label="综合事务部意见：" prop="planComment" label-width="130px">
            <el-input type="textarea" v-model="form.planComment" :autosize="{ minRows: 4 }"
              :disabled="taskName != '编制计划'"></el-input>
            <auditor-row ref="zhRef" :isCurrent="taskName == '编制计划'"
              :signature="form.planUserId ? form.planUserId : null" :signTime="form.planTime"></auditor-row>
          </el-form-item>
          <el-form-item label="分管审核意见：" prop="managerComment" label-width="130px">
            <el-input type="textarea" v-model="form.managerComment" :autosize="{ minRows: 4 }"
              :disabled="taskName != '分管审核'"></el-input>
            <auditor-row ref="fgRef" :isCurrent="taskName == '分管审核'"
              :signature="form.managerUserId ? form.managerUserId : null" :signTime="form.managerTime"></auditor-row>
          </el-form-item>
          <el-form-item label="总经理审批意见：" prop="zjlComment" label-width="130px">
            <el-input type="textarea" v-model="form.zjlComment" :autosize="{ minRows: 4 }"
              :disabled="taskName != '总经理审批'"></el-input>
            <auditor-row ref="zjlRef" :isCurrent="taskName == '总经理审批'"
              :signature="form.zjlUserId ? form.zjlUserId : null" :signTime="form.zjlTime"></auditor-row>
          </el-form-item>
        </el-form>
        <el-row style="text-align: center;" v-if="taskName != ''">
          <el-button type="warning" @click="saves()">保存</el-button>
          <el-button type="primary" @click="completeApply()">提交</el-button>
        </el-row>
      </el-col>
      <el-col :span="6" :xs="24" v-if="isFlow">
        <el-card>
          <h2 style="text-align: center;">流程进度</h2>
          <div>
            <flow :flowData="flowData" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog title="选择下个流程审批人" :visible.sync="completeOpen" width="60%" append-to-body>
      <el-form ref="taskForm" :model="taskForm">
        <el-form-item prop="targetKey">
          <flow-user v-if="checkSendUser" :checkType="checkType" @handleUserSelect="handleUserSelect"></flow-user>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="completeOpen = false">取 消</el-button>
        <el-button type="primary" @click="taskComplete()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import flow from '@/views/flowable/task/todo/detail/flow';
import { flowXmlAndNode } from "@/api/flowable/definition";
import { parseTime } from "@/utils/ruoyi";
import { complete, rejectTask, returnList, returnTask, getNextFlowNode, delegate, flowTaskForm, } from "@/api/flowable/todo";
import { getUsersDeptLeaderByDept, getUsersManageLeaderByDept, getUserByPost } from '@/api/system/post'
import { listProcureApproval, getProcureApproval, addProcureApproval, updateProcureApproval, delProcureApproval } from "@/api/oa/procure/procureApproval";
import { listProcurePlan, getProcurePlan, addProcurePlan, updateProcurePlan, delProcurePlan } from "@/api/oa/procure/procurePlan";
import plan from './plan.vue'
import AuditorRow from '@/views/flowable/form/components/auditorRow.vue';
import FlowUser from '@/components/flow/User';
export default {
  components: { flow, FlowUser, plan, AuditorRow },
  props: {
    taskName: {
      type: String,
      required: true
    },
    taskForm: {
      type: Object,
      required: true
    },
    isFlow: {
      type: Boolean,
      default: true
    },
  },
  created() {
    this.initFlow();
    this.initForm();
  },
  data() {
    return {
      flowData: {},
      form: {
        deptId: undefined,
        applyTime: undefined,
        applier: undefined,
      },
      rules: {
        applyReason: [
          { required: true, message: '请输入购置说明', trigger: 'blur' }
        ]
      },
      formTotal: 0,
      checkSendUser: false,
      completeOpen: false,
      completeTitle: '',
      checkType: 'single',
    }
  },
  methods: {
    initFlow() {
      if (this.isFlow) {
        flowXmlAndNode({ procInsId: this.taskForm.procInsId, deployId: this.taskForm.deployId }).then(res => {
          this.flowData = res.data;
        })
      }
    },
    initForm() {
      const formId = this.taskForm.formId;
      getProcureApproval(formId).then(res => {
        if (res.data) {
          this.formTotal = 1
          this.form = res.data
        } else {
        }
        if (this.taskName == '采购申请') {
          this.form.applier = this.$store.getters.userId;
          this.form.applyDept = this.$store.getters.deptId;
          this.form.applyTime = parseTime(new Date(), "{y}-{m}-{d}")
        } else if (this.taskName == '编制计划') {
          this.rules = {
            planComment: [
              { required: true, message: '请输入综合事务部意见', trigger: 'blur' }
            ]
          }
        } else if (this.taskName == '分管审核') {
          this.rules = {
            managerComment: [
              { required: true, message: '请输入审核意见', trigger: 'blur' }
            ]
          }
        } else if (this.taskName == '总经理审批') {
          this.rules = {
            zjlComment: [
              { required: true, message: '请输入审核意见', trigger: 'blur' }
            ]
          }
        }
      })
    },
    // 保存表单
    async saves() {
      if (this.formTotal != 0) {
        if (this.taskName == '编制计划') {
          this.form.planUserId = this.$refs.zhRef.localSignatureUserId;
          this.form.planTime = this.$refs.zhRef.loaclSignTime;
        } else if (this.taskName == '分管审核') {
          this.form.managerUserId = this.$refs.fgRef.localSignatureUserId;
          this.form.managerTime = this.$refs.fgRef.loaclSignTime;
        } else if (this.taskName == '总经理审批') {
          this.form.zjlUserId = this.$refs.zjlRef.localSignatureUserId;
          this.form.zjlTime = this.$refs.zjlRef.loaclSignTime;
        }
        await updateProcureApproval(this.form)
      } else {
        this.form.procureApplyId = this.taskForm.formId
        await addProcureApproval(this.form)
      }
      this.savePlan();
      this.$message.success('保存成功')
    },
    // 保存采购计划
    async savePlan() {
      const planList = this.$refs.planRef.itemList;
      const isAdd = this.$refs.planRef.formTotal;
      const procureApplyId = this.taskForm.formId;
      if (isAdd != 0)
        await delProcurePlan(procureApplyId)
      for (let plan of planList) {
        plan.procureApplyId = procureApplyId
        await addProcurePlan(plan)
      }
    },
    completeApply() {
      const params = { taskId: this.taskForm.taskId };
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.saves();
          getNextFlowNode(params).then(async res => {
            if (this.taskName == '采购申请') {
              this.checkSendUser = true;
              this.completeOpen = true;
            } else if (this.taskName == '编制计划') {
              let managerList = []
              let result = await getUsersManageLeaderByDept({ deptId: this.form.applyDept });
              result.data.forEach(element => {
                managerList.push(element.userId)
              });
              this.$set(this.taskForm.variables, "approvalList", managerList);
              this.successComplete();
            } else if (this.taskName == '分管审核') {
              let result = await getUserByPost({ postName: '总经理' })
              this.$set(this.taskForm.variables, "approval", result.data[0].userId);
              this.successComplete();
            } else if (this.taskName == '总经理审批') {
              this.$modal.confirm('最后一个节点，提交将结束流程，是否提交？').then(() => {
                this.successComplete();
              })
            }
          })
        } else {
          this.$message.error('请完善必填项')
        }
      })
    },
    successComplete() {
      complete(this.taskForm).then(response => {
        this.$modal.msgSuccess(response.msg);
        this.$emit('goBack')
      })
    },
    // 用户信息选中数据
    handleUserSelect(selection) {
      if (selection) {
        //不多选
        this.$set(this.taskForm.variables, "approval", selection.userId.toString());
      }
    },
    /** 用户审批任务 */
    taskComplete() {
      if (!this.taskForm.variables && this.checkSendUser) {
        this.$modal.msgError("请选择流程接收人员!");
        return;
      }
      if (this.taskForm) {
        this.successComplete();
      }
    },
  },

}
</script>

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