<!--
 * @Author: ysh
 * @Date: 2024-05-10 15:31:57
 * @LastEditors: wrh
 * @LastEditTime: 2025-12-16 11:06:33
-->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="flowDisabled ? 18 : 24" :xs="24">
        <h2 class="text-center">分包合同评审表</h2>
        <div class="mt20 mb20" v-if="showAlter && flowDisabled">
          <el-alert title="任务被退回，请修改后重新提交" type="error" :closable="false">
            <return-comment :taskForm="taskForm" @isReturn="isReturn"></return-comment>
          </el-alert>
        </div>
        <el-form ref="form" :model="form" :rules="rules" label-width="130px" :formDisabled="formDisabled">
          <el-divider></el-divider>
          <el-form-item label="分包合同名称" prop="subContractName">
            <el-input type="textarea" :rows="3" v-model="form.subContractName" placeholder="请输入分包合同名称"
              :disabled="taskName != '合同拟稿'" />
          </el-form-item>
          <el-form-item label="分包合同金额" prop="subAmount">
            <el-input-number :controls="false" v-model="form.subAmount" placeholder="请输入分包合同金额"
              :disabled="taskName != '合同拟稿'" />(元)
          </el-form-item>
          <el-form-item label="承接单位" prop="partnerId">
            <el-select allow-create v-model="form.partnerId" multiple filterable placeholder="请选择"
              :style="taskName == '合同拟稿' ? { width: '84%' } : { width: '100%' }" disabled clearable>
              <el-option v-for="item in partnerList" :key="item.value" :label="item.partnerName" :value="item.partnerId">
              </el-option>
            </el-select>
            <el-button type="primary" @click="partnerOpen = true" size="mini" v-if="taskName == '合同拟稿'">选择单位</el-button>
          </el-form-item>
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="form.contactPerson" placeholder="请输入联系人" :disabled="taskName != '合同拟稿'" />
          </el-form-item>
          <el-form-item label="联系电话" prop="telephone">
            <el-input v-model="form.telephone" placeholder="请输入联系电话" :disabled="taskName != '合同拟稿'" />
          </el-form-item>
          <el-form-item label="合同文件" prop="contractDocument">
            <FileUpload v-if="taskName == '合同拟稿' && !form.contractDocument" :disabled="taskName != '合同拟稿'"
              ref="contractFile" :limit="1" :filePathName="'分包合同/合同文件'"
              :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']" @input="getContractPath">
            </FileUpload>
            <div v-if="form.contractDocument">
              <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + form.contractDocument}`)">
                {{ getFileName(form.contractDocument) }}
              </el-link>
              <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + form.contractDocument}`"
                :underline="false" target="_blank">
                <span class="el-icon-download">下载文件</span>
              </el-link>
              <FileUpload v-if="taskName == '合同拟稿'" :limit="1" :filePathName="'分包合同/合同文件'"
                :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']" @input="getContractPath"></FileUpload>
            </div>
          </el-form-item>
          <el-form-item label="关联项目" prop="projectId">
            <el-button type="primary" size="mini" @click="open = true" v-if="taskName == '合同拟稿'">选择项目</el-button>
            <el-table :data="chooseProjectList" border>
              <el-table-column type="index" width="50" label="序号" />
              <el-table-column label="项目编号" align="center" key="projectNumber" prop="projectNumber" />
              <el-table-column label="项目名称" align="center" key="projectName" prop="projectName" />
              <el-table-column label="项目负责人" align="center" key="projectLeaderName" prop="projectLeaderUser.nickName" />
              <el-table-column label="承担部门" align="center" prop="undertakingDeptName"></el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button type="text" icon="el-icon-view" @click="clickProjectFn(scope.row)">查看</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="关联主合同：">
            <el-button type="primary" size="mini" @click="contractOpen = true" icon="el-icon-plus"
              v-if="taskName == '合同拟稿'">新增关联主合同</el-button>
            <el-table v-loading="contractloading" :data="connectContractList" border>
              <el-table-column label="合同名称" align="center" prop="contractName" width="220px" />
              <el-table-column label="合同金额" align="center" prop="amount" />
              <el-table-column label="甲方单位" align="center" prop="partyA.partyAName" width="220px" />
              <el-table-column label="合同编码" align="center" prop="contractCode" />
              <el-table-column label="合同编号" align="center" prop="contractNumber" />
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button type="text" icon="el-icon-view" @click="clickContractFn(scope.row)">查看</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-divider></el-divider>
          <!-- 表1：合同计划工作量 -->
          <work-table ref="workTableRef" :contractId="taskForm.formId" :taskName="taskName"></work-table>

          <p class="mb20 mt20"></p>

          <!-- 表2：合同回款计划  -->
          <payment-table ref="paymentRef" :contractId="taskForm.formId" :amount="form.subAmount" :titles="'付款'"
            :taskName="taskName"></payment-table>

          <el-form-item label="合同备注" prop="remark">
            <el-input type="textarea" v-model="form.remark" :autosize="{ minRows: 4 }" placeholder="请输入合同备注"
              :disabled="taskName != '合同拟稿'" />
          </el-form-item>
          <el-row>
            <el-col :span="6" :xs="24" :offset="11">
              <el-form-item label="拟稿人：" label-width="120px">
                <span class="auditor"> {{ form.draftUser ? form.draftUser.nickName : draftUser }} </span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="日期：" label-width="120px">
                <!-- <span> {{ form.draftTime ? form.draftTime : draftTime }} </span> -->
                <el-date-picker v-model="form.draftTime" :disabled="taskName != '合同拟稿'" type="date"
                  value-format="yyyy-MM-dd" placeholder="选择日期"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="评审方式" prop="commentType">
            <el-radio-group v-model="form.commentType" @change="changeCommentType" :disabled="taskName != '合同拟稿'">
              <el-radio :label="'0'">无须评审</el-radio>
              <el-radio :label="'1'">会议评审</el-radio>
              <el-radio :label="'2'">线上会审</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="线上会审：" v-if="commentOpen">
            <table border="1" style="width:100%;">
              <tr>
                <td style="width: 50px;">序号</td>
                <td>会审部门</td>
                <td>会审人</td>
                <td>会审意见</td>
                <td style="width: 200px;">会审附件</td>
                <td style="width: 90px;">签名</td>
                <td style="width: 100px;">日期</td>
              </tr>
              <tr v-for="(comment, index) in commentList" :key="index">
                <td>
                  {{ index + 1 }}
                </td>
                <td>
                  <el-select v-model="comment.deptId" clearable style="width:120px"
                    :disabled="(index < 4 && taskName == '合同拟稿') || taskName != '合同拟稿'" @change="getDeptLeader">
                    <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName" :value="item.deptId">
                    </el-option>
                  </el-select>
                </td>
                <td>
                  <el-select v-model="comment.userId" clearable style="width:120px"
                    :disabled="(index < 4 && taskName == '合同拟稿') || taskName != '合同拟稿'">
                    <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId">
                    </el-option>
                  </el-select>
                </td>
                <td>
                  <el-input v-model="comment.comment" type="textarea" clearable :autosize="{ minRows: 2 }"
                    :disabled="taskName != '线上会审' || (taskName == '线上会审' && comment.userId != userId)"></el-input>
                </td>
                <!-- 线上会审附件 -->
                <td @click="clickFile(comment)">
                  <FileUpload v-if="comment.document == '' || comment.document == null" ref="hs" :limit="1"
                    :filePathName="'分包合同/线上会审意见'" :isShowTip="false"
                    :disabled="taskName != '线上会审' || (taskName == '线上会审' && comment.userId != userId)"
                    :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']" @input="setCommentDocument">
                  </FileUpload>
                  <div v-if="comment.document != '' && comment.document != null">
                    <transition-group class="upload-file-list el-upload-list el-upload-list--text"
                      name="el-fade-in-linear" tag="ul">
                      <li key="li01" class="el-upload-list__item ele-upload-list__item-content">
                        <el-link :href="`${baseUrl}${'/profile/upload' + comment.document}`" :underline="false"
                          target="_blank">
                          <span class="el-icon-document" style="color:#0011ff;text-decoration: underline;">
                            {{ getFileName(comment.document) }}
                          </span>
                        </el-link>
                        <div class="ele-upload-list__item-content-action"
                          v-if="taskName == '线上会审' && comment.userId == userId">
                          <el-link :underline="false" @click="handleFileDelete(comment, 'document')"
                            type="danger">删除</el-link>
                        </div>
                      </li>
                    </transition-group>
                  </div>
                </td>
                <td>
                  <span class="auditor"> {{ comment.commentUser ? comment.commentUser.nickName : '' }} </span>
                </td>
                <td>
                  <el-date-picker v-model="comment.commentTime"
                    :disabled="taskName != '线上会审' || (taskName == '线上会审' && comment.userId != userId)" type="date"
                    value-format="yyyy-MM-dd" style="width:140px;" placeholder="选择日期"></el-date-picker>
                </td>
                <td v-show="taskName == '合同拟稿'">
                  <div class="delete-btn" @click="deletCommentItem(index)">
                    <i class="el-icon-circle-close"></i>
                  </div>
                </td>
              </tr>
            </table>
            <el-button icon="el-icon-plus" size="mini" @click="addCommentList()" type="primary" plain
              :disabled="taskName != '合同拟稿'"></el-button>
          </el-form-item>
          <el-form-item label="会议评审：" v-if="meetingOpen">
            <table border="1">
              <tr>
                <td>评审时间</td>
                <td>
                  <el-date-picker clearable v-model="meetingForm.meetingTime" type="date" value-format="yyyy-MM-dd"
                    placeholder="请选择评审日期" :disabled="taskName != '合同拟稿'">
                  </el-date-picker>
                </td>
                <td>评审地点</td>
                <td>
                  <el-select v-model="meetingForm.place" clearable style="width:120px" :disabled="taskName != '合同拟稿'">
                    <el-option v-for="item in placeList" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </td>
                <td>评审主持人</td>
                <td>
                  <el-select v-model="meetingForm.hostId" clearable style="width:120px" :disabled="taskName != '合同拟稿'">
                    <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId">
                    </el-option>
                  </el-select>
                </td>
              </tr>
              <tr>
                <td>参与评审人员</td>
                <td colspan="5">
                  <el-select v-model="meetingForm.users" multiple clearable style="width:600px"
                    :disabled="taskName != '合同拟稿'">
                    <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId">
                    </el-option>
                  </el-select>
                </td>
              </tr>
              <tr>
                <td>评审意见表</td>
                <td colspan="5" style="text-align:left;">
                  <FileUpload v-if="meetingForm.document == null || meetingForm.document == ''" ref="contractFile"
                    :limit="1" :filePathName="'分包合同/会议评审意见'" :disabled="taskName != '会议评审'"
                    :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']" @input="getMeetingPath">
                  </FileUpload>
                  <div v-if="meetingForm.document != null && meetingForm.document != ''">
                    <file-item :document="meetingForm.document"></file-item>
                  </div>
                </td>
              </tr>
              <tr>
                <td>评审结论</td>
                <td colspan="5">
                  <el-input type="textarea" v-model="meetingForm.conclusion" clearable
                    :disabled="taskName != '会议评审'"></el-input>
                </td>
              </tr>
              <tr>
                <td colspan="2"></td>
                <td>主持人签名</td>
                <td>
                  <span class="auditor"> {{ meetingForm.hostUser ? meetingForm.hostUser.nickName : hostUser }} </span>
                </td>
                <td>日期</td>
                <td>
                  <span> {{ meetingForm.commentTime ? meetingForm.commentTime : commentTime }} </span>
                </td>
              </tr>
            </table>
          </el-form-item>
          <el-form-item label="分管审批意见" prop="remark">
            <el-input v-model="form.managerComment" type="textarea" :autosize="{ minRows: 4 }" placeholder="请输入分管审批意见"
              :disabled="taskName != '分管审核'" />
          </el-form-item>
          <el-row>
            <el-col :span="6" :xs="24" :offset="11">
              <el-form-item label="签名：" label-width="120px">
                <span class="auditor"> {{ form.managerUser ? form.managerUser.nickName : managerUser }} </span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="日期：" label-width="120px">
                <!-- <span> {{ form.managerTime ? form.managerTime : managerTime }} </span> -->
                <el-date-picker v-model="form.managerTime" :disabled="taskName != '分管审核'" type="date"
                  value-format="yyyy-MM-dd" placeholder="选择日期"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="总经理审批意见" prop="gmComment">
            <el-input v-model="form.gmComment" type="textarea" :autosize="{ minRows: 4 }" placeholder="请输入总经理审批意见"
              :disabled="taskName != '总经理审核'" />
          </el-form-item>
          <el-row>
            <el-col :span="6" :xs="24" :offset="11">
              <el-form-item label="签名：" label-width="120px">
                <span class="auditor"> {{ form.gmUser ? form.gmUser.nickName : gmUser }} </span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="日期：" label-width="120px">
                <!-- <span> {{ form.gmTime ? form.gmTime : gmTime }} </span> -->
                <el-date-picker v-model="form.gmTime" :disabled="taskName != '总经理审核'" type="date"
                  value-format="yyyy-MM-dd" placeholder="选择日期"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider></el-divider>
          <el-form-item label="签订日期" prop="signDate">
            <el-date-picker clearable v-model="form.signDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择签订日期"
              :disabled="taskName != '合同签订'">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="签订备注" prop="signRemark">
            <el-input v-model="form.signRemark" type="textarea" placeholder="请输入签订备注" :disabled="taskName != '合同签订'" />
          </el-form-item>
          <el-form-item label="签订扫描件" prop="signScan">
            <FileUpload :disabled="taskName != '合同签订'" v-if="form.signScan == null || form.signScan == ''" :limit="1"
              :filePathName="'分包合同文件'" :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']"
              @input="getSignScanPath">
            </FileUpload>
            <div v-if="form.signScan && taskName != '合同签订'">
              <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + form.signScan}`)">
                {{ getFileName(form.signScan) }}
              </el-link>
              <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + form.signScan}`"
                :underline="false" target="_blank">
                <span class="el-icon-download">下载文件</span>
              </el-link>
            </div>
          </el-form-item>
        </el-form>
        <div style="text-align: center;" v-if="flowDisabled">
          <el-button type="warning" @click="saves()" :disabled="formDisabled" v-if="taskName == '合同拟稿'">保 存</el-button>
          <el-button type="danger" @click="returnOpen = true" :disabled="formDisabled"
            v-if="taskName == '分管审核' || taskName == '总经理审核'">退
            回</el-button>
          <el-button type="primary" @click="submitForm" :disabled="formDisabled">提 交</el-button>
        </div>
      </el-col>
      <el-col :span="6" :xs="24" v-if="flowDisabled">
        <el-card>
          <h2 style="text-align: center;">流程进度</h2>
          <div>
            <flow :flowData="flowData" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog title="选择项目" :visible.sync="open" width="70%" append-to-body>
      <project-choose @chooseProject="confirmProject"></project-choose>
    </el-dialog>
    <el-dialog title="选择合作单位" :visible.sync="partnerOpen" width="70%" append-to-body>
      <choose-partner @confirm="confirmPartners"></choose-partner>
    </el-dialog>
    <el-dialog title="选择承接合同" :visible.sync="contractOpen" width="70%" append-to-body>
      <choose-contract @choose="confirmContract"></choose-contract>
    </el-dialog>
    <el-drawer :visible.sync="drawerOpen" title="" :size="'70%'" append-to-body>
      <projectInfo :needReturn="false"></projectInfo>
    </el-drawer>
    <el-drawer :visible.sync="formOpen" title="" :size="'55%'" append-to-body>
      <contract-form :taskForm="contractId" :taskName="''" :formDisabled="true" :flowDisabled="false"></contract-form>
    </el-drawer>
    <el-dialog title="退回" :visible.sync="returnOpen" width="40%" append-to-body>
      <return-btn :taskForm="taskForm" :comment="taskName == '分管审核' ? form.managerComment : form.gmComment"
        @goBack="$emit('goBack')" @saves="" @cancel="returnOpen = false"></return-btn>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from "@/utils/ruoyi";
