<!--
 * @Author: ysh
 * @Date: 2025-05-07 11:01:39
 * @LastEditors: wrh
 * @LastEditTime: 2026-02-02 11:09:36
-->
<template>
  <div class="main">
    <h2 class="text-center">项目直接生产成本预算—核算表</h2>
    <p style="text-align: center">
      编制人：{{ budgetForm.compilerUser ? budgetForm.compilerUser.nickName : '' }}
      <span style="margin-left: 20px;">核算人：{{ checkForm.checker ? getUserName(checkForm.checker) : '' }}</span>
    </p>
    <div class="mt20 mb20" v-if="showAlter && taskName">
      <el-alert title="任务被退回，请修改后重新提交" type="error" :closable="false">
        <return-comment :taskForm="taskForm" @isReturn="isReturn"></return-comment>
      </el-alert>
    </div>
    <el-divider></el-divider>
    <el-descriptions :column="3" border class="descriptions" v-loading="loading" :element-loading-text="loadingText">
      <el-descriptions-item label="项目编号">
        {{ project.projectNumber }}
      </el-descriptions-item>
      <el-descriptions-item label="项目名称">
        {{ project.projectName }}
      </el-descriptions-item>
      <el-descriptions-item label="项目负责人">
        {{ getUserName(project.projectLeader) }}
      </el-descriptions-item>
      <el-descriptions-item label="承担部门">
        {{ getDeptNames(project.undertakingDept) }}
      </el-descriptions-item>
      <el-descriptions-item label="项目备注" :span="3">
        {{ project.remark }}
      </el-descriptions-item>
      <el-descriptions-item label="编制时间" :span="1">
        {{ budgetForm.createTime }}
      </el-descriptions-item>
      <el-descriptions-item label="预算表单备注" :span="3">
        {{ budgetForm.remark }}
      </el-descriptions-item>
      <el-descriptions-item label="预算附件" :span="3" v-if="budgetForm.document">
        <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + budgetForm.document}`)">
          {{ getFileName(budgetForm.document) }}
        </el-link>
        <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + budgetForm.document}`"
          :underline="false" target="_blank">
          <span class="el-icon-download">下载文件</span>
        </el-link>
      </el-descriptions-item>
      <el-descriptions-item label="项目计划工作量" :span="3">
        <div>
          <table border="1" style="width: 100%;">
            <tr style="background-color:#f8f8f9">
              <td style="width: 250px">工作内容</td>
              <td style="width: 100px">比例尺/等级</td>
              <td style="width: 100px">单位</td>
              <td style="width: 100px">工作量</td>
              <td style="width: 100px">要求完成时间</td>
              <td style="width: 200px">备注</td>
            </tr>
            <tr v-for="(work, index) in workContentList" :key="index">
              <td>{{ work.content }}</td>
              <td>{{ work.scale }}</td>
              <td>{{ work.unit }}</td>
              <td>{{ work.workload }}</td>
              <td>{{ work.deadline }}</td>
              <td style="text-align:left;">{{ work.remark }}</td>
            </tr>
          </table>
        </div>
      </el-descriptions-item>
      <el-descriptions-item label="内业绩效额" :span="3">
        <table border="1" style="width:100%">
          <tr style="background-color:#f8f8f9" v-if="workList.length != 0">
            <td style="min-width:50px">工作简述</td>
            <td style="min-width:50px">工作内容</td>
            <td style="min-width:50px">内容细项</td>
            <td style="min-width:50px">比例尺/等级</td>
            <td style="min-width:50px">数量</td>
            <td style="min-width:50px">单价</td>
            <td style="min-width:50px">单位</td>
            <td style="min-width:50px">系数</td>
            <td style="min-width:80px">金额</td>
            <td style="min-width: 150px;">备注</td>
          </tr>
          <tr v-for="work in workList">
            <td>{{ work.content }}</td>
            <td>{{ work.workItem }}</td>
            <td>{{ work.subItem }}</td>
            <td>
              {{ work.scaleGrade }}
            </td>
            <td>
              {{ work.workload }}
            </td>
            <td>{{ work.price }}</td>
            <td>{{ work.unit }}</td>
            <td>
              {{ work.coefficient }}
            </td>
            <td style="text-align:right;">{{ work.settle ? work.settle.toFixed(2) : '0.00' }}</td>
            <td>{{ work.remark ? work.remark : '' }}</td>
          </tr>
          <tr>
            <td :colspan="8" class="head">内业绩效额合计</td>
            <td :colspan="1" class="head" style="text-align:right;">
              {{ budgetForm.settleExpense ? budgetForm.settleExpense.toFixed(2) : '0.00' }}
            </td>
            <td></td>
          </tr>
          <tr style="color:#F56C6C">
            <td :colspan="8" class="head">内业核算绩效额</td>
            <td :colspan="1" class="head" v-if="taskName == '核算编制'">
              <el-input-number v-model="budgetForm.settleAdjust" :controls="false" style="width:100%"></el-input-number>
            </td>
            <td style="text-align:right;font-weight:bold;" :colspan="1" class="head" v-else>
              {{ budgetForm.settleAdjust ? budgetForm.settleAdjust.toFixed(2) : '0.00' }}
            </td>
          </tr>
        </table>
      </el-descriptions-item>
      <el-descriptions-item label="实际参与人员" :span="3" v-if="taskName == '核算编制'">
        <span v-for="participant in actualInfo.participateList" :key="participant">
          <el-tag type="primary" effect="plain" style="margin-right: 10px;">{{ participant }}</el-tag>
        </span>
      </el-descriptions-item>
      <el-descriptions-item label="内业人员成本" :span="3" v-if="taskName == '核算编制' || innerStaffList.length > 0">
        <inner-staff-cost :staffList.sync="innerStaffList" :settleExpense="budgetForm.settleExpense"
          :settleAdjust="budgetForm.settleAdjust" :taskName="taskName"
          @update:staffList="handleInnerStaffChange"></inner-staff-cost>
      </el-descriptions-item>
      <el-descriptions-item label="外业人员成本" :span="3" v-if="taskName == '核算编制' || outerStaffList.length > 0">
        <outer-staff-cost :staffList.sync="outerStaffList" :taskName="taskName"
          @update:staffList="handleOuterStaffChange"></outer-staff-cost>
      </el-descriptions-item>
      <el-descriptions-item label="实际使用车辆" :span="3" v-if="taskName == '核算编制'">
        <span v-for="car in actualInfo.carList" :key="car.id">
          <el-tag :type="car.isExist ? 'primary' : 'warning'" effect="plain" style="margin-right: 10px;">{{
            car.licensePlate }} - {{ car.series }}</el-tag>
        </span>
      </el-descriptions-item>
      <el-descriptions-item label="车辆成本" :span="3" v-if="taskName == '核算编制' || carList.length > 0">
        <car-cost :carList.sync="carList" :taskName="taskName" @update:carList="handleCarChange"></car-cost>
      </el-descriptions-item>
      <el-descriptions-item label="实际使用设备" :span="3" v-if="taskName == '核算编制'">
        <span v-for="device in actualInfo.deviceList" :key="device.id">
          <el-tag :type="device.isExist ? 'primary' : 'warning'" style="margin-right: 10px;margin-bottom: 10px;"
            effect="plain">
            {{ device.name + '【' + (device.brand != null ? device.brand : '') + (device.series != null ? '-' +
              device.series + '】' : '')
              + (device.code != null ? '（出厂编号：' + device.code + '）' : '') }}
          </el-tag>
        </span>
      </el-descriptions-item>
      <el-descriptions-item label="设备成本" :span="3" v-if="taskName == '核算编制' || deviceList.length > 0">
        <device-cost :deviceList.sync="deviceList" :taskName="taskName"
          @update:deviceList="handleDeviceChange"></device-cost>
      </el-descriptions-item>
      <el-descriptions-item label="现场开支" :span="3">
        <site-cost :siteList.sync="siteList" :taskName="taskName" @update:siteList="handleSiteChange"
          @updateList="updateSiteList"></site-cost>
      </el-descriptions-item>
      <el-descriptions-item label="合同总价" :span="3" v-hasRole="['leader', 'finance', 'nfinance', 'admin']">
        <table border="1" style="width:100%;" v-if="contractList.length > 0">
          <tr style="background-color:#f8f8f9">
            <td>序号</td>
            <td>合同名称</td>
            <td>合同总价</td>
          </tr>
          <tr v-for="contract, index in contractList" :key="contract.contractId">
            <td>{{ index + 1 }}</td>
            <td>{{ contract.contractName }}</td>
            <td>{{ contract.amount }}</td>
          </tr>
        </table>
        <div v-else>
          <div class="alert alert-warning">
            暂无合同信息
          </div>
        </div>
      </el-descriptions-item>
      <el-descriptions-item label="分包合同总价" :span="3" v-hasRole="['leader', 'finance', 'nfinance', 'admin']">
        <table border="1" style="width:100%;" v-if="subContractList.length > 0">
          <tr style="background-color:#f8f8f9">
            <td>序号</td>
            <td>分包合同名称</td>
            <td>分包合同总价</td>
          </tr>
          <tr v-for="subContract, index in subContractList" :key="subContract.subContractId">
            <td>{{ index + 1 }}</td>
            <td>{{ subContract.subContractName }}</td>
            <td>{{ subContract.subAmount }}</td>
          </tr>
        </table>
        <div v-else>
          <div class="alert alert-warning">
            暂无分包合同信息
          </div>
        </div>
      </el-descriptions-item>
      <el-descriptions-item label="经营相关" :span="3">
        <business-cost :budgetForm.sync="budgetForm" :taskName="taskName"
          @update:budgetForm="handleBusinessChange"></business-cost>
      </el-descriptions-item>
      <el-descriptions-item label="现场外开销" :span="3">
        <other-cost :otherList.sync="otherList" :taskName="taskName" @update:otherList="handleOtherChange"></other-cost>
      </el-descriptions-item>
      <el-descriptions-item label="统计" :span="3">
        <table border="1" style="width:100%;" class="budget-summary">
          <tr class="header" style="background-color:#f8f8f9">
            <td><b>名称</b></td>
            <td><b>预算金额</b></td>
            <td><b>核算金额</b></td>
            <td><b>（核算-预算）差值</b></td>
          </tr>
          <tr>
            <td>人员成本</td>
            <td style="text-align:right;">{{ isNaN(budgetForm.staffCost) ? 0 : Number(budgetForm.staffCost).toFixed(2)
              }}
            </td>
            <td style="text-align:right;">{{ isNaN(checkStaffCost) ? 0 : Number(checkStaffCost).toFixed(2) }}</td>
            <td style="text-align:right;">{{ (Number(checkStaffCost) - Number(budgetForm.staffCost)).toFixed(2) }}</td>
          </tr>
          <tr>
            <td>车辆成本</td>
            <td style="text-align:right;">{{ isNaN(budgetForm.carCost) ? 0 : Number(budgetForm.carCost).toFixed(2) }}
            </td>
            <td style="text-align:right;">{{ isNaN(checkCarCost) ? 0 : Number(checkCarCost).toFixed(2) }}</td>
            <td style="text-align:right;">{{ (Number(checkCarCost) - Number(budgetForm.carCost)).toFixed(2) }}</td>
          </tr>
          <tr>
            <td>设备成本</td>
            <td style="text-align:right;">{{ isNaN(budgetForm.deviceCost) ? 0 : Number(budgetForm.deviceCost).toFixed(2)
            }}</td>
            <td style="text-align:right;">{{ isNaN(checkDeviceCost) ? 0 : Number(checkDeviceCost).toFixed(2) }}</td>
            <td style="text-align:right;">{{ (Number(checkDeviceCost) - Number(budgetForm.deviceCost)).toFixed(2) }}
            </td>
          </tr>
          <tr>
            <td>现场开支成本</td>
            <td style="text-align:right;">{{ isNaN(budgetForm.siteCost) ? 0 : Number(budgetForm.siteCost).toFixed(2) }}
            </td>
            <td style="text-align:right;">{{ isNaN(checkSiteCost) ? 0 : Number(checkSiteCost).toFixed(2) }}</td>
            <td style="text-align:right;">{{ (Number(checkSiteCost) - Number(budgetForm.siteCost)).toFixed(2) }}</td>
          </tr>
          <tr>
            <td>经营相关成本</td>
            <td style="text-align:right;">{{ isNaN(totalJYAmount) ? 0 : Number(totalJYAmount).toFixed(2) }}</td>
            <td style="text-align:right;">{{ isNaN(checkJYAmount) ? 0 : Number(checkJYAmount).toFixed(2) }}</td>
            <td style="text-align:right;">{{ (Number(checkJYAmount) - Number(totalJYAmount)).toFixed(2) }}</td>
          </tr>
          <tr>
            <td>现场外开销</td>
            <td style="text-align:right;">0.00</td>
            <td style="text-align:right;">{{ isNaN(checkOtherCost) ? 0 : Number(checkOtherCost).toFixed(2) }}</td>
            <td style="text-align:right;">{{ (Number(checkOtherCost) - 0).toFixed(2) }}</td>
          </tr>
          <tr class="total-budget" style="background-color: #ffeb3b; font-weight: bold;">
            <td><b>总计</b></td>
            <td style="text-align:right;"><b>{{ isNaN(budgetForm.totalBudget) ? 0 : budgetForm.totalBudget }}</b></td>
            <td style="text-align:right;"><b>{{ isNaN(totalBudgetAdjust) ? 0 : totalBudgetAdjust }}</b></td>
            <td style="text-align:right;"><b>{{ (Number(totalBudgetAdjust) - Number(budgetForm.totalBudget)).toFixed(2)
                }}</b></td>
          </tr>
        </table>
      </el-descriptions-item>
      <el-descriptions-item label="核算说明" :span="3">
        <div v-if="taskName == '核算编制' && !checkForm.checkComment" class="alert alert-warning"
          style="padding: 10px; border: 1px solid #f0ad4e; background-color: #fcf8e3; color: #8a6d3b;">
          请填写以下内容
        </div>
        <el-input :class="{ 'business-section': taskName == '核算编制' }" type="textarea" :autosize="{ minRows: 4 }"
          v-model="checkForm.checkComment" :disabled="taskName != '核算编制'" />
        <div class="sign mt10" v-if="checkForm.checkComment">
          <div class="mr20">签名：<span class="auditor">{{ getUserName(checkForm.checker) }}</span>
          </div>
          <div class="ml20"><span>核算时间：{{ checkForm.checkTime }}</span></div>
        </div>
      </el-descriptions-item>
      <el-descriptions-item label="财务审核意见" :span="3">
        <div v-if="taskName == '财务审核' && !checkForm.cwComment" class="alert alert-warning"
          style="padding: 10px; border: 1px solid #f0ad4e; background-color: #fcf8e3; color: #8a6d3b;">
          请填写以下内容
        </div>
        <el-input :class="{ 'business-section': taskName == '财务审核' }" type="textarea" :autosize="{ minRows: 4 }"
          v-model="checkForm.cwComment" :disabled="taskName != '财务审核'" />
        <div class="sign mt10" v-if="checkForm.cwComment">
          <div class="mr20">签名：<span class="auditor">{{ getUserName(checkForm.cwUserId) }}</span>
          </div>
          <div class="ml20"><span>审核时间：{{ checkForm.cwTime }}</span></div>
        </div>
      </el-descriptions-item>
      <el-descriptions-item label="分管审核意见" :span="3">
        <table border="1" style="width:100%; text-align:left;">
          <tr style="background-color:#f8f8f9;">
            <td style="width:50%;">预算分管审核意见</td>
            <td style="width:50%;">核算分管审核意见</td>
          </tr>
          <tr>
            <td>
              <el-input type="textarea" :autosize="{ minRows: 4 }" v-model="budgetForm.managerComment" disabled />
              <div class="sign mt10" v-if="budgetForm.manager">
                <div class="mr20">签名：<span class="auditor">{{ getUserName(budgetForm.manager) }}</span></div>
                <div class="ml20"><span>审核时间：{{ budgetForm.managerTime }}</span></div>
              </div>
            </td>
            <td>
              <el-input type="textarea" :autosize="{ minRows: 4 }" v-model="checkForm.managerComment"
                :disabled="taskName != '分管审核'" />
              <div class="sign mt10" v-if="checkForm.managerUserId">
                <div class="mr20">签名：<span class="auditor">{{ getUserName(checkForm.managerUserId) }}</span></div>
                <div class="ml20"><span>审核时间：{{ checkForm.managerTime }}</span></div>
              </div>
            </td>
          </tr>
        </table>
      </el-descriptions-item>
      <el-descriptions-item label="总经理审批意见" :span="3">
        <table border="1" style="width:100%; text-align:left;">
          <tr style="background-color:#f8f8f9;">
            <td style="width:50%;">预算总经理审核意见</td>
            <td style="width:50%;">核算总经理审核意见</td>
          </tr>
          <tr>
            <td>
              <el-input type="textarea" :autosize="{ minRows: 4 }" v-model="budgetForm.zjlComment" disabled />
              <div class="sign mt10" v-if="budgetForm.zjlComment">
                <div class="mr20">签名：<span class="auditor">{{ getUserName(budgetForm.auditor) }}</span>
                </div>
                <div class="ml20"><span>审核时间：{{ budgetForm.zjlTime }}</span></div>
              </div>
            </td>
            <td>
              <el-input type="textarea" :autosize="{ minRows: 4 }" v-model="checkForm.zjlComment"
                :disabled="taskName != '总经理审核'" />
              <div class="sign mt10" v-if="checkForm.zjlComment">
                <div class="mr20">签名：<span class="auditor">{{ getUserName(checkForm.zjlUserId) }}</span>
                </div>
                <div class="ml20"><span>审核时间：{{ checkForm.zjlTime }}</span></div>
              </div>
            </td>
          </tr>
        </table>
      </el-descriptions-item>
    </el-descriptions>
    <div class="text-center mt20 mb20" v-if="taskName">
      <el-button type="danger" @click="returnOpen = true">退 回</el-button>
      <el-button type="warning" @click="preserve()">保 存</el-button>
      <el-button type="success" @click="confirmSucess()">{{ taskName == '总经理审核' ? '结束流程' : '提交下一个流程' }}</el-button>
    </div>
    <el-dialog title="退回" :visible.sync="returnOpen" width="40%" append-to-body>
      <return-btn :taskForm="taskForm" :comment="commentByRole()" @goBack="$emit('goBack')"
        @cancel="returnOpen = false"></return-btn>
    </el-dialog>
  </div>
