<!--
 * @Author: ysh
 * @Date: 2024-05-10 15:31:57
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-07-09 17:42:01
-->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="flowDisabled ? 18 : 24" :xs="24">
        <h2 class="text-center"><b>承接合同评审表</b></h2>
        <el-divider></el-divider>
        <el-form ref="form" :model="form" :rules="rules" label-width="130px" :disabled="formDisabled">
          <el-row :gutter="20">
            <el-col :span="12" :xs="24">
              <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-col>

            <el-col :span="12" :xs="24">
              <el-alert title="后签合同的项目，必须选择关联项目；先签合同的项目不选关联项目" type="error">
              </el-alert>
              <el-form-item label="关联项目：" prop="projectIds">
                <el-button type="primary" size="mini" @click="open = true" v-if="taskName == '合同拟稿'">选择项目</el-button>
              </el-form-item>
              <el-table v-loading="projectloading" :data="chooseProjectList">
                <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>
            </el-col>

          </el-row>
          <el-form-item label="合同文件" prop="contractDocument">
            <FileUpload v-if="taskName == '合同拟稿'" :disabled="taskName != '合同拟稿'" ref="contractFile" :limit="1"
              :filePathName="'承接合同/合同文件'" :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf']" @input="getContractPath">
            </FileUpload>
            <div v-if="form.contractDocument && taskName != '合同拟稿'">
              <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>
            </div>
          </el-form-item>
          <el-form-item label="合同计划工作量：">
            <table border="1" style="width:100%">
              <tr>
                <td style="width: 50px;">序号</td>
                <td style="width:180px">工作内容</td>
                <td>等级或比例尺</td>
                <td>单位</td>
                <td>工作量</td>
                <td>要求完成时间</td>
                <td>备注</td>
              </tr>
              <tr v-for="(work, index) in workList" :key="index">
                <td>
                  {{ index + 1 }}
                </td>
                <td>
                  <el-input v-model="work.content" type="textarea" clearable :autosize="{ minRows: 4 }"
                    :disabled="taskName != '合同拟稿'"></el-input>
                </td>
                <td>
                  <el-select v-model="work.scale" placeholder="请选择" clearable :disabled="taskName != '合同拟稿'">
                    <el-option v-for="dict in dict.type.cmc_scale_grade" :key="dict.value" :label="dict.label"
                      :value="dict.label" />
                  </el-select>
                </td>
                <td>
                  <el-select v-model="work.unit" placeholder="请选择" clearable :disabled="taskName != '合同拟稿'">
                    <el-option v-for="dict in dict.type.cmc_unit" :key="dict.value" :label="dict.label"
                      :value="dict.label" />
                  </el-select>
                </td>
                <td>
                  <el-input-number :controls="false" style="width: 60px" v-model="work.workload" clearable
                    :disabled="taskName != '合同拟稿'"></el-input-number>
                </td>
                <td>
                  <el-date-picker style="width: 140px" v-model="work.deadline" value-format="yyyy-MM-dd" type="date"
                    placeholder="选择日期" :disabled="taskName != '合同拟稿'">
                  </el-date-picker>
                </td>
                <td>
                  <el-input v-model="work.remark" type="textarea" clearable :autosize="{ minRows: 4 }"
                    :disabled="taskName != '合同拟稿'"></el-input>
                </td>
                <td>
                  <el-button type="danger" icon="el-icon-minus" size="mini" circle @click="deletWorkItem(index)"
                    :disabled="taskName != '合同拟稿'"></el-button>
                </td>
              </tr>
            </table>
            <el-button icon="el-icon-plus" size="mini" @click="addWorkList()" type="primary" plain
              :disabled="taskName != '合同拟稿'"></el-button>
          </el-form-item>
          <el-form-item label="合同回款计划：">
            <table border="1" style="width:100%">
              <tr>
                <td style="width: 50px;">序号</td>
                <td style="width: 250px;">回款条件</td>
                <td>回款比例（%）</td>
                <td>回款金额（元）</td>
                <td>预计时间</td>
                <td>备注</td>
              </tr>
              <tr v-for="(payment, index) in paymentList" :key="index">
                <td>
                  {{ index + 1 }}
                </td>
                <td>
                  <el-input v-model="payment.paymentCondition" type="textarea" clearable :autosize="{ minRows: 4 }"
                    :disabled="taskName != '合同拟稿'"></el-input>
                </td>
                <td>
                  <el-input-number style="width:100px" :controls="false" v-model="payment.paymentPercentage" clearable
                    :disabled="taskName != '合同拟稿'" @change="calculatePaymentAmount(payment)"></el-input-number>
                </td>
                <td>
                  <el-input-number style="width:150px" :controls="false" :precision="2" v-model="payment.paymentAmount"
                    clearable :disabled="taskName != '合同拟稿'"></el-input-number>
                </td>
                <td>
                  <el-date-picker style="width: 140px" v-model="payment.paymentTime" value-format="yyyy-MM-dd" type="date"
                    placeholder="选择日期" :disabled="taskName != '合同拟稿'">
                  </el-date-picker>
                </td>
                <td>
                  <el-input v-model="payment.remark" type="textarea" clearable :autosize="{ minRows: 4 }"
                    :disabled="taskName != '合同拟稿'"></el-input>
                </td>
                <td>
                  <el-button type="danger" icon="el-icon-minus" size="mini" circle @click="deletPaymentItem(index)"
                    :disabled="taskName != '合同拟稿'"></el-button>
                </td>
              </tr>
            </table>
            <el-button icon="el-icon-plus" size="mini" @click="addPaymentList()" type="primary" plain
              :disabled="taskName != '合同拟稿'"></el-button>
          </el-form-item>
          <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="12">
              <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-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">
              <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: 4 }"
                    :disabled="taskName != '线上会审' || (taskName == '线上会审' && comment.userId != userId)"></el-input>
                </td>
                <td style="text-align:left;" @click="clickFile(comment)">
                  <FileUpload v-if="comment.document == '' || comment.document == null" ref="hs" :limit="1"
                    :filePathName="'承接合同/线上会审意见'"
                    :disabled="taskName != '线上会审' || (taskName == '线上会审' && comment.userId != userId)"
                    :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf']" @input="setCommentDocument">
                  </FileUpload>

                  <!-- <el-input v-model="comment.document" clearable
                    :disabled="taskName != '线上会审' || (taskName == '线上会审' && !comment.commentUser)"></el-input> -->
                  <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="comment.userId == userId">
                          <el-link :underline="false" @click="handleFileDelete(comment, 'document')"
                            type="danger">删除</el-link>
                        </div>
                        <button class="preview-btn" type="primary" size="mini" plain
                          @click="reviewWord(`${baseUrl}${'/profile/upload' + comment.document}`)">在线预览</button>
                      </li>
                    </transition-group>
                  </div>
                </td>
                <td>
                  <span class="auditor"> {{ comment.commentUser ? comment.commentUser.nickName : '' }} </span>
                </td>
                <td>
                  <span> {{ comment.commentTime }} </span>
                </td>
                <td>
                  <el-button type="text" style="color: #F56C6C;" size="mini" @click="deletCommentItem(index)"
                    :disabled="taskName != '合同拟稿'">删除行</el-button>
                </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 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']"
                    @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="12">
              <el-form-item label="签名：" label-width="120px"
                v-if="taskName != '合同拟稿' && taskName != '线上会审' && taskName != '会议评审'">
                <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"
                v-if="taskName != '合同拟稿' && taskName != '线上会审' && taskName != '会议评审'">
                <span> {{ form.managerTime ? form.managerTime : managerTime }} </span>
              </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="12">
              <el-form-item label="签名：" label-width="120px"
                v-if="taskName != '合同拟稿' && taskName != '线上会审' && taskName != '会议评审' && taskName != '分管审核'">
                <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"
                v-if="taskName != '合同拟稿' && taskName != '线上会审' && taskName != '会议评审' && taskName != '分管审核'">
                <span> {{ form.gmTime ? form.gmTime : gmTime }} </span>
              </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']"
              @input="getSignScanPath">
            </FileUpload>
            <div v-if="form.signScan && taskName != '合同签订'">
              <!-- <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' + form.signScan}`" :underline="false" target="_blank">
                    <span class="el-icon-document" style="color:#0011ff;text-decoration: underline;">
                      {{ getFileName(form.signScan) }}
                    </span>
                  </el-link>
                  <div class="ele-upload-list__item-content-action" v-if="taskName != ''">
                    <el-link :underline="false" @click="handleFileDelete(form, 'signScan')" type="danger">删除</el-link>
                  </div>
                  <button class="preview-btn" type="primary" size="mini" plain
                    @click="reviewWord(`${baseUrl}${'/profile/upload' + form.signScan}`)">在线预览</button>
                </li>
              </transition-group> -->
              <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="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>
      <choose-project @chooseProject="confirmProject"></choose-project>
    </el-dialog>
    <el-dialog title="选择投标项目" :visible.sync="tbOpen" width="70%" append-to-body>
      <choose-tender @choose="confirmTender"></choose-tender>
    </el-dialog>
    <el-dialog title="选择甲方单位" :visible.sync="partyAOpen" width="70%" append-to-body>
      <choose-party-a @confirm="confirmPartyA"></choose-party-a>
    </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 flow from '@/views/flowable/task/todo/detail/flow'