import { listProject, getProject } from "@/api/oa/project/project";
import { listDept } from '@/api/system/dept'
import { listUser } from '@/api/system/user'
import { listPartner, getPartner } from "@/api/oa/partner/partner";
import { listContractWork, addContractWork, delContractWork } from "@/api/oa/contract/contractWork";
import { listContractPayment, addContractPayment, delContractPayment } from "@/api/oa/contract/contractPayment";
import { listContractComment, addContractComment, updateContractComment, delContractComment } from "@/api/oa/contract/contractComment";
import { getContractMeeting, addContractMeeting, updateContractMeeting, delContractMeeting } from "@/api/oa/contract/contractMeeting";
import { listProjectContract } from "@/api/oa/contract/projectContract";
import { getContract } from "@/api/oa/contract/contract";
import { listSubContract, getSubContract, delSubContract, addSubContract, updateSubContract } from "@/api/oa/contract/subContract";
import { listContractSubcontract, delContractSubcontract, addContractSubcontract } from "@/api/oa/contract/contractSubcontract"
import { listProjectSubcontract, addProjectSubcontract, delProjectSubcontract } from '@/api/oa/contract/projectSubcontract'
import { getUsersDeptLeader, getUsersManageLeader, getUsersDeptLeaderByDept, getUsersManageLeaderByDept, getUserByPost } from '@/api/system/post.js'
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 { mapGetters } from "vuex";

