<!--
 * @Author: ysh
 * @Date: 2024-04-30 09:03:14
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-08-20 10:44:03
-->
<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">项目结算表</h2>
        <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">
                {{ chooseProject.contractCode }}
              </el-descriptions-item>
              <el-descriptions-item label="合同编号" label-class-name="my-label">
                {{ chooseProject.contractNumber }}
              </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 }}
                </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>
          <el-form-item label="经营发展部审核结算单" prop="">
            <FileUpload v-if="taskName == '经营发展部校核'" :limit="1" :filePathName="'项目结算/经营发展部审核结算单'"
              :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']" @input="setModifyDocument">
            </FileUpload>
            <div v-if="form.modifyDocument" class="upload-list">
              <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + form.modifyDocument}`)">
                {{ getFileName(form.modifyDocument) }}
              </el-link>
              <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + form.modifyDocument}`"
                :underline="false" target="_blank">
                <span class="el-icon-download">下载文件</span>
              </el-link>
            </div>
          </el-form-item>
          <el-form-item label="分管领导审核结算单" prop="">
            <FileUpload v-if="taskName == '分管审核'" :limit="1" :filePathName="'项目结算/分管领导审核结算单'"
              :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']" @input="setFinalDocument">
            </FileUpload>
            <div v-if="form.finalDocument" class="upload-list">
              <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + form.finalDocument}`)">
                {{ getFileName(form.finalDocument) }}
              </el-link>
              <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + form.finalDocument}`"
                :underline="false" target="_blank">
                <span class="el-icon-download">下载文件</span>
              </el-link>
            </div>
          </el-form-item>
          <div class="headers">
            预算内项目结算明细
            <div class="line"></div>
          </div>
          <el-form-item label-width="60px">
            <el-table :data="budgetList">
              <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%">
              <b>预算内项目结算总金额：{{ budgetSettle }}</b>
            </p>
          </el-form-item>
          <div class="headers">
            项目完成工作量及经费计算
            <div class="line"></div>
          </div>
          <el-form-item label-width="60px">
            <table border="1">
              <tr>
                <td style="width: 50px">序号</td>
                <td style="width: 180px">工作内容</td>
                <td style="width: 100px">等级或比例尺</td>
                <td style="width: 100px">单位</td>
                <td style="width: 100px">地类</td>
                <td style="width: 100px">单价</td>
                <td>工作量</td>
                <td style="width: 117px">其他系数</td>
                <td style="width: 100px">项目经费</td>
                <td>备注</td>
                <td>操作</td>
              </tr>
              <tr v-for="(work, index) in settleWorkList" :key="index">
                <td>
                  {{ index + 1 }}
                </td>
                <td>
              <tr>
                <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="2" 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> -->
                {{ work.settle }}
              </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="2" 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">
                <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 }} </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.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 }} </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="经营发展部(校核)">
              <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 }} </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 }} </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 }} </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 }} </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="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>
  </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 { deepClone } from "@/utils";
