<!--
 * @Author: ysh
 * @Date: 2024-05-10 15:31:57
 * @LastEditors: wrh
 * @LastEditTime: 2026-01-08 14:57:18
-->
<template>
  <div class="app-container">
    <!-- 承接合同打印 -->
    <el-button type="primary" @click="printOpen = true">打印</el-button>
    <el-dialog :title="title" :visible.sync="printOpen" width="60%" append-to-body>
      <contract-print :form="form" :chooseProjectList="chooseProjectList" :commentList="commentList"
        :partyAList="partyAList" :workList="workList" :paymentList="paymentList"
        @cancel="printOpen = false"></contract-print>
    </el-dialog>
    <el-row :gutter="20">
      <el-col :span="flowDisabled ? 18 : 24" :xs="24">
        <h2 class="text-center"><b>承接合同评审表</b></h2>
        <el-divider></el-divider>
        <div style="text-align:right;">
          <el-button type="warning" size="mini" @click="gotoProjectRegister()" icon="el-icon-plus">项目登记、安排生产</el-button>
        </div>
        <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" :disabled="formDisabled">
          <el-form-item label="投标项目名称：" prop="tenderId">
            <el-button type="primary" size="mini" @click="tbOpen = true" v-if="taskName == '合同拟稿'">选择投标项目</el-button>
            <el-descriptions border v-if="isSelect" style="margin-top: 10px;" :column="3" direction="vertical">
              <el-descriptions-item label="投标项目名称" label-class-name="my-label" :span="3">{{ chooseTender.projectName
              }}</el-descriptions-item>
              <el-descriptions-item label="项目来源" label-class-name="my-label">{{ getProjectSource(chooseTender)
              }}</el-descriptions-item>
              <el-descriptions-item label="联系人" label-class-name="my-label">{{ chooseTender.aPerson
              }}</el-descriptions-item>
              <el-descriptions-item label="联系电话" label-class-name="my-label">{{ chooseTender.aPhone
              }}</el-descriptions-item>
            </el-descriptions>
          </el-form-item>
          <el-form-item label="合同名称" prop="contractName">
            <el-input type="textarea" :rows="3" style="width: 100%;" v-model="form.contractName" placeholder="请输入合同名称"
              :disabled="taskName != '合同拟稿'"></el-input>
          </el-form-item>
          <el-form-item label="甲方单位" prop="partyAId">
            <el-select v-model="form.partyAId" filterable placeholder="请选择" disabled style="width: 100%;">
              <el-option v-for="item in partyAList" :key="item.value" :label="item.partyAName" :value="item.partyAId"
                :disabled="taskName != '合同拟稿'">
              </el-option>
            </el-select>
            <el-button type="primary" @click="partyAOpen = true" size="mini" v-if="taskName == '合同拟稿'">选择单位</el-button>
          </el-form-item>
          <el-form-item label="合同编码" prop="contractCode">
            <el-input style="width: 100%;" v-model="form.contractCode" placeholder="请输入合同编码"
              :disabled="taskName != '合同拟稿'"></el-input>
          </el-form-item>
          <el-form-item label="合同编号" prop="contractNumber">
            <el-input style="width:  100%;" v-model="form.contractNumber" placeholder="请输入合同编号"
              :disabled="taskName != '合同拟稿'"></el-input>
          </el-form-item>
          <el-form-item label="合同金额" prop="amount">
            <el-input style="width:100%;" v-model="form.amount" placeholder="请输入合同金额" :disabled="taskName != '合同拟稿'">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item style="text-align: left;" label="履约保证金" prop="deposit">
            <el-input style="width:100%;" v-model="form.deposit" placeholder="请输入履约保证金" :disabled="taskName != '合同拟稿'">
              <template slot="append">元</template>
            </el-input>
          </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-row>
            <el-form-item label="关联项目" prop="projectIds">
              <el-button type="primary" size="mini" @click="open = true" v-if="taskName == '合同拟稿'">选择项目</el-button>
              <el-table v-loading="projectloading" border :data="chooseProjectList">
                <el-table-column label="序号" type="index" width="50px"></el-table-column>
                <el-table-column label="项目编号" align="center" prop="projectNumber"></el-table-column>
                <el-table-column label="项目名称" align="center" prop="projectName"></el-table-column>
                <el-table-column label="项目负责人" align="center" prop="projectLeaderUser.nickName"></el-table-column>
                <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-row>
          <el-form-item label="关联分包合同">
            <el-button type="primary" size="mini" @click="subOpen = true" icon="el-icon-plus"
              v-if="taskName == '合同拟稿'">新增分包合同</el-button>
            <el-table v-loading="subloading" border :data="connectSubContractList">
              <el-table-column type="index" label="序号" width="55" align="center" />
              <el-table-column label="合同名称" align="center" prop="subContractName" />
              <el-table-column label="承接单位" align="center" prop="partner.partnerName" />
              <el-table-column label="分包合同金额" align="center" prop="subAmount" width="120" />
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button type="text" icon="el-icon-view" @click="clickSubFn(scope.row)">查看</el-button>
                  <el-button type="text" style="color:#F56C6C;" icon="el-icon-delete" v-if="taskName == '合同拟稿'"
                    @click="handleDeleteSub(scope.$index, scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <!-- 表1：合同计划工作量 -->
          <work-table ref="workTableRef" :contractId="taskForm.formId" :taskName="taskName"
            @update:workList="updateWorkList"></work-table>

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

          <!-- 表2：合同回款计划  -->
          <payment-table ref="paymentRef" :contractId="taskForm.formId" :amount="form.amount" :taskName="taskName"
            @update:paymentList="updatePaymentList"></payment-table>

          <el-form-item label="合同备注" prop="remark">
            <el-input v-model="form.remark" :autosize="{ minRows: 4 }" type="textarea" 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">
                <el-date-picker v-model="form.draftTime" :disabled="taskName != '合同拟稿'" type="date"
                  value-format="yyyy-MM-dd" placeholder="选择日期" style="width:190px;">
                </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 < 3 && 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 < 3 && 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" style="width:100%;">
              <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 filterable 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">
                  <FileUpload :disabled="taskName != '会议评审'"
                    v-if="meetingForm.document == '' || meetingForm.document == null" ref="meetingDocument" :limit="1"
                    :filePathName="'承接合同/会议评审意见'" :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']"
                    @input="getMeetingPath"></FileUpload>
                  <div v-if="meetingForm.document != '' && meetingForm.document != null">
                    <file-item :document="meetingForm.document"></file-item>
                  </div>
                  <!-- <el-input v-model="meetingForm.document" clearable :disabled="taskName != '会议评审'"></el-input> -->
                </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-divider></el-divider>
          <el-form-item label="分管审批意见" prop="managerComment">
            <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="选择日期" style="width:190px;"></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="选择日期" style="width:190px;"></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" :autosize="{ minRows: 4 }" placeholder="请输入签订备注"
              :disabled="taskName != '合同签订'" />
          </el-form-item>
          <el-form-item label="签订扫描件" prop="signScan">
            <!-- <el-input v-model="form.signScan" placeholder="请输入签订扫描件" :disabled="taskName != '合同签订'" /> -->
            <FileUpload :disabled="taskName != '合同签订'" v-if="form.signScan == null || form.signScan == ''"
              ref="contractFile" :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="taskName">
          <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="60%" append-to-body>
      <choose-project @chooseProject="confirmProject"></choose-project>
    </el-dialog>
    <el-dialog title="选择投标项目" :visible.sync="tbOpen" width="60%" append-to-body>
      <choose-tender @choose="confirmTender"></choose-tender>
    </el-dialog>
    <el-dialog title="选择甲方单位" :visible.sync="partyAOpen" width="60%" append-to-body>
      <choose-party-a @confirm="confirmPartyA"></choose-party-a>
    </el-dialog>
    <el-dialog :visible.sync="subOpen" title="选择分包合同" :size="'70%'" append-to-body>
      <choose-subcontract @choose="confirmSubContract"></choose-subcontract>
    </el-dialog>
    <el-drawer :visible.sync="drawerOpen" title="" :size="'70%'" append-to-body @close="closeDrawerFn">
      <projectInfo :needReturn="false"></projectInfo>
    </el-drawer>
    <el-drawer :visible.sync="subInfoOpen" title="" :size="'55%'" append-to-body>
      <sub-contract :taskForm="subContractId" :taskName="''" :formDisabled="true" :flowDisabled="false"></sub-contract>
    </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 { listContract, getContract, delContract, addContract, updateContract } from "@/api/oa/contract/contract";