</template>

<script>
import { getCheck, addCheck, updateCheck } from "@/api/oa/budget/check";
import { listBudget, updateBudget } from "@/api/oa/budget/budget";
import { listBudgetCar, addBudgetCar, delBudgetCar } from "@/api/oa/budget/budgetCar";
import { listBudgetDevice, addBudgetDevice, delBudgetDevice } from "@/api/oa/budget/budgetDevice";
import { listBudgetSettle } from "@/api/oa/budget/budgetSettle";
import { listBudgetStaff, addBudgetStaff, delBudgetStaff } from "@/api/oa/budget/budgetStaff";
import { listOther, addOther, delOther } from "@/api/oa/budget/budgetOther";
import { listProjectWork } from "@/api/oa/project/projectWork";
import { listSite, updateSite } from "@/api/oa/budget/budgetSite";
import { getProject } from "@/api/oa/project/project";
import { getCar } from "@/api/oa/car/car";
import { getDevice } from "@/api/oa/device/device";
import { complete, getNextFlowNode } from "@/api/flowable/todo";
import { getUsersManageLeader, getUserByPost, getUsersViceDeptLeaderByDept } from "@/api/system/post";
import { listProjectContract } from "@/api/oa/contract/projectContract";
import { listProjectSubcontract } from "@/api/oa/contract/projectSubcontract";
import { getContract } from "@/api/oa/contract/contract";
import { currentNodeByFormId } from "@/api/flowable/definition";
import { getSubContract } from "@/api/oa/contract/subContract";
import InnerStaffCost from './components/InnerStaffCost.vue';
import OuterStaffCost from './components/OuterStaffCost.vue';
import CarCost from './components/CarCost.vue';
import DeviceCost from './components/DeviceCost.vue';
import SiteCost from '@/views/flowable/form/budget/adjust/components/SiteCost.vue';
import BusinessCost from '@/views/flowable/form/budget/adjust/components/businessCost.vue';
import OtherCost from '@/views/flowable/form/budget/adjust/components/otherCost.vue';
import ReturnComment from '@/views/flowable/form/components/flowBtn/returnComment.vue';
import ReturnBtn from '@/views/flowable/form/components/flowBtn/returnBtn.vue';
export default {
  components: {
    InnerStaffCost,
    OuterStaffCost,
    CarCost,
    DeviceCost,
    SiteCost,
    BusinessCost,
    OtherCost,
    ReturnComment,
    ReturnBtn
  },
  props: {
    taskForm: {
      type: Object,
      require: true
    },
    taskName: {
      type: String,
    },
    row: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  watch: {
    'taskForm.budgetId'() {
      getCheck(this.taskForm.formId).then(res => {
        this.row.projectId = res.data.projectId;
        this.row.budgetId = res.data.budgetId;
        this.initBudgetForm();
        this.initCheckForm();
        this.getContractInfo();
        this.getSubContractInfo();
      });

    }
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      loading: true,
      budgetForm: {},
      checkForm: {},
      project: {},
      workContentList: [],
      workList: [],
      innerStaffList: [],
      outerStaffList: [],
      carList: [],
      deviceList: [],
      siteList: [],
      otherList: [],
      returnOpen: false,
      showAlter: true,
      totalJYAmount: 0,
      checkStaffCost: 0,
      checkCarCost: 0,
      checkDeviceCost: 0,
      checkSiteCost: 0,
      checkOtherCost: 0,
      checkJYAmount: 0,
      totalBudgetAdjust: 0,
      actualInfo: {
        deviceList: [],
        carList: [],
        participateList: []
      },
      contractList: [],
      subContractList: [],
      budgetId: '',
      loadingText: '加载中...'
    }
  },
  async created() {
    if (!this.row.projectId) {
      let res = await getCheck(this.taskForm.formId);
      this.row.projectId = res.data.projectId;
      this.row.budgetId = res.data.budgetId;
    }
    this.initBudgetForm();
    this.initCheckForm();
    this.getContractInfo();
    this.getSubContractInfo();
  },
  methods: {
    initBudgetForm() {
      this.loading = true;
      listBudget({ pageNum: 1, pageSize: 20, projectId: this.row.projectId, budgetId: this.row.budgetId }).then(async res => {
        this.budgetForm = res.rows[0];
        if (this.budgetForm) {
          const budgetId = this.budgetForm.budgetId;
          this.budgetId = budgetId;

          // 并发获取所有数据
          const [
            deviceRes,
            carRes,
            innerStaffRes,
            outerStaffRes,
            settleRes,
            siteRes,
            otherRes
          ] = await Promise.all([
            listBudgetDevice({ pageSize: 100, budgetId }),
            listBudgetCar({ pageSize: 100, budgetId }),
            listBudgetStaff({ pageSize: 100, budgetId, type: '内业' }),
            listBudgetStaff({ pageSize: 100, budgetId, type: '外业' }),
            listBudgetSettle({ pageSize: 100, budgetId }),
            listSite({ pageSize: 100, budgetId }),
            listOther({ pageSize: 100, budgetId })
          ]);

          // 经营相关数据处理
          this.budgetForm.outExpense = Number(this.budgetForm.outExpense).toFixed(2);
          this.budgetForm.letterExpense = Number(this.budgetForm.letterExpense).toFixed(2);
          this.budgetForm.winExpense = Number(this.budgetForm.winExpense).toFixed(2);
          this.budgetForm.taxExpense = Number(this.budgetForm.taxExpense).toFixed(2);
          this.budgetForm.travelExpense = Number(this.budgetForm.travelExpense).toFixed(2);
          this.budgetForm.totalBudget = Number(this.budgetForm.totalBudget).toFixed(2);
          this.totalJYAmount = Number(this.budgetForm.outExpense || 0) +
            Number(this.budgetForm.letterExpense || 0) +
            Number(this.budgetForm.winExpense || 0) +
            Number(this.budgetForm.taxExpense || 0) +
            Number(this.budgetForm.travelExpense || 0);

          this.budgetForm.outAdjust = Number(this.budgetForm.outAdjust).toFixed(2);
          this.budgetForm.letterAdjust = Number(this.budgetForm.letterAdjust).toFixed(2);
          this.budgetForm.winAdjust = Number(this.budgetForm.winAdjust).toFixed(2);
          this.budgetForm.taxAdjust = Number(this.budgetForm.taxAdjust).toFixed(2);
          this.budgetForm.travelAdjust = Number(this.budgetForm.travelAdjust).toFixed(2);
          this.checkJYAmount = Number(this.budgetForm.outAdjust || 0) +
            Number(this.budgetForm.letterAdjust || 0) +
            Number(this.budgetForm.winAdjust || 0) +
            Number(this.budgetForm.taxAdjust || 0) +
            Number(this.budgetForm.travelAdjust || 0);

          // 处理设备数据
          this.deviceList = deviceRes.rows.map(device => ({
            ...device,
            depreciation: Number(device.depreciation).toFixed(2),
            amount: Number(device.amount).toFixed(2),
            amountAdjust: device.amountAdjust ? Number(device.amountAdjust).toFixed(2) : 0
          }));
          this.checkDeviceCost = this.deviceList.reduce((sum, device) => sum + Number(device.amountAdjust || 0), 0).toFixed(2);

          // 处理车辆数据
          this.carList = carRes.rows.map(car => ({
            ...car,
            depreciation: Number(car.depreciation).toFixed(2),
            amount: Number(car.amount).toFixed(2),
            amountAdjust: car.amountAdjust ? Number(car.amountAdjust).toFixed(2) : 0
          }));
          this.checkCarCost = this.carList.reduce((sum, car) => sum + Number(car.amountAdjust || 0), 0).toFixed(2);

          // 处理内业人员数据
          this.innerStaffList = innerStaffRes.rows.map(staff => ({
            ...staff,
            dayCost: Number(staff.dayCost).toFixed(2),
            performance: Number(staff.performance).toFixed(2),
            amount: Number(staff.amount).toFixed(2),
            staffCost: Number(staff.staffCost).toFixed(2),
            daysAdjust: staff.daysAdjust ? Number(staff.daysAdjust).toFixed(2) : 0,
            performanceAdjust: staff.performanceAdjust ? Number(staff.performanceAdjust).toFixed(2) : 0,
            amountAdjust: staff.amountAdjust ? Number(staff.amountAdjust).toFixed(2) : 0
          }));
          let innerCheckCost = this.innerStaffList.reduce((sum, staff) => sum + Number(staff.amountAdjust || 0), 0);

          // 处理外业人员数据
          this.outerStaffList = outerStaffRes.rows.map(staff => ({
            ...staff,
            dayCost: Number(staff.dayCost).toFixed(2),
            performance: Number(staff.performance).toFixed(2),
            amount: Number(staff.amount).toFixed(2),
            staffCost: Number(staff.staffCost).toFixed(2),
            daysAdjust: staff.daysAdjust ? Number(staff.daysAdjust).toFixed(2) : 0,
            performanceAdjust: staff.performanceAdjust ? Number(staff.performanceAdjust).toFixed(2) : 0,
            amountAdjust: staff.amountAdjust ? Number(staff.amountAdjust).toFixed(2) : 0
          }));
          let outerCheckCost = this.outerStaffList.reduce((sum, staff) => sum + Number(staff.amountAdjust || 0), 0);
          this.checkStaffCost = (innerCheckCost + outerCheckCost).toFixed(2);

          // 处理内业绩效额数据
          this.workList = settleRes.rows;
          for (let work of this.workList) {
            if (work.checkPriceId) {
              work.workType = work.cmcCheckPrice.workType
              work.workItem = work.cmcCheckPrice.workItem
              work.subItem = work.cmcCheckPrice.subItem
              work.scaleGrade = work.cmcCheckPrice.scaleGrade
              work.unit = work.cmcCheckPrice.unit
              if (work.groundType == '0') {
                work.price = work.cmcCheckPrice.commonPrice
              } else {
                work.price = work.cmcCheckPrice.complexPrice
              }
            } else {
              work.workType = work.cmcPrice.workType
              work.workItem = work.cmcPrice.workItem
              work.subItem = work.cmcPrice.subItem
              work.scaleGrade = work.cmcPrice.scaleGrade
              work.unit = work.cmcPrice.unit
              if (work.groundType == '0') {
                work.price = work.cmcPrice.commonPrice
              } else {
                work.price = work.cmcPrice.complexPrice
              }
            }
          }

          // 处理现场开支
          this.siteList = siteRes.rows.map(site => ({
            ...site,
            amount: Number(site.amount).toFixed(2),
            amountAdjust: site.amountAdjust ? Number(site.amountAdjust).toFixed(2) : 0
          }));
          this.budgetForm.siteCost = this.siteList.reduce((sum, site) => sum + Number(site.amount || 0), 0).toFixed(2);
          this.checkSiteCost = this.siteList.reduce((sum, site) => sum + Number(site.amountAdjust || 0), 0).toFixed(2);

          // 处理预算外开销
          this.otherList = otherRes.rows.map(other => ({
            ...other,
            amount: Number(other.amount).toFixed(2),
            amountAdjust: other.amountAdjust ? Number(other.amountAdjust).toFixed(2) : 0
          }));
          this.checkOtherCost = this.otherList.reduce((sum, other) => sum + Number(other.amountAdjust || 0), 0).toFixed(2);
          this.totalBudgetAdjust = (Number(this.checkStaffCost) + Number(this.checkCarCost) + Number(this.checkDeviceCost)
            + Number(this.checkSiteCost) + Number(this.checkJYAmount) + Number(this.checkOtherCost)).toFixed(2);

          this.getProjectWorkList();
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    initCheckForm() {
      getCheck(this.taskForm.formId).then(res => {
        if (res.data) {
          this.checkForm = res.data;
          this.getCurrentTaskName(this.checkForm.projectId).then(response => {
            if (response != '预算批准' || response == '') {
              this.$set(this.checkForm, 'checkComment', '新版预算暂未获批准，当前节点：' + response);
            }
          })
        }
        if (this.taskName == '核算编制') {
          this.checkForm.checker = this.$store.getters.userId;
          this.checkForm.checkTime = this.parseTime(new Date(), '{y}-{m}-{d}');
        } else if (this.taskName == '财务审核') {
          this.checkForm.cwUserId = this.$store.getters.userId;
          this.checkForm.cwTime = this.parseTime(new Date(), '{y}-{m}-{d}');
        } else if (this.taskName == '分管审核') {
          this.checkForm.managerUserId = this.$store.getters.userId;
          this.checkForm.managerTime = this.parseTime(new Date(), '{y}-{m}-{d}');
        } else if (this.taskName == '总经理审核') {
          this.checkForm.zjlUserId = this.$store.getters.userId;
          this.checkForm.zjlTime = this.parseTime(new Date(), '{y}-{m}-{d}');
        }
      })
    },
    // 获取合同信息
    getContractInfo() {
      listProjectContract({ projectId: this.row.projectId }).then(res => {
        let contractIds = res.rows;
        this.contractList = [];
        for (let contractId of contractIds) {
          getContract(contractId.contractId).then(response => {
            this.contractList.push(response.data);
          })
        }
      })
    },
    getSubContractInfo() {
      listProjectSubcontract({ projectId: this.row.projectId }).then(res => {
        let subContractIds = res.rows;
        this.subContractList = [];
        for (let subContract of subContractIds) {
          getSubContract(subContract.subContractId).then(response => {
            this.subContractList.push(response.data);
          })
        }
      })
    },
    async getCurrentTaskName(projectId) {
      let resData = await currentNodeByFormId({ formId: projectId, name: '3045' })
      if (resData.code == 200) {
        return resData.msg;
      }
      else
        return ''
    },
    async initActualInfo(project) {
      let deviceIds = [];
      let carIds = [];
      let participateIds = [];
      if (project.devices) {
        deviceIds = project.devices.split(',');
      }
      if (project.cars) {
        carIds = project.cars.split(',');
      }
      if (project.participates) {
        participateIds = project.participates.split(',');
      }
      let actualDeviceList = [];
      let actualCarList = [];
      let actualParticipateList = [];
      actualDeviceList = await Promise.all(deviceIds.map(async deviceId => {
        const res = await getDevice(deviceId);
        return res.data;
      }));

      actualCarList = await Promise.all(carIds.map(async carId => {
        const res = await getCar(carId);
        return res.data;
      }));

      actualParticipateList = participateIds.map(participateId => this.getUserName(Number(participateId)));
      actualDeviceList = actualDeviceList.map(actualDevice => {
        const isExist = this.deviceList.some(device => device.deviceId === actualDevice.deviceId);
        return {
          ...actualDevice,
          isExist: isExist
        };
      });
      actualCarList = actualCarList.map(actualCar => {
        const isExist = this.carList.some(car => car.carId === actualCar.carId);
        return {
          ...actualCar,
          isExist: isExist
        };
      });
      this.actualInfo = {
        deviceList: actualDeviceList,
        carList: actualCarList,
        participateList: actualParticipateList
      }
    },
    getProjectWorkList() {
      getProject(this.row.projectId).then(res => {
        this.project = res.data;
        this.initActualInfo(this.project);
      })
      listProjectWork({ pageSize: 999, projectId: this.row.projectId }).then(res => {
        this.workContentList = res.rows;
      })
    },
    // 处理内业人员数据变化
    handleInnerStaffChange(newList) {
      this.innerStaffList = newList;
      let innerSum = this.innerStaffList.reduce((sum, staff) => sum + (Number(staff.amountAdjust) || 0), 0)
      let outerSum = this.outerStaffList.reduce((sum, staff) => sum + (Number(staff.amountAdjust) || 0), 0)
      this.checkStaffCost = (innerSum + outerSum).toFixed(2);
      // 计算人员核算成本
      this.budgetForm.staffAdjust = this.checkStaffCost;
      this.getTotalBudgetAdjust();
    },

    // 处理外业人员数据变化
    handleOuterStaffChange(newList) {
      this.outerStaffList = newList;
      let innerSum = this.innerStaffList.reduce((sum, staff) => sum + (Number(staff.amountAdjust) || 0), 0)
      let outerSum = this.outerStaffList.reduce((sum, staff) => sum + (Number(staff.amountAdjust) || 0), 0)
      this.checkStaffCost = (innerSum + outerSum).toFixed(2);
      // 计算人员核算成本
      this.budgetForm.staffAdjust = this.checkStaffCost;
      this.getTotalBudgetAdjust();
    },
    // 处理车辆数据变化
    handleCarChange(newList) {
      this.carList = newList;
      this.checkCarCost = this.carList.reduce((sum, car) => sum + (Number(car.amountAdjust) || 0), 0).toFixed(2);
      // 计算车辆核算成本
      this.budgetForm.carAdjust = this.checkCarCost;
      this.getTotalBudgetAdjust();
    },
    // 处理设备数据变化
    handleDeviceChange(newList) {
      this.deviceList = newList;
      this.checkDeviceCost = this.deviceList.reduce((sum, device) => sum + (Number(device.amountAdjust) || 0), 0).toFixed(2);
      // 计算设备核算成本
      this.budgetForm.deviceAdjust = this.checkDeviceCost;
      this.getTotalBudgetAdjust();
    },
    // 处理现场开支数据变化
    handleSiteChange(newList) {
      this.siteList = newList;
      this.checkSiteCost = this.siteList.reduce((sum, site) => sum + (Number(site.amountAdjust) || 0), 0).toFixed(2);
      this.budgetForm.siteAdjust = this.checkSiteCost
      this.getTotalBudgetAdjust();
    },
    async updateSiteList() {
      // 获取现场开支
      let siteRes = await listSite({ pageSize: 100, budgetId: this.budgetId });
      this.siteList = siteRes.rows.map(site => ({
        ...site,
        amount: Number(site.amount).toFixed(2),
        amountAdjust: site.amountAdjust ? Number(site.amountAdjust).toFixed(2) : 0
      }));

      this.budgetForm.siteCost = this.siteList.reduce((sum, site) => sum + Number(site.amount || 0), 0).toFixed(2);
      this.checkSiteCost = this.siteList.reduce((sum, site) => sum + Number(site.amountAdjust || 0), 0).toFixed(2);
      this.budgetForm.siteAdjust = this.checkSiteCost
    },
    // 处理经营相关数据变化
    handleBusinessChange(newData) {
      this.budgetForm.outAdjust = newData.outAdjust;
      this.budgetForm.letterAdjust = newData.letterAdjust;
      this.budgetForm.winAdjust = newData.winAdjust;
      this.budgetForm.taxAdjust = newData.taxAdjust;
      this.budgetForm.travelAdjust = newData.travelAdjust;
      this.checkJYAmount = Number(newData.outAdjust || 0) +
        Number(newData.letterAdjust || 0) +
        Number(newData.winAdjust || 0) +
        Number(newData.taxAdjust || 0) +
        Number(newData.travelAdjust || 0);
      // 计算经营相关核算成本
      this.budgetForm.businessAdjust = this.checkJYAmount;
      this.getTotalBudgetAdjust();
    },
    // 处理预算外开销数据变化
    handleOtherChange(newList) {
      this.otherList = newList;
      this.checkOtherCost = this.otherList.reduce((sum, other) => sum + (Number(other.amountAdjust) || 0), 0).toFixed(2);
      this.budgetForm.otherCost = this.checkOtherCost
      this.getTotalBudgetAdjust();
    },
    getTotalBudgetAdjust() {
      this.totalBudgetAdjust = (Number(this.checkStaffCost) +
        Number(this.checkCarCost) +
        Number(this.checkDeviceCost) +
        Number(this.checkSiteCost) +
        Number(this.checkJYAmount) +
        Number(this.checkOtherCost)).toFixed(2);
    },
    // 保存
    async preserve() {
      this.loading = true;
      this.loadingText = '保存中...';
      this.$message.warning('保存中...');
      try {
        let obj = {
          budgetId: this.row.budgetId,
          projectId: this.row.projectId,
          checkId: this.taskForm.formId
        }

        // 并发处理基础数据保存
        const savePromises = [];
        this.checkForm.totalAdjust = this.totalBudgetAdjust
        if (!this.checkForm.checkId) {
          savePromises.push(addCheck(obj));
          this.$emit('preserve');
        } else {
          savePromises.push(updateCheck(this.checkForm));
        }
        savePromises.push(updateBudget(this.budgetForm));

        if (this.taskName == '核算编制') {
          // 并发处理所有删除操作
          const deletePromises = [
            delBudgetStaff(this.row.budgetId),
            delBudgetCar(this.row.budgetId),
            delBudgetDevice(this.row.budgetId),
            delOther(this.row.budgetId)
          ];

          await Promise.all(deletePromises);

          // 并发处理所有新增操作
          const addPromises = [];

          // 人员数据（保持顺序）
          const staffList = this.innerStaffList.concat(this.outerStaffList);
          staffList.forEach(staff => {
            staff.budgetId = this.row.budgetId;
            addPromises.push(addBudgetStaff(staff));
          });

          // 车辆数据（保持顺序）
          this.carList.forEach(car => {
            car.budgetId = this.row.budgetId;
            addPromises.push(addBudgetCar(car));
          });

          // 设备数据（保持顺序）
          this.deviceList.forEach(device => {
            device.budgetId = this.row.budgetId;
            addPromises.push(addBudgetDevice(device));
          });

          // 预算外开销数据（保持顺序）
          this.otherList.forEach(other => {
            other.budgetId = this.row.budgetId;
            addPromises.push(addOther(other));
          });

          // 现场开支更新（保持顺序）
          this.siteList.forEach(site => {
            addPromises.push(updateSite(site));
          });

          // 并发执行所有新增操作
          await Promise.all(addPromises);
        }

        // 等待基础数据保存完成
        await Promise.all(savePromises);

        this.$message.success('保存成功');
      } catch (error) {
        console.error('保存失败:', error);
        this.$message.error('保存失败，请重试');
      } finally {
        this.loading = false;
        this.loadingText = '加载中...';
      }
    },
    confirmSucess() {
      this.preserve();
      let msg = this.taskName == '总经理审核' ? '是否结束流程？' : '是否提交到下一个流程？';
      this.$modal.confirm(msg).then(async () => {
        if (this.taskName == '核算编制') {
          let cwRes = await getUsersViceDeptLeaderByDept({ deptId: 106 });
          let cwUserId = cwRes.data.userId;
          this.$set(this.taskForm.variables, 'approvalList', [cwUserId]);
        } else if (this.taskName == '财务审核') {
          let managerLeaderRes = await getUsersManageLeader({ userId: this.budgetForm.compiler });
          let managerLeader = managerLeaderRes.data;
          let managerList = managerLeader.map(item => item.userId);
          this.$set(this.taskForm.variables, 'approvalList', managerList);
        } else if (this.taskName == '分管审核') {
          let zjlRes = await getUserByPost({ postName: '总经理' });
          let zjlUserId = zjlRes.data[0].userId;
          this.$set(this.taskForm.variables, 'approval', zjlUserId);
        }
        // 提交到下一个流程
        getNextFlowNode({ taskId: this.taskForm.taskId }).then(res => {
          complete(this.taskForm).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.$emit("goBack");
          });
        })
      })
    },
    commentByRole() {
      if (this.taskName == '核算编制') {
        return this.checkForm.checkComment
      } else if (this.taskName == '财务审核') {
        return this.checkForm.cwComment
      } else if (this.taskName == '分管审核') {
        return this.checkForm.managerComment
      } else if (this.taskName == '总经理审核') {
        return this.checkForm.zjlComment
      }
    },
    isReturn(val) {
      this.showAlter = val;
    },
  },
}
</script>

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

.mylabel {
  font-weight: bold;
}

.main {
  width: 90%;
  margin: 0 auto;
  text-align: center;
}

.descriptions {
  width: 100%;
  margin: 0 auto;
}

table {
  text-align: center;
  border-collapse: collapse;
  margin: 0 auto;

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

.sign {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding-right: 80px;
  line-height: 30px;
  /* 如果需要垂直居中 */
}

.adjust {
  color: #F56C6C;
  width: 120px;
}

::v-deep .el-descriptions .is-bordered .el-descriptions-item__cell {
  border: 1px solid #838894;
}

::v-deep .el-descriptions-item__label.is-bordered-label {
  color: #434141;
  background: #eaeaea;
  width: 120px;
}

.business-section {
  border: 2px solid #E6A23C !important;
  box-shadow: 0 0 10px rgba(64, 158, 255, 0.2);

  tr {
    background-color: #f0f7ff;

    &:hover {
      background-color: #e6f1ff;
    }
  }

  .el-input-number {
    .el-input__inner {
      background-color: #fff;
      border: 1px solid #E6A23C;

      &:focus {
        border-color: #e2af62;
        box-shadow: 0 0 5px rgba(64, 158, 255, 0.3);
      }
    }
  }

  .head.amount {
    background-color: #ecf5ff;
    color: #E6A23C;
    font-weight: bold;
  }
}
</style>