<!--
 * @Author: ysh
 * @Date: 2024-09-20 16:09:07
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-09-30 15:57:01
-->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="isFlow ? 18 : 24" :xs="24">
        <h2 style="text-align: center;">项目委外审批表</h2>
        <el-form ref="form" :model="form" :rules="rules" :disabled="taskName == ''">
          <el-row :gutter="20">
            <el-col :span="7" :xs="24">
              <el-form-item label="申请人：" prop="applier" label-width="100px">
                {{ getUserName(form.applier) }}
              </el-form-item>
            </el-col>
            <el-col :span="7" :xs="24">
              <el-form-item label="申请部门：" prop="applyDept" label-width="100px">
                {{ getDeptName(form.applyDept) }}
              </el-form-item>
            </el-col>
            <el-col :span="7" :xs="24">
              <el-form-item label="申请时间：" prop="date" label-width="100px">
                {{ form.applyTime }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="项目名称：" prop="projectId" label-width="100px">
            <el-button icon="el-icon-plus" type="primary" @click="prOpen = true" size="mini"
              v-if="taskName == '委外申请'">选择项目</el-button>
            <el-descriptions class="mb20" border v-if="form.projectId" style="margin-top: 10px" :column="1">
              <el-descriptions-item label="项目编号">
                {{ project.projectNumber }}
              </el-descriptions-item>
              <el-descriptions-item label="项目名称">
                {{ project.projectName }}
              </el-descriptions-item>
              <el-descriptions-item label="项目负责人">
                {{ getUserName(project.projectLeader) }}
              </el-descriptions-item>
              <el-descriptions-item label="项目类型">
                {{ project.projectType }}
              </el-descriptions-item>
              <el-descriptions-item label="承担部门">
                {{ getDeptNames(project.undertakingDept) }}
              </el-descriptions-item>
            </el-descriptions>
          </el-form-item>
          <el-form-item label="合作单位：" prop="partnerId">
            <el-tag class="mr10" v-for="item in partnerList" :key="item.partnerId" v-if="partnerList.length != 0">
              {{ item.partnerName }}
            </el-tag>
            <el-button icon="el-icon-plus" type="primary" @click="partOpen = true" size="mini"
              v-if="taskName == '委外申请'">选择合作单位</el-button>
          </el-form-item>
          <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="委外工作计划：">
            <outsource-plan ref="planRef" :taskForm="taskForm" :taskName="taskName"
              :outsourceId="outsourceId"></outsource-plan>
          </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="prOpen" :width="'60%'" append-to-body>
      <choose-project @chooseProject="confirmProject"></choose-project>
    </el-dialog>
    <el-dialog title="选择合作单位" :visible.sync="partOpen" :width="'60%'" append-to-body>
      <choose-partner @confirm="confirmPartner"></choose-partner>
    </el-dialog>
  </div>
</template>

<script>
import flow from '@/views/flowable/task/todo/detail/flow';
import { flowXmlAndNode } from "@/api/flowable/definition";
import { complete, rejectTask, returnList, returnTask, getNextFlowNode, delegate, flowTaskForm, } from "@/api/flowable/todo";
import { parseTime } from "@/utils/ruoyi";
import { getProject } from "@/api/oa/project/project";
import { listOutsource, getOutsource, addOutsource, updateOutsource, delOutsource } from "@/api/oa/outsource/outsource";
import { listOutsourceWork, getOutsourceWork, addOutsourceWork, updateOutsourceWork, delOutsourceWork } from "@/api/oa/outsource/outsourceWork";
import { getUsersDeptLeaderByDept, getUsersManageLeaderByDept, getUserByPost } from '@/api/system/post'
import { getPartner } from "@/api/oa/partner/partner";
import chooseProject from '@/views/flowable/form/components/chooseProject.vue';
import ChoosePartner from '@/views/flowable/form/components/choosePartner.vue';
import outsourcePlan from './outsourcePlan.vue';
import AuditorRow from '@/views/flowable/form/components/auditorRow.vue';
export default {
  components: { flow, chooseProject, ChoosePartner, outsourcePlan, AuditorRow },
  props: {
    taskName: {
      type: String,
      required: true
    },
    taskForm: {
      type: Object,
      required: true
    },
    isFlow: {
      type: Boolean,
      default: true
    },
  },
  data() {
    return {
      flowData: {},
      form: {
        deptId: undefined,
        applyTime: undefined,
        applier: undefined,
      },
      rules: {
        applyReason: [
          { required: true, message: '请输入委外说明', trigger: 'blur' }
        ],
        projectId: [
          { required: true, message: '请选择项目', trigger: 'change' }
        ],
        partnerId: [
          { required: true, message: '请选择合作单位', trigger: 'change' }
        ]
      },
      project: {},
      partnerList: [],
      prOpen: false,
      partOpen: false,
      formTotal: 0,
      outsourceId: ''
    }
  },
  created() {
    this.initFlow();
    this.initForm();
  },
  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;
      this.outsourceId = formId;
      getOutsource(formId).then(res => {
        if (res.data) {
          this.formTotal = 1
          this.form = res.data;
          this.getPartnerList(res.data.partnerId);
          this.getProjectInfo(res.data.projectId);
        }
        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}")
        }
      })
    },
    getProjectInfo(projectId) {
      getProject(projectId).then(res => {
        if (res.data)
          this.project = res.data
      })
    },
    getPartnerList(partnerId) {
      if(!partnerId) return
      this.partnerList = [];
      let ids = partnerId.split(',');
      ids.forEach(async item => {
        let res = await getPartner(item);
        if (res.data)
          this.partnerList.push(res.data)
      })
    },
    async saves() {
      if (this.formTotal != 0) {
        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 updateOutsource(this.form)
      } else {
        this.form.outsourceId = this.taskForm.formId;
        await addOutsource(this.form)
      }
      this.savePlan()
      this.$message.success('保存成功')
    },
    async savePlan() {
      const planList = this.$refs.planRef.workList;
      const isAdd = this.$refs.planRef.formTotal;
      const outsourceId = this.taskForm.formId;
      if (isAdd != 0)
        await delOutsourceWork(outsourceId)
      for (let plan of planList) {
        plan.outsourceId = outsourceId
        await addOutsourceWork(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 == '委外申请') {
              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(res => {
                this.successComplete();
              })
            }
          })
        } else {
          this.$message.error('请完善必填项')
        }
      })
    },
    successComplete() {
      complete(this.taskForm).then(response => {
        this.$modal.msgSuccess(response.msg);
        this.$emit('goBack')
      })
    },
    confirmProject(val) {
      if (val.length != 1) {
        this.$message.error("项目只能选择一个！");
        return;
      }
      this.project = val[0]
      this.$set(this.form, 'projectId', val[0].projectId)
      this.prOpen = false;
      this.$refs.form.validateField('projectId');
    },
    confirmPartner(val) {
      this.partnerList = val;
      this.partOpen = false;
      const ids = val.map(obj => obj.partnerId).join(',');
      this.$set(this.form, 'partnerId', ids)
      this.$refs.form.validateField('partnerId');
    }
  },
}
</script>

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