import { listContractWork, addContractWork, delContractWork } from "@/api/oa/contract/contractWork";
import { listContractPayment, addContractPayment, delContractPayment } from "@/api/oa/contract/contractPayment";
import { listContractComment, addContractComment, updateContractComment } from "@/api/oa/contract/contractComment";
import { getContractMeeting, addContractMeeting, updateContractMeeting } from "@/api/oa/contract/contractMeeting";
import { listProjectContract, addProjectContract, delProjectContract } from "@/api/oa/contract/projectContract";
import { complete, rejectTask, returnList, returnTask, getNextFlowNode, delegate, flowTaskForm, } from "@/api/flowable/todo";
import { listTender, getTender } from "@/api/oa/tender/tender";
import { getUsersDeptLeader, getUsersManageLeader, getUsersDeptLeaderByDept, getUsersManageLeaderByDept, getUserByPost } from '@/api/system/post.js'
import { listSubContract, getSubContract, delSubContract, addSubContract, updateSubContract } from "@/api/oa/contract/subContract";
import { listContractSubcontract, delContractSubcontract, addContractSubcontract } from "@/api/oa/contract/contractSubcontract"
import flow from '@/views/flowable/task/todo/detail/flow'
import { definitionStart, flowXmlAndNode } from "@/api/flowable/definition";
import { listPartyA } from "@/api/oa/partyA/partyA";
import { mapGetters } from "vuex";
import projectInfo from '@/views/oa/project/info'
import { listDefinition } from "@/api/flowable/definition";
import { Snowflake } from '@/utils/snowFlake.js'
import { todoList, getNextFlowNodeByStart } from "@/api/flowable/todo";

