<!--
 * @Author: ysh
 * @Date: 2024-04-30 09:03:14
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-03-03 16:36:09
-->
<template>
  <div class="app-container" v-loading="loading">
    <el-row :gutter="20">
      <el-col :span="flowDisabled ? 19 : 24" :xs="24">
        <el-button type="success" icon="el-icon-printer" @click="printOpen = true">打印</el-button>
        <h2 class="text-center">项目结算表 <span style="color:#f56c6c" v-if="isAppend">（追加结算）</span> </h2>
        <div class="mt20 mb20" v-if="showAlter && flowDisabled">
          <el-alert title="任务被退回，请修改后重新提交" type="error" :closable="false">
            <return-comment :taskForm="taskForm" @isReturn="isReturn"></return-comment>
          </el-alert>
        </div>
        <div class="headers">
          项目信息
          <div class="line"></div>
        </div>
        <el-form ref="settleForm" :model="form" :rules="rules" label-width="160px" :disabled="disabled">
          <el-form-item label="项目编号" prop="projectId">
            <el-button icon="el-icon-plus" size="mini" type="primary" @click="prOpen = true"
              :disabled="taskName != '结算发起'">选择项目</el-button>
            <el-descriptions border v-if="isSelect" style="margin-top: 10px" :column="2">
              <el-descriptions-item label="项目编号" label-class-name="my-label">
                {{ chooseProject.projectNumber }}
              </el-descriptions-item>
              <el-descriptions-item label="项目名称" label-class-name="my-label">
                {{ chooseProject.projectName }}
              </el-descriptions-item>
              <el-descriptions-item label="项目负责人" label-class-name="my-label">
                {{ getUserName(chooseProject.projectLeader) }}
              </el-descriptions-item>
              <el-descriptions-item label="甲方单位" label-class-name="my-label">
                {{ chooseProject.partyA ? chooseProject.partyA.partyAName : '' }}
              </el-descriptions-item>
              <el-descriptions-item label="联系人" label-class-name="my-label">
                {{ chooseProject.contactPerson }}
              </el-descriptions-item>
              <el-descriptions-item label="联系电话" label-class-name="my-label">
                {{ chooseProject.telephone }}
              </el-descriptions-item>
              <el-descriptions-item label="项目类型" label-class-name="my-label">
                {{ chooseProject.projectType }}
              </el-descriptions-item>
              <el-descriptions-item label="项目级别" label-class-name="my-label">
                {{
                  chooseProject.projectLevel == "0" ? " 一般项目" : "重大项目"
                }}
              </el-descriptions-item>
              <el-descriptions-item label="承担部门" label-class-name="my-label">
                {{ chooseProject.undertakingDeptName }}
              </el-descriptions-item>
              <el-descriptions-item label="项目登记人" label-class-name="my-label">
                {{ chooseProject.projectRegistrantUser ? chooseProject.projectRegistrantUser.nickName : "" }}
              </el-descriptions-item>
            </el-descriptions>
          </el-form-item>
          <el-form-item label="工作量上报说明" prop="workloadReport">
            <el-input v-model="form.workloadReport" type="textarea" :rows="4" :disabled="taskName != '结算发起'"
              placeholder="请输入工作量上报说明" />
          </el-form-item>
          <el-row>
            <el-col :span="6" :xs="24" :offset="12">
              <el-form-item label="工作上报人：" prop="reporterName">
                <span class="auditor">
                  {{ form.reporterName ? "" : getUserName(form.reporter) }}
                </span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="上报日期：" prop="reportTime">
                <span> {{ form.reportTime }} </span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="附件上传" prop="">
            <FileUpload v-if="taskName == '结算发起'" :limit="1" :filePathName="'项目结算/原始数据'"
              :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']" @input="setSettleDocument">
            </FileUpload>
            <div v-if="form.settleDocument" class="upload-list">
              <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + form.settleDocument}`)">
                {{ getFileName(form.settleDocument) }}
              </el-link>
              <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + form.settleDocument}`"
                :underline="false" target="_blank">
                <span class="el-icon-download">下载文件</span>
              </el-link>
            </div>
          </el-form-item>

          <div class="headers" v-hasRole="['leader', 'business']">
            合同信息
            <div class="line"></div>
          </div>
          <project-contract-info :projectId="projectId" v-hasRole="['leader', 'business']"></project-contract-info>
          <div class="headers">
            预算内项目结算明细
            <div class="line"></div>
          </div>
          <el-form-item label-width="60px">
            <el-table :data="budgetList" v-if="budgetList.length > 0">
              <el-table-column prop="budgetSettleId" label="序号" />
              <el-table-column prop="content" label="工作内容" />
              <el-table-column label="具体内容" width="150px">
                <template slot-scope="scope">
                  {{ scope.row.cmcPrice.workType + '/' + scope.row.cmcPrice.workItem }}
                </template>
              </el-table-column>
              <el-table-column prop="cmcPrice.scaleGrade" label="等级或比例尺" />
              <el-table-column prop="cmcPrice.unit" label="单位" />
              <el-table-column prop="groundType" label="地类">
                <template slot-scope="scope">
                  {{ scope.row.groundType == '0' ? '一般地类' : '复杂地类' }}
                </template>
              </el-table-column>
              <el-table-column prop="cmcPrice" label="单价">
                <template slot-scope="scope">
                  {{ scope.row.groundType == '0' ? scope.row.cmcPrice.commonPrice : scope.row.cmcPrice.complexPrice }}
                </template>
              </el-table-column>
              <el-table-column prop="coefficient" label="系数" />
              <el-table-column prop="workload" label="工作量" />
              <el-table-column prop="settle" label="金额" />
              <el-table-column prop="remark" label="备注" />
            </el-table>
            <p style="text-align: right;font-size:18px;padding-right:13%" v-if="budgetList.length > 0">
              <b>预算内项目结算总金额：{{ budgetSettle }}</b>
            </p>
            <el-tag type="danger" v-else>
              未发起项目预算
            </el-tag>
          </el-form-item>
          <div class="headers">
            项目完成工作量及经费计算
            <div class="line"></div>
          </div>
          <div class="flex mb10" style="padding-left:80px;">
            <div style="flex:1">
              <el-link type="success" :href="`${baseUrl}${'/profile/upload/项目结算/cmc项目结算导入模板.xlsx'}`">
                结算工作量导入模板下载<i class="el-icon-download"></i>
              </el-link>
            </div>
            <div class="text-right" style="flex:1">
              <el-button size="mini" type="warning" icon="el-icon-upload2" @click="importOpen = true">一键导入</el-button>
            </div>
          </div>
          <el-form-item label-width="60px">
            <table border="1">
              <tr>
                <td style="width:50px;">序号</td>
                <td style="min-width:140px">工作内容</td>
                <td style="min-width:80px">等级或比例尺</td>
                <td style="min-width:80px">单位</td>
                <td style="min-width:80px">地类</td>
                <td style="min-width:80px">单价</td>
                <td>工作量</td>
                <td style="min-width:80px">其他系数</td>
                <td style="min-width:80px">项目经费</td>
                <td style="min-width:200px;">备注</td>
                <td>操作</td>
              </tr>
              <tr v-for="(work, index) in settleWorkList" :key="index">
                <td>
                  {{ index + 1 }}
                </td>
                <td>
              <tr v-if="taskName == '结算发起'">
                <td>
                  <el-button size="mini" type="primary" icon="el-icon-plus" :disabled="isModify"
                    @click="handleChoosePrice(work, index)">选择工作内容</el-button>
                </td>
              </tr>
              <tr>
                <td>
                  <el-input v-model="work.content" type="textarea" clearable :autosize="{ minRows: 4, maxRows: 10 }"
                    :disabled="isModify"></el-input>
                </td>
              </tr>
              </td>
              <td>
                {{ work.scale == "" ? "无" : work.scale }}
              </td>
              <td>
                {{ work.unit }}
              </td>
              <td>
                {{ work.groundType == "0" ? "一般地类" : "复杂地类" }}
              </td>
              <td>
                {{ work.price }}
              </td>
              <td>
                <el-input-number :precision="2" style="width: 100px" v-model="work.workload" clearable
                  :disabled="isModify" @blur="calculateSettle(work)" :controls="false"></el-input-number>
              </td>
              <td>
                <div style="display: flex">
                  <el-input-number :precision="3" style="width: 100px" v-model="work.coefficient" clearable
                    :disabled="isModify" @blur="calculateSettle(work)" :controls="false"></el-input-number>
                  <el-popover placement="top-start" title="系数备注" width="200" trigger="click">
                    <div v-html="work.noteTip"></div>
                    <i class="el-icon-info" slot="reference" @click="getCoefficientRemark(work, work.workType)"></i>
                  </el-popover>
                </div>
              </td>
              <td>
                <!-- <el-input-number style="width:100px" v-model="work.settle" clearable :controls="false"></el-input-number> -->
                <div>{{ work.settle }}</div>
                <div v-if="taskName == '结算发起'">
                  <el-button size="mini" type="text" v-if="Number(work.settle) <= 600 && Number(work.settle) != 0"
                    @click="setSettle(work)">置为600</el-button>
                  <el-button size="mini" type="text" v-if="Number(work.settle) <= 600 && Number(work.settle) != 0"
                    @click="resetSettle(work)">还原</el-button>
                </div>
              </td>
              <td>
                <el-input v-model="work.remark" type="textarea" clearable :disabled="isModify"
                  :autosize="{ minRows: 4, maxRows: 10 }"></el-input>
              </td>
              <td>
                <el-button type="text" size="mini" style="color: #f56c6c"
                  @click="deletWorkItem(index, settleWorkList)">删除行</el-button>
              </td>
              </tr>
              <tr>
                <td :colspan="8">结算费用合计</td>
                <td>{{ settleSumTr.amount }}</td>
                <td>
                  <el-input v-model="settleSumTr.remark" type="textarea" clearable :disabled="isModify"
                    :autosize="{ minRows: 2, maxRows: 10 }"></el-input>
                </td>
              </tr>
            </table>
            <el-button icon="el-icon-plus" type="primary" plain size="mini" @click="addWorkList"></el-button>
            <div v-if="exceed">
              <el-alert :title="'超过预算金额：' + exceedAmount" type="error">
              </el-alert>
            </div>
          </el-form-item>

          <!-- 结算汇总 -->
          <div class="headers">
            结算汇总
            <div class="line"></div>
          </div>
          <el-form-item label-width="60px">
            <h3>表1：扣除明细</h3>
            <table border="1">
              <tr>
                <td style="width: 50px">序号</td>
                <td style="width: 280px">扣除内容</td>
                <td style="width: 200px">扣除金额（元）</td>
                <td style="width: 280px">备注</td>
                <td style="width: 100px">操作</td>
              </tr>
              <tr v-for="(work, index) in settleSumList" :key="index">
                <td>
                  {{ index + 1 }}
                </td>
                <td>
                  <el-input v-model="work.content" type="textarea" clearable :autosize="{ minRows: 2, maxRows: 10 }"
                    :disabled="isModify">
                  </el-input>
                </td>
                <td>
                  <el-input-number :min="0" :precision="3" style="width: 200px" v-model="work.amount" clearable
                    :disabled="isModify" :controls="false" @blur="calculateActualSumSettle()"></el-input-number>
                  <!-- {{ work.amount }} -->
                </td>
                <td>
                  <el-input v-model="work.remark" type="textarea" clearable :autosize="{ minRows: 2, maxRows: 10 }"
                    :disabled="isModify">
                  </el-input>
                </td>
                <td>
                  <el-button type="text" size="mini" style="color: #f56c6c"
                    @click="deletWorkItem(index, settleSumList)">删除行</el-button>
                </td>
              </tr>
            </table>
            <el-button icon="el-icon-plus" type="primary" plain size="mini" @click="addSumWorkList"></el-button>
            <h3>表2：部门结算金额</h3>
            <table border="1">
              <tr>
                <td style="width: 150px">实际结算总金额（元）</td>
                <td style="width: 50px">序号</td>
                <td style="width: 280px">部门名称</td>
                <td style="width: 200px">结算金额（元）</td>
                <td style="width: 280px">备注</td>
                <td style="width: 100px">操作</td>
              </tr>
              <tr v-for="(dept, index) in deptSettleList" :key="index" v-if="dept.content != '实际结算总金额'">
                <td :rowspan="deptSettleList.length" v-if="index == 0">
                  {{ Number(actualSumSettle).toFixed(2) }}
                </td>
                <td>
                  {{ index + 1 }}
                </td>
                <td>
                  <!-- <el-input v-model="dept.content" type="textarea" clearable :autosize="{ minRows: 2, maxRows: 10 }">
                  </el-input> -->
                  <el-select v-model="dept.content" placeholder="请选择" filterable clearable style="width:100%;"
                    :disabled="isModify">
                    <el-option v-for="item in $store.state.user.deptList" :key="item.deptId" :label="item.deptName"
                      :value="item.deptName">
                    </el-option>
                  </el-select>
                </td>
                <td>
                  <el-input-number :precision="2" style="width: 200px" v-model="dept.amount" clearable :controls="false"
                    :disabled="isModify" @blur="calculateDeptAmount(index)"></el-input-number>
                </td>
                <td>
                  <el-input v-model="dept.remark" type="textarea" clearable :autosize="{ minRows: 2, maxRows: 10 }"
                    :disabled="isModify">
                  </el-input>
                </td>
                <td>
                  <el-button type="text" size="mini" style="color: #f56c6c"
                    @click="deletWorkItem(index, deptSettleList)">删除行</el-button>
                </td>
              </tr>
              <tr>
                <td :colspan="2">结算说明</td>
                <td :colspan="3">
                  <el-input v-model="form.settleComment" type="textarea" clearable placeholder="请输入说明"
                    :autosize="{ minRows: 2, maxRows: 10 }" :disabled="isModify">
                  </el-input>
                </td>
              </tr>
            </table>
            <el-button icon="el-icon-plus" type="primary" plain size="mini" @click="addDeptSettleList"></el-button>
          </el-form-item>

          <!-- 结算审核情况 -->
          <div v-if="taskName != '结算发起'">
            <div class="headers">
              结算审核情况
              <div class="line"></div>
            </div>
            <el-form-item label="综合事务部(设备领用情况)">
              <el-input v-model="form.zhComment" type="textarea" :disabled="taskName != '综合事务部处理'" clearable
                :autosize="{ minRows: 4, maxRows: 10 }">
              </el-input>
            </el-form-item>
            <el-row>
              <el-col :span="6" :xs="24" :offset="12">
                <el-form-item label="签名：" label-width="120px">
                  <span class="auditor"> {{ form.zhUserName ? form.zhUserName : getUserName(form.zhUserId) }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px">
                  <span> {{ form.zhTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="综合事务部(车辆排班情况)">
              <el-input v-model="form.jsbComment" type="textarea" :disabled="taskName != '综合事务部驾驶班处理'" clearable
                :autosize="{ minRows: 4, maxRows: 10 }">
              </el-input>
            </el-form-item>
            <el-row>
              <el-col :span="6" :xs="24" :offset="12">
                <el-form-item label="签名：" label-width="120px">
                  <span class="auditor"> {{ form.jsbUserName ? form.jsbUserName : getUserName(form.jsbUserId) }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px">
                  <span> {{ form.jsbTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="技术质量与安全部(质量及工作量)">
              <el-input v-model="form.jsComment" type="textarea" :disabled="taskName != '技术质量与安全部审核'" clearable
                :autosize="{ minRows: 4, maxRows: 10 }">
              </el-input>
            </el-form-item>
            <el-row>
              <el-col :span="6" :xs="24" :offset="12">
                <el-form-item label="签名：" label-width="120px">
                  <span class="auditor"> {{ form.jsUserName ? form.jsUserName : getUserName(form.jsUserId) }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px">
                  <span> {{ form.jsTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="经营发展部(校核)" prop="jyComment">
              <el-input v-model="form.jyComment" type="textarea" :disabled="taskName != '经营发展部校核'" clearable
                :autosize="{ minRows: 4, maxRows: 10 }">
              </el-input>
            </el-form-item>
            <el-row>
              <el-col :span="6" :xs="24" :offset="12">
                <el-form-item label="签名：" label-width="120px">
                  <span class="auditor"> {{ form.jyUserName ? form.jyUserName : getUserName(form.jyUserId) }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px">
                  <span> {{ form.jyTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="分管领导(审核)">
              <el-input v-model="form.managerComment" type="textarea" :disabled="taskName != '分管审核'" clearable
                :autosize="{ minRows: 4, maxRows: 10 }">
              </el-input>
            </el-form-item>
            <el-row>
              <el-col :span="6" :xs="24" :offset="12">
                <el-form-item label="签名：" label-width="120px">
                  <span class="auditor"> {{ form.managerUserName ? form.managerUserName :
                    getUserName(form.managerUserId) }}
                  </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px">
                  <span> {{ form.managerTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="总经理(审批)">
              <el-input v-model="form.gmComment" type="textarea" :disabled="taskName != '总经理审批'" clearable
                :autosize="{ minRows: 4, maxRows: 10 }">
              </el-input>
            </el-form-item>
            <el-row>
              <el-col :span="6" :xs="24" :offset="12">
                <el-form-item label="签名：" label-width="120px">
                  <span class="auditor"> {{ form.gmUserName ? form.gmUserName : getUserName(form.gmUserId) }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px">
                  <span> {{ form.gmTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="董事长（批准）" v-if="exceed">
              <el-input v-model="form.dszComment" type="textarea" :disabled="taskName != '董事长批准'" clearable
                :autosize="{ minRows: 4, maxRows: 10 }">
              </el-input>
            </el-form-item>
            <el-row v-if="exceed">
              <el-col :span="6" :xs="24" :offset="12">
                <el-form-item label="签名：" label-width="120px">
                  <span class="auditor"> {{ form.dszUserName ? form.dszUserName : getUserName(form.dszUserId) }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px">
                  <span> {{ form.dszTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
        <el-button type="success" icon="el-icon-printer" @click="printOpen = true">打印</el-button>
        <div style="text-align: center" v-if="!disabled">
          <el-button type="warning" @click="preserve">保存</el-button>
          <el-button type="danger" v-if="taskName != '结算发起'" @click="returnOpen = true">退 回</el-button>
          <el-button type="primary" @click="submitNextFlow" v-if="taskName != '董事长批准'">提 交</el-button>
          <el-button type="primary" @click="submitNextFlow" v-else>结算批准</el-button>
        </div>
      </el-col>
      <el-col :span="5" :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="printOpen" width="65%" append-to-body>
      <settle-print :form="form" :chooseProject="chooseProject" :workList="settleWorkList"
        :settleList="oldSettleSumList" @cancel="printOpen = false"></settle-print>
    </el-dialog>
    <el-drawer title="选择单价" :visible.sync="drawer" direction="rtl">
      <choose-price :row="clickWork" @getPrice="getPrice" @cancel="drawer = false"></choose-price>
    </el-drawer>

    <el-dialog title="选择项目" :visible.sync="prOpen" width="70%" append-to-body>
      <choose-project @chooseProject="confirmProject"></choose-project>
    </el-dialog>
    <el-dialog title="退回" :visible.sync="returnOpen" width="40%" append-to-body>
      <return-btn :taskForm="taskForm" :comment="commentByRole()" @goBack="$emit('goBack')" @saves=""
        @cancel="returnOpen = false"></return-btn>
    </el-dialog>

    <el-dialog title="导入结算工作量" :visible.sync="importOpen" width="400px" append-to-body>
      <settle-import @getDataList="getImportSettleList" @cancel="importOpen = false"></settle-import>
    </el-dialog>
  </div>
</template>

<script>
import flow from "@/views/flowable/task/todo/detail/flow";
import { flowXmlAndNode } from "@/api/flowable/definition";
import { parseTime } from "@/utils/ruoyi";
import { listProject, getProject } from "@/api/oa/project/project";
import { listSettle, getSettle, addSettle, updateSettle } from "@/api/oa/settle/settle";
import { listSettleSummary, addSettleSummary, delSettleSummary } from "@/api/oa/settle/settleSummary";
import { listSettleWork, addSettleWork, delSettleWork } from "@/api/oa/settle/settleWork";
import { getPrice, getPriceRemarkByWorkType } from "@/api/oa/price/price";
import ChoosePrice from "./components/choosePrice.vue";
import { getUser } from "@/api/system/user";
import { getUserByRole } from "@/api/system/role";
import { getUserByPost } from "@/api/system/post";
import { complete, getNextFlowNode, findReCommitTask, taskRecommit } from "@/api/flowable/todo";
import { getUsersDeptLeaderByDept, getUsersManageLeaderByDept, } from "@/api/system/post.js";
import { listBudget } from "@/api/oa/budget/budget";
import { listBudgetSettle } from "@/api/oa/budget/budgetSettle";
import SettlePrint from "./components/print/settlePrint.vue";
import ChooseProject from "./components/chooseProject.vue";
import projectContractInfo from "./projectContractInfo.vue";
import ReturnComment from '@/views/flowable/form/components/flowBtn/returnComment.vue';
import ReturnBtn from '@/views/flowable/form/components/flowBtn/returnBtn.vue';
import SettleImport from "./settleImport.vue";
export default {
  components: {
    flow,
    ChoosePrice,
    SettlePrint,
    ChooseProject,
    projectContractInfo,
    ReturnComment,
    ReturnBtn,
    SettleImport
  },
  props: {
    taskName: {
      type: String,
      required: true,
    },
    taskForm: {
      type: Object,
      required: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    flowDisabled: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    'chooseProject.projectId'(val) {
      this.getBudgetSettle();
    },
    'taskForm.formId'() {
      this.initForm();
    }
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      isAppend: false,//是否追加结算
      printOpen: false,
      loading: false,
      drawer: false,
      prOpen: false,
      flag: false,
      flowData: {},
      form: {},
      rules: {
        projectId: [
          { required: true, trigger: "change", message: "请选择项目编号" },
        ],
      },
      isSelect: false,
      chooseProject: {},
      fileList: [],
      budgetList: [],
      budgetSettle: 0,
      settleWorkList: [
        {
          content: "",
          priceId: "",
          scale: "无",
          unit: "",
          groundType: "0",
          price: "",
          workload: 0,
          coefficient: 1,
          settle: 0,
          remark: "",
        },
      ],
      oldSettleWorkList: [],
      settleSumTr: {
        content: "结算费用合计",
        amount: 0,
        remark: "",
        tableNumber: "2",
      },
      settleSumList: [
        {
          content: "",
          amount: 0,
          remark: "",
          tableNumber: "0",
        },
      ],
      deptSettleList: [
        {
          content: "",
          amount: 0,
          remark: "",
          tableNumber: "1",
        },
      ],
      oldSettleSumList: [],
      actualSumSettle: "",
      clickWork: {},
      deptId: undefined,
      deptList: [],
      exceed: false, //是否超预算
      exceedAmount: 0,
      isModify: false, //是否可以修改结算工作量
      projectId: '',
      showAlter: true,
      returnOpen: false,
      importOpen: false,
    };
  },
  created() {
    this.initRules();
    this.initForm();
    if (this.flowDisabled)
      flowXmlAndNode({
        procInsId: this.taskForm.procInsId,
        deployId: this.taskForm.deployId,
      }).then((res) => {
        this.flowData = res.data;
      });
  },
  mounted() {
    if (this.$route.query.projectId) {
      getProject(this.$route.query.projectId).then((res) => {
        if (res.data) {
          this.$set(this.form, "projectId", res.data.projectId);
          this.handleSelectProject(res.data.projectId);
        }
      });
    } else {
      this.handleSelectProject(this.form.projectId);
    }
    this.isModify = this.taskName != '结算发起' && this.taskName != '经营发展部校核' && this.taskName != '分管审核'
  },
  methods: {
    initRules() {
      if (this.taskName == '经营发展部校核') {

      } else if (this.taskName == '经营发展部校核') {
        this.rules = {
          jyComment: [
            { required: true, message: '请输入意见', trigger: 'blur' }
          ]
        }
      }
    },
    // 初始化表单
    async initForm() {
      this.loading = true
      const res = await listSettle({ settleId: this.taskForm.formId });
      if (res.total === 1) {
        this.form = res.rows[0];
        this.isAppend = await this.getIsAppend(this.taskForm.formId, res.rows[0].projectId) //判断是否为追加结算
        this.flag = true;
        const settleId = this.taskForm.formId;
        const [
          projectResponse,
          budgetResponse,
          settleWorkResponse,
          settleSummaryResponse
        ] = await Promise.all([
          getProject(res.rows[0].projectId),
          listBudget({ projectId: res.rows[0].projectId }),
          listSettleWork({ settleId: settleId, pageSize: 50 }),
          listSettleSummary({ settleId, pageSize: 50 })
        ]);

        if (projectResponse) {
          this.chooseProject = projectResponse.data;
          this.projectId = projectResponse.data.projectId
          this.isSelect = true;
        }
        if (budgetResponse && budgetResponse.total === 1) {
          const budgetId = budgetResponse.rows[0].budgetId;
          const budgetSettleResponse = await listBudgetSettle({ budgetId });
          if (budgetSettleResponse.code === 200) {
            this.budgetList = budgetSettleResponse.rows;
            this.budgetSettle = budgetResponse.rows[0].settleExpense;
          } else {
            this.budgetList = [];
            this.budgetSettle = 0;
          }
        } else {
          this.budgetList = [];
          this.budgetSettle = 0;
        }
        // 获取申请工作量列表
        if (settleWorkResponse) {
          this.settleWorkList = settleWorkResponse.rows;
          for (let work of this.settleWorkList) {
            if (work.priceId)
              getPrice(work.priceId).then((settleWorkResponse) => {
                if (settleWorkResponse.data) {
                  this.setValue(work, "scale", settleWorkResponse.data.scaleGrade);
                  this.setValue(work, "unit", settleWorkResponse.data.unit);
                  if (work.groundType == "0") {
                    work.price = settleWorkResponse.data.commonPrice;
                  } else {
                    work.price = settleWorkResponse.data.complexPrice;
                  }
                }
              });
          }
        }
        // 结算汇总里的扣除明细以及部门结算金额
        if (settleSummaryResponse) {
          this.oldSettleSumList = settleSummaryResponse.rows;
          for (let s of settleSummaryResponse.rows) {
            if (s.content == "结算费用合计") {
              this.settleSumTr = s;
              break;
            }
          }
          this.settleSumList = settleSummaryResponse.rows.filter((item) => item.tableNumber == "0");
          this.deptSettleList = settleSummaryResponse.rows.filter(
            (item) => item.tableNumber == "1" && item.content != '实际结算总金额'
          );
          this.calculateActualSumSettle();
        }
        if (this.settleSumTr.amount > this.budgetSettle) {
          this.exceed = true
        } else {
          this.exceed = false
        }
        this.calcaulatExceed()

        getUser(this.form.reporter).then((res) => {
          if (res.data) {
            this.deptId = res.data.deptId;
          }
        });
        this.getCurrentUser();
      } else if (res.total == 0) {
        this.flag = false;
        if (this.taskName == "结算发起") {
          this.form.reporter = this.$store.state.user.id;
          this.form.reportTime = parseTime(new Date(), "{y}-{m}-{d}");
        }
      }
      this.loading = false;
      this.deptList = this.$store.state.user.deptList
    },
    async getIsAppend(settleId, projectId) {
      let res = await listSettle({ projectId });
      if (res.total > 1) {
        let arr = res.rows
        const target = arr.find(item => item.settleId === settleId);
        const parseTime = (timeStr) => Date.parse(timeStr);
        const allTimestamps = arr.map(item => parseTime(item.reportTime));
        const minTimestamp = Math.min(...allTimestamps);
        const targetTimestamp = parseTime(target.reportTime);
        const isAppend = targetTimestamp !== minTimestamp;
        return isAppend
      } else {
        return false
      }
    },
    async getBudgetSettle() {
      let budgetData = await listBudget({ projectId: this.form.projectId })
      if (budgetData.total == 1) {
        let budgetId = budgetData.rows[0].budgetId;
        let datas = await listBudgetSettle({ budgetId })
        if (datas.code == 200) {
          this.budgetList = datas.rows;
          this.budgetSettle = budgetData.rows[0].settleExpense
        }
      } else {
        this.budgetList = []
        this.budgetSettle = 0
      }
    },
    // 获取当前处理人
    getCurrentUser() {
      if (this.taskName == "综合事务部处理") {
        this.form.zhUserName = this.$store.state.user.name;
        this.form.zhUserId = this.$store.state.user.id;
        this.form.zhTime = parseTime(new Date(), "{y}-{m}-{d}");
      }
      else if (this.taskName == "综合事务部驾驶班处理") {
        this.form.jsbUserName = this.$store.state.user.name;
        this.form.jsbUserId = this.$store.state.user.id;
        this.form.jsbTime = parseTime(new Date(), "{y}-{m}-{d}");
      }
      else if (this.taskName == "技术质量与安全部审核") {
        this.form.jsUserName = this.$store.state.user.name;
        this.form.jsUserId = this.$store.state.user.id;
        this.form.jsTime = parseTime(new Date(), "{y}-{m}-{d}");
      } else if (this.taskName == "经营发展部校核") {
        this.form.jyUserName = this.$store.state.user.name;
        this.form.jyUserId = this.$store.state.user.id;
        this.form.jyTime = parseTime(new Date(), "{y}-{m}-{d}");
      } else if (this.taskName == "分管审核") {
        this.form.managerUserName = this.$store.state.user.name;
        this.form.managerUserId = this.$store.state.user.id;
        this.form.managerTime = parseTime(new Date(), "{y}-{m}-{d}");
      } else if (this.taskName == "总经理审批") {
        this.form.gmUserName = this.$store.state.user.name;
        this.form.gmUserId = this.$store.state.user.id;
        this.form.gmTime = parseTime(new Date(), "{y}-{m}-{d}");
      } else if (this.taskName == "董事长批准") {
        this.form.dszUserName = this.$store.state.user.name;
        this.form.dszUserId = this.$store.state.user.id;
        this.form.dszTime = parseTime(new Date(), "{y}-{m}-{d}");
      }
    },
    // 保存按钮
    preserve() {
      this.$refs["settleForm"].validate((vaild) => {
        if (vaild) {
          if (this.flag) {
            this.updateSettleFn();
            this.updateSettleSummaryFn();
            this.updateSettleWorkFn();
            this.$message.success("保存成功");
          } else {
            this.addSettleFn();
            this.$message.success("保存成功");
          }
        } else {
          this.$message.error('请完善表单必填项')
        }
      });
    },
    submitNextFlow() {
      this.$refs["settleForm"].validate((vaild) => {
        if (vaild) {
          this.preserve();
          if (this.taskName == "结算发起") {
            this.$confirm('结算合计总金额大于了预算内项目结算总金额，将走《超预算或预算外支付（报销）》流程', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            }).then(() => {
              if (this.showAlter) {
                const taskId = this.taskForm.taskId
                findReCommitTask(this.taskForm).then(res => {
                  taskRecommit({ taskId, targetKey: res.data[0].id, comment: '' }).then(res1 => {
                    if (res1.code == 200) {
                      this.$message.success('操作成功')
                      this.$emit('goBack');
                    }
                  })
                })
              } else {
                getUserByRole({ roleId: 4 }).then((res) => {
                  this.getNextFlowNodeFn(res.data[0]);
                });
              }

            })
          } else if (this.taskName == "综合事务部处理") {
            getUserByRole({ roleId: 5 }).then((res) => {
              this.getNextFlowNodeFn(res.data[1]);
            });
          } else if (this.taskName == "综合事务部驾驶班处理") {
            this.getNextFlowNodeFn(null, 109, false);
          }
          else if (this.taskName == "技术质量与安全部审核") {
            this.getNextFlowNodeFn(null, 105, true);
          } else if (this.taskName == "经营发展部校核") {
            this.getNextFlowNodeFn(null, this.deptId, true);
          } else if (this.taskName == "分管审核") {
            getUserByPost({ postName: "总经理" }).then((res) => {
              this.getNextFlowNodeFn(res.data[0].userId);
            });
          } else if (this.taskName == "总经理审批") {
            this.$set(this.taskForm.variables, "exceed", this.exceed);
            if (this.exceed) {
              getUserByPost({ postName: "董事长" }).then((res) => {
                this.getNextFlowNodeFn(res.data[0].userId);
              });
            } else {
              this.getNextFlowNodeFn();
            }
          } else if (this.taskName == "董事长批准") {
            this.$modal.confirm('最后一个节点，提交将结束流程，是否提交？').then(() => {
              this.getNextFlowNodeFn();
            })
          }
        } else {
          this.$message.error('请完善表单必填项')
        }
      });
    },
    // 获取下一个节点  (下一个用户id,部门id,是否为会签)
    getNextFlowNodeFn(userId, deptId, isList) {
      const params = { taskId: this.taskForm.taskId };
      getNextFlowNode(params).then((res) => {
        if (userId) {
          this.$set(this.taskForm.variables, "approval", userId);
          this.handleComplete(this.taskForm);
        } else {
          if (deptId && isList) {
            getUsersManageLeaderByDept({ deptId }).then((res) => {
              let ids = [];
              res.data.forEach(user => {
                ids.push(user.userId)
              })
              this.$set(this.taskForm.variables, "approvalList", ids);
              this.handleComplete(this.taskForm);
            });
          } else if (deptId && !isList) {
            getUsersDeptLeaderByDept({ deptId }).then((res) => {
              this.$set(this.taskForm.variables, "approval", res.data.userId);
              this.handleComplete(this.taskForm);
            });
          } else {
            this.handleComplete(this.taskForm);
          }
        }
      });
    },
    handleComplete(taskForm) {
      complete(taskForm).then(response => {
        this.$modal.msgSuccess(response.msg);
        this.$emit('goBack');
      })
    },
    // 选择项目
    handleSelectProject(val) {
      if (val != "" && val != undefined && val != null) {
        getProject(val).then((res) => {
          this.chooseProject = res.data;
          this.isSelect = true;
          this.getBudgetSettle();
          getUser(this.chooseProject.projectRegistrant).then((res) => {
            if (res.data) {
              this.$set(
                this.chooseProject,
                "projectRegistrantName",
                res.data.nickName
              );
            }
          });
        });
      } else {
        this.isSelect = false;
      }
    },
    isEmptyObject(obj) {
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          return false;
        }
      }
      return true;
    },
    addWorkList() {
      this.settleWorkList.push({
        content: "",
        priceId: "",
        scale: "",
        unit: "",
        groundType: "0",
        price: "",
        workload: 0,
        coefficient: 1,
        settle: 0,
        remark: "",
      });
    },
    addSumWorkList() {
      this.settleSumList.push({
        content: "",
        amount: 0,
        remark: "",
        tableNumber: "0",
      });
    },
    addDeptSettleList() {
      this.deptSettleList.push({
        content: "",
        amount: 0,
        remark: "",
        tableNumber: "1",
      });
    },
    deletWorkItem(index, arr) {
      if (arr.length == 1) {
        return;
      }
      if (index >= 0 && index < arr.length) {
        arr.splice(index, 1);
      }
      this.calculateSumSettle();
      this.calculateActualSumSettle();
    },
    calculateSettle(work) {
      let sum = work.workload * work.coefficient * work.price;
      // if (sum < 600 && sum != 0 && work.priceId != 147) {
      //   this.$message.warning('不足600，按600算')
      //   work.remark = '不足600，按600算'
      //   sum = 600
      // }
      work.settle = Number(sum).toFixed(2);
      this.calculateSumSettle();
      this.calculateActualSumSettle();
    },
    // 置为600
    setSettle(work) {
      work.settle = 600;
      work.remark = '不足600，按600算';
      this.calculateSumSettle();
      this.calculateActualSumSettle();
    },
    resetSettle(work) {
      work.remark = '';
      this.calculateSettle(work)
    },
    calculateSumSettle() {
      let sum = 0;
      let arr = this.settleWorkList;
      for (let a of arr) {
        sum = sum + Number(a.settle);
      }
      this.settleSumTr.amount = sum.toFixed(2);
      if (sum > this.budgetSettle) {
        this.exceed = true;
        this.calcaulatExceed();

      } else {
        this.exceed = false;
      }
    },
    calculateActualSumSettle() {
      let sum = 0;
      let arr = this.settleSumList;
      for (let a of arr) {
        sum = sum + Number(a.amount);
      }
      this.actualSumSettle = Number(this.settleSumTr.amount) - sum;
      if (this.deptSettleList.length == 1)
        this.deptSettleList[0].amount = this.actualSumSettle;
    },
    calculateDeptAmount(index) {
      let num = 0;
      let len = this.deptSettleList.length;
      if (len > 1) {
        if (index == len - 1) {
          for (let i = 0; i < index; i++) {
            num = num + this.deptSettleList[i].amount;
          }
          this.deptSettleList[index].amount = this.actualSumSettle - num;
        }
      }
    },
    calcaulatExceed() {
      if (Number(this.budgetSettle) - Number(this.settleSumTr.amount) < 0)
        this.exceedAmount = Number(this.settleSumTr.amount) - Number(this.budgetSettle)
    },
    handleChoosePrice(work, index) {
      this.clickWork = work;
      this.clickWork.index = index;
      this.drawer = true;
    },
    getPrice(val) {
      let index = this.clickWork.index;
      this.setValue(this.settleWorkList[index], "workType", val.workType);
      this.setValue(this.settleWorkList[index], "scale", val.scaleGrade);
      this.setValue(this.settleWorkList[index], "unit", val.unit);
      this.setValue(this.settleWorkList[index], "groundType", val.groundType);
      this.setValue(this.settleWorkList[index], "price", val.price);
      this.setValue(this.settleWorkList[index], "priceId", val.priceId);
      this.setValue(this.settleWorkList[index], "content", val.content);
      this.calculateSettle(this.settleWorkList[index]);
      this.drawer = false;
    },
    setValue(key, name, val) {
      this.$set(key, name, val);
    },

    // 增加数据
    addSettleFn() {
      let settleId = this.taskForm.formId;
      this.form.settleId = settleId;
      getSettle(this.taskForm.formId).then((res) => {
        if (res.data) {
          updateSettle(this.form);
          this.updateSettleWorkFn(settleId);
          this.updateSettleSummaryFn(settleId);
        } else {
          addSettle(this.form).then((res) => {
            this.addSettleWorkFn(settleId);
            this.addSettleSummaryFn(settleId);
          });
        }
      });
    },
    async addSettleWorkFn(settleId) {
      for (let work of this.settleWorkList) {
        work.settleId = settleId;
        await addSettleWork(work);
      }
    },
    async addSettleSummaryFn(settleId) {
      this.settleSumTr.settleId = settleId;
      await addSettleSummary(this.settleSumTr);
      for (let item of this.settleSumList) {
        item.settleId = settleId;
        await addSettleSummary(item);
      }
      for (let item of this.deptSettleList) {
        item.settleId = settleId;
        await addSettleSummary(item);
      }
      let obj = { settleId: settleId, content: '实际结算总金额', amount: (this.actualSumSettle).toFixed(2), tableNumber: 1 }
      await addSettleSummary(obj)
    },

    // 更新数据
    updateSettleFn() {
      updateSettle(this.form);
    },
    updateSettleWorkFn() {
      delSettleWork([this.taskForm.formId]).then((res) => {
        this.addSettleWorkFn(this.taskForm.formId);
      });
    },
    updateSettleSummaryFn() {
      delSettleSummary([this.taskForm.formId]).then((res) => {
        this.addSettleSummaryFn(this.taskForm.formId);
      });
    },
    getFileName(name) {
      if (name) {
        let arr = name.split("/");
        return arr[arr.length - 1];
      }
    },
    setSettleDocument(val) {
      this.getDoc(val, "settleDocument");
    },
    setModifyDocument(val) {
      this.getDoc(val, "modifyDocument");
    },
    setFinalDocument(val) {
      this.getDoc(val, "finalDocument");
    },
    getDoc(val, name) {
      if (val) {
        let arr = val.split("/upload");
        this.form[name] = arr[1];
        if (val == "") {
          this.form[name] = "";
        }
      }
    },
    async confirmProject(val) {
      if (val.length == 1) {
        this.prOpen = false;
        this.chooseProject = val[0];
        let settleData = await listSettle({ projectId: val[0].projectId });
        if (settleData.total >= 1) {
          this.$modal.confirm('该项目已经发起过项目结算，是否追加结算？').then(() => {
            this.$set(this.form, 'projectId', val[0].projectId)
            this.isSelect = true;
            this.isAppend = true;
          })
        } else {
          this.$set(this.form, 'projectId', val[0].projectId)
          this.isSelect = true;
          this.isAppend = false;
        }
      } else {
        this.$message.error("项目只能选择一个！");
        return;
      }
    },
    // 获取系数备注
    getCoefficientRemark(work, workType) {
      getPriceRemarkByWorkType({ workType }).then((res) => {
        if (res.code == 200) {
          if (workType != undefined) this.$set(work, "noteTip", res.msg);
        }
      });
    },
    isReturn(val) {
      this.showAlter = val
    },
    commentByRole() {
      if (this.taskName == '经营发展部校核') {
        return this.form.jyComment
      } else if (this.taskName == '分管审核') {
        return this.form.managerComment
      } else if (this.taskName == '总经理审批') {
        return this.form.gmComment
      } else if (this.taskName == '董事长批准') {
        return this.form.dszComment
      }
    },
    getImportSettleList(val) {
      this.settleWorkList = val;
      for (let work of this.settleWorkList) {
        this.calculateSettle(work)
      }
      this.importOpen = false;
    }
  },
};
</script>

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

.headers {
  position: relative;
  font-weight: bold;
  font-size: 18px;
  padding-left: 40px;
  padding-bottom: 20px;

  .line {
    position: absolute;
    left: 22px;
    top: 5px;
    width: 5px;
    height: 14px;
    border-radius: 10px;
    background-color: #2893e5;
  }
}

table {
  /*边框*/
  /* border: 1px solid black; */
  text-align: center;
  border-collapse: collapse;
  width: 100%;
  /*设置背景颜色*/
  /* background-color: #bfa; */
}

h3 {
  font-family: "黑体";
  font-weight: bold;
}

::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>