import { flowXmlAndNode } from "@/api/flowable/definition";
import ChooseProject from '../components/chooseProject.vue';
import ChooseTender from '../components/chooseTender.vue';
import { listPartyA } from "@/api/oa/partyA/partyA";
import FileItem from './fileItem.vue';
import { mapGetters } from "vuex";
import ChoosePartyA from '@/views/flowable/form/components/choosePartyA.vue';
export default {
  dicts: ['cmc_scale_grade', 'cmc_unit'],
  components: {
    flow,
    ChooseProject,
    ChooseTender,
    FileItem,
    ChoosePartyA
  },
  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,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      tbOpen: false,
      partyAOpen: false,
      // 表单参数
      form: {
        amount: 0,
        deposit: 0,
      },
      meetingForm: {
        users: [],
      },
      projectContractForm: {
        projectIds: [],
      },
      // 表单校验
      rules: {},
      meetingOpen: false,
      commentOpen: false,
      chooseProjectList: [],
      partyAList: [],
      projectList: [],
      deptList: [],
      userList: [],
      users: undefined,
      workList: [{
        content: "",
        scale: "",
        unit: "",
        workload: "",
        deadline: undefined,
        remark: "",
      }],
      paymentList: [{
        paymentCondition: "",
        paymentPercentage: "",
        paymentAmount: "",
        paymentTime: undefined,
        remark: "",
      }],
      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: {},
    };
  },
  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.managerTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    else if (this.taskName == '总经理审核') {
      this.gmUser = this.$store.getters.name;
      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 => {
        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
            })
          }
          listContractWork({ contractId: this.taskForm.formId }).then(res => {
            if (res.rows)
              this.workList = res.rows;
          });
          listContractPayment({ contractId: this.taskForm.formId }).then(res => {
            if (res.rows)
              this.paymentList = res.rows;
          });
          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
                },
              ]
              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;
            }
          })
        }
      })
    },
    // 查询业主单位列表
    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) ? '院内' : '院外';
    },
    addWorkList() {
      this.workList.push({
        content: "",
        scale: "",
        unit: "",
        workload: "",
        deadline: undefined,
        remark: "",
      });
    },
    addPaymentList() {
      this.paymentList.push({
        paymentCondition: "",
        paymentPercentage: "",
        paymentAmount: "",
        paymentTime: undefined,
        remark: "",
      });
    },
    addCommentList() {
      this.commentList.push({
        deptId: "",
        userId: "",
        comment: "",
        document: "",
        commentTime: undefined,
      });
    },
    deletWorkItem(index) {
      let arr = this.workList;
      if (arr.length == 1) {
        return;
      }
      if (index >= 0 && index < arr.length) {
        arr.splice(index, 1);
      }
    },
    deletPaymentItem(index) {
      let arr = this.paymentList;
      if (arr.length == 1) {
        return;
      }
      if (index >= 0 && index < arr.length) {
        arr.splice(index, 1);
      }
    },
    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 || tenderId.trim() === '') {
        this.$message.error('请选择一个有效的投标项目');
        return false;
      }
      return true;
    },
    validateDocument(doc) {
      // 这里添加你的验证逻辑  
      // 例如，检查tenderId是否为空或者是否符合其他规则  
      if (!doc || doc.trim() === '') {
        this.$message.error('请上传合同文件');
        return false;
      }
      return true;
    },
    /** 提交按钮 */
    submitForm() {
      this.isTenderIdValid = this.validateTenderId(this.form.tenderId);
      this.isDocumentValid = this.validateDocument(this.form.contractDocument)
      if (!this.isTenderIdValid) {
        // tenderId无效，阻止提交  
        return;
      }
      if (!this.isDocumentValid) {
        return;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.formTotal != 0) {
            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 == '合同签订') {
                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("新增失败，请确认合同编码是否唯一");
              }
            });
          }
        }
      });
    },
    updateContractData() {
      updateContract(this.form).then(response => {
        this.$modal.msgSuccess("数据添加成功");
        this.open = false;
        delContractWork(this.form.contractId).then(res => {
          for (let work of this.workList) {
            work.contractId = this.form.contractId
            addContractWork(work);
          }
        })
        delContractPayment(this.form.contractId).then(res => {
          for (let payment of this.paymentList) {
            payment.contractId = this.form.contractId
            addContractPayment(payment);
          }
        })
      });
    },
    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
            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.$set(this.form, 'partyAId', val[0].partyAId)
      }
    },
    calculatePaymentAmount(payment) {
      let amount = (payment.paymentPercentage / 100) * this.form.amount
      this.$set(payment, 'paymentAmount', Number(amount))
    },
    reviewWord(url) {
      this.$router.push({
        path: '/preview',
        query: {
          url: url
        }
      })
    }
  }
}
</script>

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

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>