import FileItem from './fileItem.vue';
import ChooseProject from '../components/chooseProject.vue';
import ChooseTender from '../components/chooseTender.vue';
import workTable from './components/workTable.vue';
import paymentTable from './components/paymentTable.vue';
import subContract from '@/views/flowable/form/business/subContract.vue';
import ChoosePartyA from '@/views/flowable/form/components/choosePartyA.vue';
import ChooseSubcontract from '@/views/flowable/form/components/chooseSubcontract.vue';
import ReturnComment from '@/views/flowable/form/components/flowBtn/returnComment.vue';
import ReturnBtn from '@/views/flowable/form/components/flowBtn/returnBtn.vue';
import ContractPrint from '@/views/flowable/form/components/print/contractPrint.vue';

export default {
  dicts: ['cmc_scale_grade', 'cmc_unit'],
  components: {
    flow, ChooseProject, ChooseTender, FileItem, ChoosePartyA, workTable, paymentTable,
    projectInfo, ChooseSubcontract, subContract, ReturnComment, ReturnBtn, ContractPrint
  },
  props: {
    taskName: {
      type: String,
      required: true
    },
    taskForm: {
      type: Object,
      required: true
    },
    formDisabled: {
      type: Boolean,
      default: false
    },
    flowDisabled: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    ...mapGetters(["userId"]),
  },
  watch: {
    'taskForm.formId'(newval) {
      this.projectloading = true
      this.getProjectList();
      this.getDeptList();
      this.getTenderList();
      this.getUserList();
      this.initForm();
    }
  },
  name: "Contract",
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      isTenderIdValid: true, // 用于跟踪tenderId是否有效 
      isDocumentValid: true,
      draftUser: '',
      draftTime: undefined,
      managerUser: '',
      managerTime: undefined,
      gmUser: '',
      gmTime: undefined,
      hostUser: '',
      commentTime: undefined,
      // 遮罩层
      loading: true,
      projectloading: true,
      subloading: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      subOpen: false,
      tbOpen: false,
      partyAOpen: false,
      // 表单参数
      form: {
        amount: 0,
        deposit: 0,
      },
      meetingForm: {
        users: [],
      },
      projectContractForm: {
        projectIds: [],
      },
      // 表单校验
      rules: {},
      meetingOpen: false,
      commentOpen: false,
      drawerOpen: false,
      subInfoOpen: false,
      chooseProjectList: [],
      connectSubContractList: [],
      partyAList: [],
      projectList: [],
      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
        },
      ],
      tenderList: [],
      chooseTender: {},
      isSelect: false,
      formTotal: 0,
      flowData: {},
      clickTd: {},
      subContractId: {
        formId: ''
      },
      showAlter: true,
      returnOpen: false,
      printOpen: 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.getPartyAList();
    this.getDeptList();
    this.getTenderList();
    this.getUserList();
    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 = {
          contractCode: [
            { required: true, message: '请输入合同编码', trigger: 'blur' },
          ],
          commentType: [
            { required: true, message: '请选择评审方式', trigger: 'change' },
          ]
        }
      } else if (this.taskName == '分管审核') {
        this.rules = {
          managerComment: [
            { required: true, message: '请输入分管审批意见', trigger: 'blur' }
          ]
        }
      }
    },
    initForm() {
      getContract(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}');
          this.projectloading = false;
        }
        else {
          this.formTotal = 1;
          this.form = res.data;
          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;
          }
          if (res.data.tenderId) {
            getTender(res.data.tenderId).then(response => {
              this.chooseTender = response.data;
              this.isSelect = true
            })
          }
          listContractComment({ pageNum: 1, pageSize: 100, 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: 109,
                  userId: '',
                  comment: '',
                  document: '',
                  commentTime: undefined
                },
              ]
              for (let comment of this.commentList) {
                getUsersDeptLeaderByDept({ deptId: comment.deptId }).then(res => {
                  comment.userId = res.data.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;
            }
          });
          listProjectContract({ contractId: this.taskForm.formId }).then(res => {
            if (res.rows) {
              let list = []
              for (let row of res.rows) {
                this.projectContractForm.projectIds.push(row.projectId);
                getProject(row.projectId).then(response => {
                  list.push(response.data)
                })
              }
              this.chooseProjectList = list;
              this.projectloading = false;
            }
          })
        }
      })
    },
    // 获取关联分包合同
    getContractSubcontractList() {
      this.subloading = true;
      const contractId = this.taskForm.formId;
      listContractSubcontract({ contractId: contractId }).then(async res => {
        let list = []
        for (let r of res.rows) {
          let obj = await getSubContract(r.subContractId)
          list.push(obj.data)
        }
        this.connectSubContractList = list
        this.subloading = false;
      })
    },
    // 查询业主单位列表
    getPartyAList() {
      this.loading = true
      listPartyA({
        pageNum: 1,
        pageSize: 99999999
      }).then(response => {
        this.partyAList = 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
      })
    },
    // 查询项目列表
    getTenderList() {
      this.loading = true
      listTender({
        pageNum: 1,
        pageSize: 99999999
      }).then(response => {
        this.tenderList = response.rows;
      })
    },
    // 选择项目
    handleSelectTender(val) {
      if (val != "" && val != undefined && val != null) {
        getTender(val).then(res => {
          this.chooseTender = res.data;
          this.isSelect = true;
        })
      } else {
        this.isSelect = false
      }
    },
    isEmptyObject(obj) {
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          return false;
        }
      }
      return true;
    },
    getProjectSource(chooseTender) {
      const TARGET_COMPANY = '中国电建集团成都勘测设计研究院有限公司';
      if (!chooseTender || !chooseTender.partyA || !chooseTender.partyA.partyAName) {
        return '';
      }
      return chooseTender.partyA.partyAName.includes(TARGET_COMPANY) ? '院内' : '院外';
    },
    addCommentList() {
      this.commentList.push({
        deptId: "",
        userId: "",
        comment: "",
        document: "",
        commentTime: undefined,
      });
    },
    setCommentDocument(val) {
      let arr = val.split('/upload');
      this.clickTd.document = arr[1];
    },
    handleFileDelete(key, val) {
      key[val] = ''
    },
    clickFile(val) {
      this.clickTd = val
    },
    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;
        for (let comment of this.commentList) {
          getUsersDeptLeaderByDept({ deptId: comment.deptId }).then(res => {
            comment.userId = res.data.userId;
          })
        }
      }
    },
    getDeptLeader(val) {
      getUsersDeptLeaderByDept({ deptId: Number(val) }).then(res => {
        for (let comment of this.commentList) {
          if (comment.deptId == val)
            comment.userId = res.data.userId;
        }
      })
    },
    handleSelectProject() {
      this.chooseProjectList = [];
      for (let projectId of this.projectContractForm.projectIds) {
        getProject(projectId).then(res => {
          this.chooseProjectList.push(res.data)
        })
      }
    },
    // 表单重置
    reset() {
      this.form = {
        contractId: null,
        contractCode: null,
        contractNumber: null,
        amount: null,
        deposit: null,
        contractDocument: null,
        drafter: null,
        draftTime: null,
        remark: null,
        signDate: null,
        signRemark: null,
        signScan: null,
        commentType: ''
      };
      this.resetForm("form");
    },
    // 手动验证tenderId的方法  
    validateTenderId(tenderId) {
      // 这里添加你的验证逻辑  
      // 例如，检查tenderId是否为空或者是否符合其他规则  
      if (!tenderId) {
        this.$message.error('请选择一个有效的投标项目');
        return false;
      }
      return true;
    },
    validateDocument(doc) {
      // 这里添加你的验证逻辑  
      // 例如，检查tenderId是否为空或者是否符合其他规则  
      if (!doc || doc.trim() === '') {
        this.$message.error('请上传合同文件');
        return false;
      }
      return true;
    },
    // 保存信息
    saves() {
      if (this.formTotal != 0) {
        this.updateContractData();
        this.updateRelatedProject();
      } else {
        this.form.contractId = this.taskForm.formId;
        addContract(this.form).then(async response => {
          if (response.code == 200) {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            for (let work of this.workList) {
              work.contractId = this.form.contractId
              await addContractWork(work);
            }
            for (let payment of this.paymentList) {
              payment.contractId = this.form.contractId
              await addContractPayment(payment);
            }
            for (let projectId of this.projectContractForm.projectIds) {
              await addProjectContract({ projectId: projectId, contractId: this.form.contractId });
            }
            this.formTotal = 1
          } else {
            this.$message.error("新增失败，请确认合同编码是否唯一");
          }
        });
      }
    },
    /** 提交按钮 */
    submitForm() {
      // this.isTenderIdValid = this.validateTenderId(this.form.tenderId);
      this.isDocumentValid = this.validateDocument(this.form.contractDocument)
      if (!this.isDocumentValid) {
        return;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.formTotal != 0) {
            if (this.taskName == '分管审核') {
              this.form.managerUserId = this.$store.getters.userId;
            }
            else if (this.taskName == '总经理审核') {
              this.form.gmUserId = this.$store.getters.userId;
            }
            const params = { taskId: this.taskForm.taskId };
            this.updateContractData();
            this.updateRelatedProject();
            if (this.taskName == '合同拟稿') {
              this.firstGetNextFlow();
              return
            }
            getNextFlowNode(params).then(res => {
              if (this.taskName == '分管审核') {
                getUserByPost({ postName: '总经理' }).then(res => {
                  this.$set(this.taskForm.variables, "approval", res.data[0].userId);
                  complete(this.taskForm).then(response => {
                    this.$modal.msgSuccess(response.msg);
                    this.$emit('goBack')
                  });
                })
              }
              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);
                  complete(this.taskForm).then(response => {
                    this.$modal.msgSuccess(response.msg);
                    this.$emit('goBack')
                  });
                })
              }
              else if (this.taskName == '会议评审') {
                this.meetingForm.contractId = this.form.contractId;
                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);
                  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 == '合同签订') {
                this.$modal.confirm('最后一个节点，提交将结束流程，是否提交？').then(() => {
                  complete(this.taskForm).then(response => {
                    this.$modal.msgSuccess(response.msg);
                    this.$emit('goBack')
                  });
                })
              }
            })
          } else {
            this.form.contractId = this.taskForm.formId;

            addContract(this.form).then(response => {
              if (response.code == 200) {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                for (let work of this.workList) {
                  work.contractId = this.form.contractId
                  addContractWork(work);
                }
                for (let payment of this.paymentList) {
                  payment.contractId = this.form.contractId
                  addContractPayment(payment);
                }
                for (let projectId of this.projectContractForm.projectIds) {
                  addProjectContract({ projectId: projectId, contractId: this.form.contractId });
                }
                this.firstGetNextFlow();
              } else {
                this.$message.error("新增失败，请确认合同编码是否唯一");
              }
            });
          }
        } else {
          this.$message.error('请完善必填项')
        }
      });
    },
    updateContractData() {
      this.workList = this.$refs.workTableRef.workList;
      this.paymentList = this.$refs.paymentRef.paymentList;
      updateContract(this.form).then(response => {
        this.$modal.msgSuccess("保存成功");
        this.open = false;
        // 删除合同的工作和支付信息，并等待两个操作完成
        Promise.all([
          delContractWork(this.form.contractId),
          delContractPayment(this.form.contractId)
        ]).then(async ([workRes, paymentRes]) => {
          // 添加工作信息
          for (const work of this.workList) {
            work.contractId = this.form.contractId;
            await addContractWork(work);
          }
          // 添加支付信息
          for (const payment of this.paymentList) {
            payment.contractId = this.form.contractId;
            await addContractPayment(payment);
          }
          // 等待所有添加操作完成
          return Promise.all();
        }).then(() => {
          // this.$modal.msgSuccess("计划工作量和回款计划添加成功");
        }).catch(error => {
          // this.$modal.msgError("操作失败: " + error.message);
        });
      }).catch(error => {
        this.$modal.msgError("合同更新失败: " + error.message);
      });
    },
    updateRelatedProject() {
      delProjectContract(this.taskForm.formId).then(() => {
        for (let projectId of this.projectContractForm.projectIds) {
          addProjectContract({ projectId: projectId, contractId: this.taskForm.formId });
        }
      })
    },
    firstGetNextFlow() {
      const params = { taskId: this.taskForm.taskId };
      getNextFlowNode(params).then(res => {
        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');
            complete(this.taskForm).then(response => {
              this.$modal.msgSuccess(response.msg);
              this.$emit('goBack')
            });
          })
        }
        else if (this.commentOpen == true && this.meetingOpen == false) {
          let approvalList = [];
          for (let comment of this.commentList) {
            comment.contractId = this.form.contractId
            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');
          complete(this.taskForm).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.$emit('goBack')
          });
        }
        else if (this.commentOpen == false && this.meetingOpen == true) {
          this.meetingForm.contractId = this.form.contractId;
          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');
          complete(this.taskForm).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.$emit('goBack')
          });
        }
      })
    },
    getContractPath(val) {
      let arr = val.split('/upload')
      this.form.contractDocument = arr[1]
      if (val == "") {
        this.form.contractDocument = ""
      }
    },
    getSignScanPath(val) {
      let arr = val.split('/upload')
      this.form.signScan = arr[1]
      if (val == "") {
        this.form.signScan = ""
      }
    },
    getMeetingPath(val) {

    },
    getFileName(name) {
      if (name) {
        let arr = name.split('/')
        return arr[arr.length - 1];
      }

    },
    confirmProject(val) {
      this.open = false
      for (let v of val) {
        this.projectContractForm.projectIds.push(v.projectId);
      }
      this.chooseProjectList = val
    },
    confirmTender(val) {
      this.tbOpen = false
      this.form.amount = val.quote
      this.form.deposit = val.deposit
      this.form.tenderId = val.tenderId
      this.chooseTender = val
      this.isSelect = true
      this.form.partyAId = val.partyAId
    },
    confirmPartyA(val) {
      this.partyAOpen = false
      if (val && val.length > 1) {
        return this.$message.error('请选择一个甲方单位')
      }
      if (val) {
        this.getPartyAList();
        this.$set(this.form, 'partyAId', val[0].partyAId)
      }
    },
    async confirmSubContract(val) {
      let isSame = this.haveSameIds(val, this.connectSubContractList, 'subContractId');
      if (isSame) {
        this.$message.error('请勿重复添加已有的分包合同')
        return
      }
      this.subOpen = false
      for (let v of val) {
        this.connectSubContractList.push(v)
        await addContractSubcontract({ contractId: this.taskForm.formId, subContractId: v.subContractId })
      }
      this.getContractSubcontractList()
    },
    haveSameIds(arr1, arr2, key) {
      return arr1.some(obj1 => arr2.some(obj2 => obj1[key] === obj2[key]))
    },
    reviewWord(url) {
      this.$router.push({
        path: '/preview',
        query: {
          url: url
        }
      })
    },
    clickProjectFn(row) {
      this.$router.replace({ query: { ...this.$route.query, projectId: row.projectId } });
      this.drawerOpen = true;
      // 找到当前tab并修改当前tab显示的标题
      let currentView = this.$store.state.tagsView.visitedViews.find(item => item.path === this.$route.path);
      if (currentView != null) {
        currentView.title = row.projectName;
      }
    },
    closeDrawerFn() {
      this.drawerOpen = false;
      // 只需要删除 query 中的 projectId参数，保留其他参数
      const { projectId, ...otherQuery } = this.$route.query;
      this.$router.replace({ 
        path: this.$route.path, 
        query: otherQuery 
      });
      // 找到当前tab并修改当前tab显示的标题为"承接合同"
      let currentView = this.$store.state.tagsView.visitedViews.find(item => item.path === this.$route.path);
      if (currentView != null) {
        currentView.title = '承接合同';
      }
    },
    clickSubFn(row) {
      this.subContractId.formId = row.subContractId
      this.subInfoOpen = true
    },
    handleDeleteSub(index, row) {
      delContractSubcontract(row.subContractId)
      this.connectSubContractList.splice(index, 1)
    },
    // 跳转项目流转，并结束流程
    async gotoProjectRegister() {
      let response = await listDefinition({
        pageNum: 1,
        pageSize: 9999,
        name: "项目流转",
        category: "project",
      })
      if (response.data.total == 1) {
        let obj = response.data.records[0]
        this.$confirm("是否发起项目流转？若页面未跳转，请刷新页面", '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.handleStartProcess(obj)
        })
      }
    },
    handleStartProcess(row) {
      let formId = new Snowflake(1n, 1n, 0n).nextId().toString();
      getNextFlowNodeByStart({ deploymentId: row.deploymentId, variables: { formId: formId } }).then(res => {
        let data = res.data;
        const variables = {};
        const formData = {};
        formData.disabled = true;
        formData.formBtns = false;
        formData.formId = formId
        if (row.id) {
          variables.variables = formData;
          let routePath = this.getRoutePath(row);
          this.$emit('goBack');
          this.$cache.local.set('contractId', `${this.taskForm.formId}`)
          definitionStart(row.id, JSON.stringify(variables)).then(res => {
            this.$modal.msgSuccess(res.msg);
            let procInstanceId = res.data;
            todoList({
              pageNum: 1,
              pageSize: 99999999, processInsId: procInstanceId
            }).then(toDoRes => {
              let records = toDoRes.data.records;
              if (records.length == 1) {
                records = records[0]
              }
              this.$router.push({
                path: routePath,
                query: {
                  procInsId: records.procInsId,
                  executionId: records.executionId,
                  deployId: records.deployId,
                  taskId: records.taskId,
                  taskName: records.taskName,
                  startUser: records.startUserName + '-' + records.startDeptName,
                  formId: formData.formId,
                  procDefName: records.procDefName,
                }
              })
            })
          })
        }
      })
    },
    getRoutePath(row) {
      let path;
      for (let p of this.publicData.pathRoute) {
        if (p.name == row.name) {
          path = p.path
          break
        } else {
          path = '/flowable/task/todo/detail/index'
        }
      }
      return path
    },
    isReturn(val) {
      this.showAlter = val
    },
    updateWorkList(newWorkList) {
      this.workList = newWorkList;
    },
    updatePaymentList(newPaymentList) {
      this.paymentList = newPaymentList;
    }
  }
}
</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;
  border: 1px solid #a5abb0;

  /*设置背景颜色*/
  /* 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;
}

::v-deep .el-descriptions-item__label.is-bordered-label {
  color: #5a5757;
  background: rgba($color: #a9adb3, $alpha: 0.1);
  width: 150px;
  min-width: 150px;
}

::v-deep .el-descriptions .is-bordered .el-descriptions-item__cell {
  border: 1px solid #cdd0d3;
}
</style>