import { listSettle, getSettle, delSettle, addSettle, updateSettle } from "@/api/oa/settle/settle";
import { listSettleSummary, getSettleSummary, addSettleSummary, delSettleSummary, updateSettleSummary } from "@/api/oa/settle/settleSummary";
import { listSettleWork, getSettleWork, addSettleWork, updateSettleWork, delSettleWork } from "@/api/oa/settle/settleWork";
import { listProjectContract, addProjectContract } from "@/api/oa/contract/projectContract";
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 } from "@/api/flowable/todo";
import { getUsersDeptLeader, 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 { getDept } from "@/api/system/dept";
import { getContract } from "@/api/oa/contract/contract";
import ChooseProject from "./components/chooseProject.vue";
export default {
  components: {
    flow,
    ChoosePrice,
    SettlePrint,
    ChooseProject,
  },
  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,
      printOpen: false,
      loading: false,
      drawer: false,
      prOpen: false,
      flag: false,
      flowData: {},
      form: {},
      rules: {
        projectId: [
          { required: true, trigger: "change", message: "请选择项目编号" },
        ],
      },
      projectList: [],
      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, //是否可以修改结算工作量
    };
  },
  created() {
    this.getProjectList(); //获取项目列表
    this.getContractDataList(); //获取合同编码和编号
    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: {
    // 初始化表单
    async initForm() {
      this.loading = true
      const res = await listSettle({ settleId: this.taskForm.formId });
      if (res.total === 1) {
        this.form = res.rows[0];
        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: 30 }),
          listSettleSummary({ settleId })
        ]);

        if (projectResponse) {
          this.chooseProject = projectResponse.data;
          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"
          );
          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.form.reporterName = res.data.nickName;
            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.reporterName = this.$store.state.user.name;
          this.form.reportTime = parseTime(new Date(), "{y}-{m}-{d}");
        }
      }
      this.loading = false;
      this.deptList = this.$store.state.user.deptList
    },

    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.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}");
      }
      this.getReviewerName();
    },
    // 获取审核人
    getReviewerName() {
      if (this.form.zhUserId) {
        this.form.zhUserName = this.getUserName(this.form.zhUserId)
      }
      if (this.form.jsUserId) {
        this.form.jsUserName = this.getUserName(this.form.jsUserId)
      }
      if (this.form.jyUserId) {
        getUser(this.form.jyUserId).then((res) => {
          this.form.jyUserName = res.data.nickName;
        });
      }
      if (this.form.managerUserId) {
        getUser(this.form.managerUserId).then((res) => {
          this.form.managerUserName = res.data.nickName;
        });
      }
      if (this.form.gmUserId) {
        getUser(this.form.gmUserId).then((res) => {
          this.form.gmUserName = res.data.nickName;
        });
      }
    },
    // 保存按钮
    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(() => {
              getUserByRole({ roleId: 4 }).then((res) => {
                this.getNextFlowNodeFn(res.data[0]);
              });
            })
          } 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.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');
      })
    },
    // 查询项目列表
    getProjectList() {
      listProject({
        pageNum: 1,
        pageSize: 99999999,
      }).then((response) => {
        this.projectList = response.rows;
      });
    },
    // 选择项目
    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;
    },
    // 获取合同
    getContractDataList() {
      listProjectContract({ projectId: this.taskForm.formId }).then((res) => {
        if (res.rows) {
          for (let row of res.rows) {
            getContract(row.contractId).then((res) => {
              if (res.data) {
                if (this.form.contractCode != "") {
                  this.form.contractCode =
                    this.form.contractCode + "、" + res.data.contractCode;
                } else {
                  this.form.contractCode = res.data.contractCode;
                }
                if (this.form.contractNumber != "") {
                  this.form.contractNumber =
                    this.form.contractNumber + "、" + res.data.contractNumber;
                } else {
                  this.form.contractNumber = res.data.contractNumber;
                }
              }
            });
          }
        }
      });
    },
    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) {
      // let arr = this.settleWorkList;
      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) {
        this.$message.warning('不足600，按600算')
        work.remark = '不足600，按600算'
        sum = 600
      }
      else {
        work.remark = ''
      }
      work.settle = Number(sum).toFixed(2);
      this.calculateSumSettle();
      this.calculateActualSumSettle();
    },
    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);
          });
        }
      });
    },
    addSettleWorkFn(settleId) {
      for (let work of this.settleWorkList) {
        work.settleId = settleId;
        addSettleWork(work);
      }
    },
    addSettleSummaryFn(settleId) {
      this.settleSumTr.settleId = settleId;
      addSettleSummary(this.settleSumTr);
      for (let item of this.settleSumList) {
        item.settleId = settleId;
        addSettleSummary(item);
      }
      for (let item of this.deptSettleList) {
        item.settleId = settleId;
        addSettleSummary(item);
      }
    },

    // 更新数据
    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] = "";
        }
      }
    },
    confirmProject(val) {
      if (val.length == 1) {
        this.prOpen = false;
        this.chooseProject = val[0];
        this.$set(this.form, 'projectId', val[0].projectId)
        this.isSelect = true;
      } 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);
          // this.$notify({
          //   title: workType,
          //   dangerouslyUseHTMLString: true,
          //   message: res.msg,
          //   duration: 0
          // });
        }
      });
    },
  },
};
</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: 40px;

  .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;
}
</style>