import projectInfo from '@/views/oa/project/info'
import FileItem from './fileItem.vue';
import workTable from './components/workTable.vue';
import paymentTable from './components/paymentTable.vue';
import projectChoose from '../components/chooseProject.vue';
import ChoosePartner from '../components/choosePartner.vue';
import ChooseContract from '@/views/flowable/form/components/chooseContract.vue';
import contractForm from '@/views/flowable/form/business/contractForm.vue';
import ReturnBtn from '@/views/flowable/form/components/flowBtn/returnBtn.vue';
import ReturnComment from '@/views/flowable/form/components/flowBtn/returnComment.vue';
export default {
  dicts: ['cmc_scale_grade', 'cmc_unit'],
  components: {
    flow,
    projectChoose,
    ChooseContract,
    FileItem,
    ChoosePartner,
    workTable,
    paymentTable,
    contractForm,
    projectInfo,
    ReturnComment,
    ReturnBtn
  },
  props: {
    taskName: {
      type: String,
      required: true
    },
    taskForm: {
      type: Object,
      required: true
    },
    formDisabled: {
      type: Boolean,
      default: false
    },
    flowDisabled: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    ...mapGetters(["userId"]),
  },
  name: "SubContract",
  watch: {
    'taskForm.formId'() {
      this.chooseProjectList = []
      this.initRules();
      this.initForm();
    }
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      draftUser: '',
      draftTime: undefined,
      managerUser: '',
      managerTime: undefined,
      gmUser: '',
      gmTime: undefined,
      hostUser: '',
      commentTime: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // cmc分包合同评审表格数据
      subContractList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      partnerOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contractId: null,
        subContractName: null,
        subAmount: null,
        partnerId: null,
        contactPerson: null,
        drafter: null,
        draftTime: null,
        signDate: null,
        signRemark: null,
        signScan: null,
        commentType: null
      },
      // 表单参数
      form: {},
      meetingForm: {
        users: [],
      },
      // 表单校验
      rules: {},
      meetingOpen: false,
      commentOpen: false,
      projectList: [],
      partnerList: [],
      chooseProject: {},
      chooseProjectList: [],
      chooseContract: {
        contractCode: [],
        contractNumber: [],
        amount: []
      },
      contractCode: '',
      contractNumber: '',
      amount: '',
      deptList: [],
      userList: [],
      users: undefined,
      workList: [],
      paymentList: [],
      placeList: [{ id: '0', name: '301会议室' }, { id: '1', name: '216会议室' }],
      commentList: [
        {
          deptId: 105,
          userId: '',
          comment: '',
          document: '',
          commentTime: undefined
        },
        {
          deptId: 106,
          userId: '',
          comment: '',
          document: '',
          commentTime: undefined
        },
        // {
        //   deptId: 107,
        //   userId: '',
        //   comment: '',
        //   document: '',
        //   commentTime: undefined
        // },
        {
          deptId: 109,
          userId: '',
          comment: '',
          document: '',
          commentTime: undefined
        },
        {
          deptId: 109,
          userId: '',
          comment: '',
          document: '',
          commentTime: undefined
        },
      ],
      isSelect: false,
      formTotal: 0,
      flowData: {},
      clickTd: {},
      contractOpen: false,
      connectContractList: [],
      contractloading: true,
      formOpen: false,
      contractId: {
        formId: ''
      },
      drawerOpen: false,
      showAlter: true,
      returnOpen: false,
    };
  },
  created() {
    if (this.taskName == '合同拟稿') {
      this.draftUser = this.$store.getters.name;
      this.draftTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    else if (this.taskName == '会议评审') {
      this.hostUser = this.$store.getters.name;
      this.commentTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    else if (this.taskName == '分管审核') {
      this.managerUser = this.$store.getters.name;
      this.form.managerUserId = this.$store.getters.userId;
      this.managerTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    else if (this.taskName == '总经理审核') {
      this.gmUser = this.$store.getters.name;
      this.form.gmUserId = this.$store.getters.userId;
      this.gmTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    this.getProjectList();
    this.getPartnerList();
    this.getDeptList();
    this.getUserList();
    this.getList();
    if (this.flowDisabled)
      flowXmlAndNode({ procInsId: this.taskForm.procInsId, deployId: this.taskForm.deployId }).then(res => {
        this.flowData = res.data;
      })
  },
  mounted() {
    this.initRules();
    this.initForm();
  },
  methods: {
    initRules() {
      if (this.taskName == '合同拟稿') {
        this.rules = {
          partnerId: [
            { required: true, message: '请选择承接单位', trigger: 'change' },
          ],
          subContractName: [
            { required: true, message: '请输入分包合同名称', trigger: 'blur' },
          ],
          subAmount: [
            { required: true, message: '请输入分包合同额', trigger: 'blur' },
          ],
          commentType: [
            { required: true, message: '请选择评审方式', trigger: 'change' },
          ],
        }
      } else if (this.taskName == '分管审核') {
        this.rules = {
          managerComment: [
            { required: true, message: '请输入分管审批意见', trigger: 'blur' }
          ]
        }
      }
    },
    initForm() {
      getSubContract(this.taskForm.formId).then(res => {
        this.getContractSubcontractList();
        if (this.isEmptyObject(res.data)) {
          this.formTotal = 0;
          this.form.drafter = this.$store.getters.userId;
          // this.form.draftTime = parseTime(new Date(), '{y}-{m}-{d}');
        }
        else {
          this.formTotal = 1;
          this.form = res.data;
          this.form.partnerId = this.form.partnerId ? this.form.partnerId.split(',') : null;
          if (this.form.commentType == '0') {
            this.commentOpen = false;
            this.meetingOpen = false;
          }
          else if (this.form.commentType == '1') {
            this.commentOpen = false;
            this.meetingOpen = true;
          }
          else if (this.form.commentType == '2') {
            this.commentOpen = true;
            this.meetingOpen = false;
          }
          listProjectSubcontract({ subContractId: res.data.subContractId }).then(res => {
            if (res.rows) {
              res.rows.forEach(project => {
                getProject(project.projectId).then(res => {
                  if (res.data) {
                    this.chooseProjectList.push(res.data);
                    this.confirmProject(this.chooseProjectList)
                  }
                })
              })
            }
          })
          listContractComment({ contractId: this.taskForm.formId }).then(res => {
            if (res.rows && res.rows.length != 0) {
              this.commentList = res.rows;
              for (let comment of this.commentList) {
                if (comment.commentTime == undefined) {
                  if (comment.userId != this.$store.getters.userId) {
                    comment.commentUser = undefined;
                  }
                  else {
                    comment.commentTime = parseTime(new Date(), '{y}-{m}-{d}');
                  }
                }
              }
            }
            else {
              this.commentList = [
                {
                  deptId: 105,
                  userId: '',
                  comment: '',
                  document: '',
                  commentTime: undefined
                },
                {
                  deptId: 106,
                  userId: '',
                  comment: '',
                  document: '',
                  commentTime: undefined
                },
                // {
                //   deptId: 107,
                //   userId: '',
                //   comment: '',
                //   document: '',
                //   commentTime: undefined
                // },
                {
                  deptId: 109,
                  userId: '',
                  comment: '',
                  document: '',
                  commentTime: undefined
                },
                {
                  deptId: 109,
                  userId: '',
                  comment: '',
                  document: '',
                  commentTime: undefined
                },
              ]
              let num = 0;
              for (let comment of this.commentList) {
                num = num + 1;
                if (num <= 3) {
                  getUsersDeptLeaderByDept({ deptId: comment.deptId }).then(res => {
                    comment.userId = res.data.userId;
                  })
                }
                else {
                  getUserByPost({ postName: '专职安全员' }).then(res => {
                    comment.userId = res.data[0].userId;
                  })
                }
              }
            }
          });
          getContractMeeting(this.taskForm.formId).then(res => {
            if (res.data) {
              let data = res.data;
              if (res.data.users == null || res.data.users == undefined || res.data.users == "") {
                data.users = []
              } else {
                data.users = data.users.split(',');
                let arr = []
                for (let d of data.users) {
                  arr.push(parseInt(d))
                }
                data.users = arr;
              }
              this.meetingForm = data;
            }
          });
        }
      })
    },
    /** 查询cmc分包合同评审列表 */
    getList() {
      this.loading = true;
      listSubContract(this.queryParams).then(response => {
        this.subContractList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取关联承接合同
    getContractSubcontractList() {
      this.contractloading = true;
      const subContractId = this.taskForm.formId;
      listContractSubcontract({ subContractId: subContractId }).then(async res => {
        let list = []
        for (let r of res.rows) {
          let obj = await getContract(r.contractId)
          list.push(obj.data)
        }
        this.connectContractList = list
        this.contractloading = false;
      })
    },
    // 查询承接单位列表
    getPartnerList() {
      this.loading = true
      listPartner({
        pageNum: 1,
        pageSize: 99999999
      }).then(response => {
        this.partnerList = response.rows;
      })
    },
    // 查询项目列表
    getProjectList() {
      this.loading = true
      listProject({
        pageNum: 1,
        pageSize: 99999999
      }).then(response => {
        this.projectList = response.rows;
      })
    },
    getUserList() {
      listUser({ pageSize: 9999, pageNum: 1 }).then(res => {
        this.userList = res.rows
      })
    },
    getDeptList() {
      listDept({ pageSize: 9999, pageNum: 1 }).then(res => {
        this.deptList = res.data
      })
    },
    isEmptyObject(obj) {
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          return false;
        }
      }
      return true;
    },
    addCommentList() {
      this.commentList.push({
        deptId: "",
        userId: "",
        comment: "",
        document: "",
        commentTime: undefined,
      });
    },
    deletCommentItem(index) {
      let arr = this.commentList;
      if (arr.length == 1) {
        return;
      }
      if (index >= 0 && index < arr.length) {
        arr.splice(index, 1);
      }
    },
    changeCommentType(val) {
      if (val == '0') {
        this.commentOpen = false;
        this.meetingOpen = false;
      }
      else if (val == '1') {
        this.commentOpen = false;
        this.meetingOpen = true;
      }
      else if (val == '2') {
        this.commentOpen = true;
        this.meetingOpen = false;
        let num = 0;
        for (let comment of this.commentList) {
          num = num + 1;
          if (num <= 3) {
            getUsersDeptLeaderByDept({ deptId: comment.deptId }).then(res => {
              comment.userId = res.data.userId;
            })
          }
          else {
            getUserByPost({ postName: '专职安全员' }).then(res => {
              comment.userId = res.data[0].userId;
            })
          }
        }
      }
    },
    getDeptLeader(val) {
      getUsersDeptLeaderByDept({ deptId: Number(val) }).then(res => {
        for (let comment of this.commentList) {
          if (comment.deptId == val)
            comment.userId = res.data.userId;
        }
      })
    },
    validateDocument(doc) {
      // 这里添加你的验证逻辑  
      // 例如，检查tenderId是否为空或者是否符合其他规则  
      if (!doc || doc.trim() === '') {
        this.$message.error('请上传合同文件');
        return false;
      }
      return true;
    },
    // 保存信息
    async saves() {
      this.workList = this.$refs.workTableRef.workList;
      this.paymentList = this.$refs.paymentRef.paymentList;
      if (this.formTotal != 0) {
        if (this.form.partnerId && this.form.partnerId instanceof Array)
          this.form.partnerId = this.form.partnerId.join(',')
        updateSubContract(this.form).then(response => {
          this.$modal.msgSuccess("表单修改成功");
          this.open = false;
          this.getList();
          this.updateChooseProjectList()
        });
      } else {
        this.form.subContractId = this.taskForm.formId;
        if (this.form.partnerId && this.form.partnerId.length)
          this.form.partnerId = this.form.partnerId.join(',')
        addSubContract(this.form).then(response => {
          this.$modal.msgSuccess("表单新增成功");
          this.open = false;
          this.getList();
          this.formTotal = 1;
        });
        const subContractId = this.form.subContractId;
        this.chooseProjectList.forEach(item => {
          addProjectSubcontract({ subContractId: subContractId, projectId: item.projectId })
        })
        this.connectContractList.forEach(item => {
          addContractSubcontract({ subContractId: subContractId, contractId: item.contractId })
        })
        for (let work of this.workList) {
          work.contractId = subContractId;
          await addContractWork(work);
        }
        for (let payment of this.paymentList) {
          payment.contractId = subContractId;
          await addContractPayment(payment);
        }
        const params = { taskId: this.taskForm.taskId };
        getNextFlowNode(params).then(res => {
          this.contractDraftSubmit(handleComplete)
        })
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.workList = this.$refs.workTableRef.workList;
      this.paymentList = this.$refs.paymentRef.paymentList;
      // let isProjectValid = this.validateManual(this.chooseProjectList);
      let isDocValid = this.validateDocument(this.form.contractDocument)
      if (!isDocValid) {
        // 无效，阻止提交  
        return;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          const handleComplete = (taskForm) => {
            complete(taskForm).then(response => {
              this.$modal.msgSuccess(response.msg);
              this.$emit('goBack');
            })
          };
          if (this.formTotal != 0) {
            if (this.form.partnerId)
              this.form.partnerId = this.form.partnerId.join(',')
            if (this.taskName == '分管审核') {
              this.form.managerUserId = this.$store.getters.userId;
            }
            else if (this.taskName == '总经理审核') {
              this.form.gmUserId = this.$store.getters.userId;
            }
            updateSubContract(this.form).then(response => {
              this.$modal.msgSuccess("表单修改成功");
              this.open = false;
              this.getList();
              this.updateChooseProjectList()
            });
            const params = { taskId: this.taskForm.taskId };
            getNextFlowNode(params).then(res => {
              if (this.taskName == '分管审核') {
                getUserByPost({ postName: '总经理' }).then(res => {
                  this.$set(this.taskForm.variables, "approval", res.data[0].userId);
                  handleComplete(this.taskForm);
                })
              }
              else if (this.taskName == '合同拟稿') {
                this.contractDraftSubmit(handleComplete)
              }
              else if (this.taskName == '线上会审') {
                for (let comment of this.commentList) {
                  updateContractComment(comment);
                }
                getUsersManageLeader({ userId: this.form.drafter }).then(res => {
                  let userIdList = [];
                  userIdList.push(res.data[0].userId)
                  this.$set(this.taskForm.variables, "approvalList", userIdList);
                  handleComplete(this.taskForm);
                })
              }
              else if (this.taskName == '会议评审') {
                this.meetingForm.contractId = this.form.subContractId;
                let formData = new FormData();
                let jsonForm = JSON.stringify(this.meetingForm);
                formData.append("form", jsonForm);
                updateContractMeeting(formData);
                getUsersManageLeader({ userId: this.form.drafter }).then(res => {
                  let userIdList = [];
                  userIdList.push(res.data[0].userId)
                  this.$set(this.taskForm.variables, "approvalList", userIdList);
                  handleComplete(this.taskForm);
                })
              }
              else if (this.taskName == '总经理审核') {
                handleComplete(this.taskForm);
              }
              else if (this.taskName == '合同签订') {
                this.$modal.confirm('最后一个节点，提交将结束流程，是否提交？').then(() => {
                  handleComplete(this.taskForm);
                })
              }
            })
          } else {
            this.form.subContractId = this.taskForm.formId;
            if (this.form.partnerId)
              this.form.partnerId = this.form.partnerId.join(',')
            addSubContract(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
            const subContractId = this.form.subContractId;
            this.chooseProjectList.forEach(item => {
              addProjectSubcontract({ subContractId: subContractId, projectId: item.projectId })
            })
            this.connectContractList.forEach(item => {
              addContractSubcontract({ subContractId: subContractId, contractId: item.contractId })
            })
            for (let work of this.workList) {
              work.contractId = subContractId;
              addContractWork(work);
            }
            for (let payment of this.paymentList) {
              payment.contractId = subContractId;
              addContractPayment(payment);
            }
            const params = { taskId: this.taskForm.taskId };
            getNextFlowNode(params).then(res => {
              this.contractDraftSubmit(handleComplete)
            })

          }
        } else {
          this.$message.error('必填项未填写完毕')
        }
      });
    },
    // 合同拟稿提交事件
    contractDraftSubmit(handleComplete) {
      if (this.commentOpen == false && this.meetingOpen == false) {
        getUsersManageLeaderByDept({ deptId: 105 }).then(res => {
          let userIdList = [];
          userIdList.push(res.data[0].userId)
          this.$set(this.taskForm.variables, "approvalList", userIdList);
          this.$set(this.taskForm.variables, "commentType", '0');
          handleComplete(this.taskForm);
        })
      }
      else if (this.commentOpen == true && this.meetingOpen == false) {
        let approvalList = [];
        for (let comment of this.commentList) {
          comment.contractId = this.form.subContractId
          if (!this.showAlter) {
            if (comment.commentId) {
              updateContractComment(comment)
            } else {
              addContractComment(comment)
            }
          }
          approvalList.push(comment.userId)
        }
        this.$set(this.taskForm.variables, "approvalList", approvalList);
        this.$set(this.taskForm.variables, "commentType", '2');
        handleComplete(this.taskForm);
      }
      else if (this.commentOpen == false && this.meetingOpen == true) {
        this.meetingForm.contractId = this.form.subContractId;
        let formData = new FormData();
        let jsonForm = JSON.stringify(this.meetingForm);
        formData.append("form", jsonForm);
        addContractMeeting(formData);
        this.$set(this.taskForm.variables, "approval", this.meetingForm.hostId);
        this.$set(this.taskForm.variables, "commentType", '1');
        handleComplete(this.taskForm);
      }
    },
    async updateChooseProjectList() {
      this.workList = this.$refs.workTableRef.workList;
      this.paymentList = this.$refs.paymentRef.paymentList;
      const subContractId = this.taskForm.formId;
      try {
        // 删除项目分包合同
        await delProjectSubcontract(subContractId);
        // 添加新的项目分包合同
        for (let item of this.chooseProjectList) {
          await addProjectSubcontract({ subContractId: subContractId, projectId: item.projectId });
        }
        // 删除承接分包合同
        await delContractSubcontract(subContractId);
        // 添加新的承接分包合同
        for (let item of this.connectContractList) {
          await addContractSubcontract({ subContractId: subContractId, contractId: item.contractId });
        }
        // 删除合同工作
        await delContractWork(subContractId);
        // 添加新的合同工作
        for (let work of this.workList) {
          work.contractId = subContractId;
          await addContractWork(work);
        }
        // 删除合同付款
        await delContractPayment(subContractId);
        // 添加新的合同付款
        for (let payment of this.paymentList) {
          payment.contractId = subContractId;
          await addContractPayment(payment);
        }
        this.$modal.msgSuccess("更新成功");
      } catch (error) {
        console.error("更新选择项目列表时出错:", error);
        this.$modal.msgError("更新失败");
      }
    },
    // 确定合作单位
    confirmPartners(val) {
      this.partnerOpen = false
      if (val) {
        let ids = []
        let contactPerson = []
        let telephone = []
        val.map(item => {
          ids.push(item.partnerId)
          if (item.contactPerson)
            contactPerson.push(item.contactPerson)
          if (item.telephone)
            telephone.push(item.telephone)
        })
        this.$set(this.form, 'contactPerson', contactPerson.join(','));
        this.$set(this.form, 'telephone', telephone.join(','));
        this.form.partnerId = ids
      }
    },
    confirmProject(val) {
      this.open = false
      if (val) {
        this.chooseProjectList = val;
        this.isSelect = true
        val.map(item => {
          this.fetchContracts(item.projectId)
            .then(contractData => {
              let [contractCode, contractNumber, amount] = this.processContractData(contractData);
              this.$set(item, 'contractCode', contractCode)
              this.$set(item, 'contractNumber', contractNumber)
              this.$set(item, 'amount', amount)
            })
        })
      }
    },
    async confirmContract(val) {
      let isSame = this.haveSameIds([val], this.connectContractList, 'contractId');
      if (isSame) {
        this.$message.error('请勿重复添加已有的合同');
        return
      }
      this.contractOpen = false;
      this.connectContractList.push(val)

    },
    haveSameIds(arr1, arr2, key) {
      return arr1.some(obj1 => arr2.some(obj2 => obj1[key] === obj2[key]))
    },
    // 获取合同详情
    fetchContracts(projectId) {
      return new Promise((resolve, reject) => {
        listProjectContract({ projectId: projectId }).then(response => {
          if (response.rows) {
            const contractIds = response.rows.map(row => row.contractId);
            Promise.all(contractIds.map(contractId => getContract(contractId)))
              .then(contractData => {
                resolve(contractData);
              })
              .catch(error => {
                reject(error);
              });
          } else {
            resolve([]); // 如果没有合同，返回一个空数组  
          }
        }).catch(error => {
          reject(error);
        });
      });
    },
    // 处理合同编码、合同编号的格式
    processContractData(contractData) {
      let chooseContract = {
        amount: [],
        contractCode: [],
        contractNumber: []
      }
      contractData.forEach(contract => {
        if (contract.data) {
          chooseContract.amount.push(contract.data.amount);
          chooseContract.contractCode.push(contract.data.contractCode);
          chooseContract.contractNumber.push(contract.data.contractNumber);
        }
      });
      let amount = chooseContract.amount.join('、');
      let contractCode = chooseContract.contractCode.join('、');
      let contractNumber = chooseContract.contractNumber.join('、');
      return [contractCode, contractNumber, amount]
    },
    getFileName(name) {
      if (name) {
        let arr = name.split('/')
        return arr[arr.length - 1];
      }
    },
    getContractPath(val) {
      let arr = val.split('/upload')
      this.form.contractDocument = arr[1]
      if (val == "") {
        this.form.contractDocument = ""
      }
    },
    getMeetingPath(val) {
      let arr = val.split('/upload')
      this.meetingForm.document = arr[1]
      if (val == "") {
        this.meetingForm.document = ""
      }
    },
    getSignScanPath(val) {
      let arr = val.split('/upload')
      this.form.signScan = arr[1]
      if (val == "") {
        this.form.signScan = ""
      }
    },
    handleFileDelete(key, val) {
      key[val] = ''
    },
    setCommentDocument(val) {
      let arr = val.split('/upload');
      this.clickTd.document = arr[1];
    },
    clickFile(val) {
      this.clickTd = val
    },
    // 手动验证tenderId的方法  
    validateManual(name) {
      // 这里添加你的验证逻辑  
      // 例如，检查tenderId是否为空或者是否符合其他规则  
      if (name && name.length == 0) {
        this.$message.error('请选择至少一个有效项目');
        return false;
      }
      return true;
    },
    clickContractFn(row) {
      this.formOpen = true;
      this.contractId.formId = row.contractId
    },
    clickProjectFn(row) {
      this.$router.replace({ query: { ...this.$route.query, projectId: row.projectId } });
      this.drawerOpen = true;
    },
    isReturn(val) {
      this.showAlter = val
    }
  }
};
</script>

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

.delete-btn {
  color: #F56C6C;
  cursor: pointer;

  i {
    font-size: 25px;
  }
}

table {
  /*边框*/
  /* border: 1px solid black; */
  text-align: center;
  border-collapse: collapse;

  /*设置背景颜色*/
  /* background-color: #bfa; */
  td {
    padding: 5px;
  }
}

.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>