<!--
 * @Author: ysh
 * @Date: 2024-04-03 16:28:09
 * @LastEditors: wrh
 * @LastEditTime: 2025-12-31 16:22:43
-->
<template>
  <div class="main">
    <div v-loading="loading">
      <h2 class="text-center">项目直接生产成本预算表（旧版）</h2>
      <p style="text-align: center;">编制人：{{ budgetForm.compilerUser ? budgetForm.compilerUser.nickName : '' }} | 编制时间：{{ budgetForm.createTime }} </p>
      <el-descriptions :column="3" border class="descriptions">
        <el-descriptions-item label="项目编号">
          {{ projectForm.projectNumber }}
        </el-descriptions-item>
        <el-descriptions-item label="项目名称">
          {{ projectForm.projectName }}
        </el-descriptions-item>
        <el-descriptions-item label="项目负责人">
          {{ getUserName(projectForm.projectLeader) }}
        </el-descriptions-item>
        <el-descriptions-item label="承担部门">
          {{ getDeptNames(projectForm.undertakingDept) }}
        </el-descriptions-item>
        <el-descriptions-item label="项目备注" :span="3">
          {{ projectForm.remark }}
        </el-descriptions-item>
        <el-descriptions-item label="预算表单备注" :span="5">
          {{ budgetForm.remark }}
        </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>
                  {{ 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:80px">金额</td>
              <td style="min-width: 150px;">备注</td>
            </tr>
            <tr v-for="work in workList">
              <td>{{ work.content }}</td>
              <td>{{ work.cmcPrice ? work.cmcPrice.workItem : '' }}</td>
              <td>
                {{ work.scaleGrade }}
              </td>
              <td v-if="taskName == '分管审核' || taskName == '总经理审核'">
                <el-input-number :controls="false" style="width:100px;" v-model="work.workload"
                  @change="computeWorkSettle(work)"></el-input-number>
              </td>
              <td v-else>
                {{ work.workload }}
              </td>
              <td>{{ work.price }}</td>
              <td>{{ work.unit }}</td>
              <td v-if="taskName == '分管审核' || taskName == '总经理审核'">
                <el-input-number :controls="false" style="width:100px;" v-model="work.coefficient"
                  @change="computeWorkSettle(work)"></el-input-number>
                <el-button type="text" @click="getCoefficientRemark(work)">系数备注</el-button>
              </td>
              <td v-else>
                {{ 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="7" class="head">预结算额合计</td>
              <td :colspan="1" class="head" style="text-align:right;">{{ budgetForm.settleExpense ?
                budgetForm.settleExpense.toFixed(2) : '0.00' }}</td>
              <td></td>
            </tr>
          </table>
        </el-descriptions-item>
        <el-descriptions-item label="间接成本" :span="3">
          <table border="1" style="width:100%">
            <tr v-if="userLen != 1" style="background-color:#f8f8f9">
              <td :rowspan="userLen">人员</td>
              <td>姓名</td>
              <td>基本工资</td>
              <td>岗位工资</td>
              <td>人员成本（天）</td>
              <td></td>
              <td></td>
              <td style="min-width:80px">预算天数</td>
              <td></td>
              <td style="min-width:80px">金额</td>
            </tr>
            <tr v-for="user, index in chooseUser" :key="'user' + user.userId + index">
              <td>{{ user.user ? user.user.nickName : '' }}</td>
              <td>1780</td>
              <td>
                <span v-if="$store.getters.roles.includes('leader')">
                  {{ user.user.deptId === 115 ? '/' : user.salary.salary }}
                </span>
                <span v-else>/</span>
              </td>
              <td>
                <span v-if="$store.getters.roles.includes('leader')">
                  {{ parseFloat((user.salary.salary + 1780) / 21.75) ? parseFloat((user.salary.salary + 1780) /
                    21.75).toFixed(2) : '0.00' }}
                </span>
                <span v-else>/</span>
              </td>
              <td></td>
              <td></td>
              <td v-if="taskName == '分管审核' || taskName == '总经理审核' || taskName == '预算批准'">
                <el-input-number :controls="false" style="width:100px;" v-model="user.days"
                  @blur="computedFixCostSettle(user, 'user')"></el-input-number>
              </td>
              <td v-else>
                {{ user.days }}
              </td>
              <td></td>
              <td style="text-align:right;">{{ user.staffCost ? user.staffCost.toFixed(2) : '0.00' }}</td>
            </tr>
            <tr v-if="carLen != 1" style="background-color:#f8f8f9">
              <td :rowspan="carLen">车辆</td>
              <td>车牌号</td>
              <td>油耗（元/km）</td>
              <td>保险（元/天）</td>
              <td>维修（元/天）</td>
              <td>折旧成本（天）</td>
              <td>总里程</td>
              <td>预算天数</td>
              <td>过路费</td>
              <td>金额</td>
            </tr>
            <tr v-for="car in chooseCar" :key="'car' + car.carId">
              <td>{{ car.car ? car.car.licensePlate : '' }}</td>
              <td>{{ car.car ? car.car.fuel : '' }}</td>
              <td>{{ car.car ? car.car.insurance : '' }}</td>
              <td>{{ car.car ? car.car.maintenance : '' }}</td>
              <td>{{ car.car ? car.car.dayCost : '' }}</td>
              <td v-if="taskName != '分管审核' && taskName != '总经理审核'">{{ car.distance }}</td>
              <td v-if="taskName == '分管审核' || taskName == '总经理审核'">
                <el-input-number :controls="false" style="width:100px;" v-model="car.distance"
                  @blur="computedFixCostSettle(car, 'car')"></el-input-number>
              </td>
              <!-- <td v-else>
                {{ car.distance }}
              </td> -->
              <td v-if="taskName == '分管审核' || taskName == '总经理审核'">
                <el-input-number :controls="false" style="width:100px;" v-model="car.days"
                  @blur="computedFixCostSettle(car, 'car')"></el-input-number>
              </td>
              <td v-else>
                {{ car.days }}
              </td>
              <td> {{ car.toll }} </td>
              <td style="text-align:right;">{{ car.expense ? car.expense.toFixed(2) : '0.00' }}</td>
            </tr>
            <tr v-if="deviceLen != 1" style="background-color:#f8f8f9">
              <td :rowspan="deviceLen">设备</td>
              <td>设备名称</td>
              <td>规格型号</td>
              <td>品牌</td>
              <td>折旧成本（天）</td>
              <td></td>
              <td></td>
              <td>预算天数</td>
              <td></td>
              <td>金额</td>
            </tr>
            <tr v-for="device in chooseDevice" :key="'device' + device.deviceId">
              <td>{{ device.device ? device.device.name : '' }}</td>
              <td>{{ device.device ? device.device.series : '' }}</td>
              <td>{{ device.device ? device.device.brand : '' }}</td>
              <td>{{ device.device ? device.device.dayCost : '' }}</td>
              <td></td>
              <td></td>
              <td v-if="taskName == '分管审核' || taskName == '总经理审核'">
                <el-input-number :controls="false" style="width:100px;" v-model="device.days"
                  @blur="computedFixCostSettle(device, 'device')"></el-input-number>
              </td>
              <td v-else>
                {{ device.days }}
              </td>
              <td></td>
              <td style="text-align:right;">{{ device.depreciation ? device.depreciation.toFixed(2) : '0.00' }}</td>
            </tr>
            <tr>
              <td :colspan="9" class="head">间接成本合计</td>
              <td :colspan="1" class="head" style="text-align:right;">{{ budgetForm.fixCost }}</td>
            </tr>
          </table>
        </el-descriptions-item>
        <el-descriptions-item label="外协费用" :span="2">
          <div v-if="taskName == '分管审核' || taskName == '总经理审核'">
            <el-input-number :controls="false" style="width:100%;" v-model="budgetForm.outExpense"
              @blur="computedDirectExpense()"></el-input-number>
          </div>
          <div v-else class="text-center">
            {{ budgetForm.outExpense }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="1">
          {{ budgetForm.outRemark }}
        </el-descriptions-item>
        <el-descriptions-item label="车船租赁" :span="2">
          <div v-if="taskName == '分管审核' || taskName == '总经理审核'">
            <el-input-number :controls="false" style="width:100%;" v-model="budgetForm.rentExpense"
              @blur="computedDirectExpense()"></el-input-number>
          </div>
          <div v-else class="text-center">
            {{ budgetForm.rentExpense }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="1">
          {{ budgetForm.rentRemark }}
        </el-descriptions-item>
        <el-descriptions-item label="其他费用" :span="2">
          <div v-if="taskName == '分管审核' || taskName == '总经理审核'">
            <el-input-number :controls="false" style="width:100%;" v-model="budgetForm.otherExpense"
              @blur="computedDirectExpense()"></el-input-number>
          </div>
          <div v-else class="text-center">
            {{ budgetForm.otherExpense }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="1">
          {{ budgetForm.otherRemark }}
        </el-descriptions-item>
        <el-descriptions-item label="税费成本" :span="2">
          <div v-if="taskName == '分管审核' || taskName == '总经理审核'">
            <el-input-number :controls="false" style="width:100%;" v-model="budgetForm.taxExpense"
              @blur="computedDirectExpense()"></el-input-number>
          </div>
          <div v-else class="text-center">
            {{ budgetForm.taxExpense }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="1">
          {{ budgetForm.taxRemark }}
        </el-descriptions-item>
        <el-descriptions-item label="经营管理费用" :span="2">
          <div v-if="taskName == '分管审核' || taskName == '总经理审核'">
            <el-input-number :controls="false" style="width:100%;" v-model="budgetForm.businessExpense"
              @blur="computedDirectExpense()"></el-input-number>
          </div>
          <div v-else class="text-center">
            {{ budgetForm.businessExpense }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="1">
          {{ budgetForm.businessRemark }}
        </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 class="text-center" style="font-weight:bold;font-size:18px;color:orange">
            {{ budgetForm.totalBudget }}
          </div>
          <div class="text-center">
            <!-- （简写：{{ (budgetForm.totalBudget / 10000).toFixed(4) + '万' }}） -->
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="合同总价约" :span="3" v-if="$store.getters.roles.includes('leader')">
          <div class="text-center" style="font-weight:bold;font-size:18px;color:#409EFF">
            {{ contract.contractId ? contract.amount : '' }}
          </div>
          <div class="text-center">
            <!-- （简写：{{ contract.contractId ? (contract.amount / 10000).toFixed(4) + '万' : '' }}） -->
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="利润" :span="3" v-if="$store.getters.roles.includes('leader')">
          <div class="text-center" style="font-weight:bold;font-size:18px;color:#67C23A">
            {{ profit ? profit.toFixed(2) : '0.00' }}
          </div>
          <div class="text-center">
            <!-- （简写：{{ (profit / 10000).toFixed(4) + '万' }}） -->
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="分管审核意见" :span="3">
          <div>
            <el-input :disabled="taskName != '分管审核'" type="textarea" placeholder="请输入审核意见"
              v-model="budgetForm.managerComment" :autosize="{ minRows: 4 }"></el-input>
            <div class="sign mt10">
              <div class="mr20">签名：<span class="auditor">{{ getUserName(budgetForm.manager) }}</span>
              </div>
              <div class="ml20"><span>审核时间：{{ budgetForm.managerTime }}</span></div>
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="总经理审核意见" :span="3">
          <div>
            <el-input :disabled="taskName != '总经理审核'" type="textarea" placeholder="请输入审核意见"
              v-model="budgetForm.zjlComment" :autosize="{ minRows: 4 }"></el-input>
            <div class="sign mt10">
              <div class="mr20">签名：<span class="auditor">{{ getUserName(budgetForm.auditor) }}</span>
              </div>
              <div class="ml20"><span>审核时间：{{ budgetForm.zjlTime }}</span></div>
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="董事长批准意见" :span="3">
          <div>
            <el-input :disabled="taskName != '预算批准'" type="textarea" placeholder="请输入审核意见"
              v-model="budgetForm.dszComment" :autosize="{ minRows: 4 }"></el-input>
            <div class="sign mt10">
              <div class="mr20">签名：<span class="auditor">{{ getUserName(budgetForm.approver) }}</span>
              </div>
              <div class="ml20"><span>审核时间：{{ budgetForm.dszTime }}</span></div>
            </div>
          </div>
        </el-descriptions-item>
      </el-descriptions>
    </div>

    <el-row v-if="taskName == '分管审核' || taskName == '总经理审核' || taskName == '预算批准'" class="text-center mt20 mb20">
      <el-button type="danger" @click="returnOpen = true">退 回</el-button>
      <el-button type="success" @click="confirmSucess(taskName)">提 交</el-button>
    </el-row>
    <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>
  </div>
</template>

<script>
import { listBudget, updateBudget } from "@/api/oa/budget/budget";
import { listBudgetCar, updateBudgetCar } from "@/api/oa/budget/budgetCar";
import { listBudgetDevice, updateBudgetDevice } from "@/api/oa/budget/budgetDevice";
import { listBudgetSettle, updateBudgetSettle } from "@/api/oa/budget/budgetSettle";
import { listBudgetStaff, updateBudgetStaff } from "@/api/oa/budget/budgetStaff";
import { listProjectWork } from "@/api/oa/project/projectWork";
import { mapGetters } from 'vuex';
import { getProject } from "@/api/oa/project/project";
import { listProjectContract, addProjectContract } from "@/api/oa/contract/projectContract";
import { listContract, getContract, delContract, addContract, updateContract } from "@/api/oa/contract/contract";
import { complete, rejectTask, returnList, returnTask, getNextFlowNode, delegate, flowTaskForm } from "@/api/flowable/todo";
import { getUser } from '@/api/system/user'
import { getUsersManageLeaderByDept } from '@/api/system/post'
import { getPriceRemarkByWorkType } from '@/api/oa/price/price'
import { getUserByPost } from "@/api/system/post";
import ReturnComment from '@/views/flowable/form/components/flowBtn/returnComment.vue';
import ReturnBtn from '@/views/flowable/form/components/flowBtn/returnBtn.vue';
export default {
  components: {
    ReturnComment,
    ReturnBtn
  },
  computed: {
    ...mapGetters(["name", "userId"]),
  },
  props: {
    taskForm: {
      type: Object,
      require: true
    },
    taskName: {
      type: String,
    }
  },
  watch: {
    'taskForm.procInsId'() {
      this.initBudgetForm();
    }
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      projectId: '',
      managerList: [],
      budgetForm: {
      },
      projectForm: {
        projectRegistrantUser: {
          nickName: ''
        }
      },
      userLen: 1,
      carLen: 1,
      deviceLen: 1,
      workLen: 1,
      chooseCar: [],
      chooseDevice: [],
      chooseUser: [],
      workList: [],
      workContentList: [],
      contract: {},
      profit: 0,
      returnOpen: false,
      loading: true,
    };
  },
  created() {
    this.initBudgetForm();
  },
  methods: {
    initBudgetForm() {
      this.loading = true;
      listBudget({ pageNum: 1, pageSize: 20, projectId: this.taskForm.formId, procInstId:this.taskForm.procInsId }).then(res => {
        this.budgetForm = res.rows[0];
        this.setSignName();
        if (this.budgetForm) {
          listBudgetDevice({ pageSize: 100, budgetId: this.budgetForm.budgetId }).then(res => {
            this.chooseDevice = res.rows;
            this.deviceLen = res.rows.length + 1;
          })
          listBudgetStaff({ pageSize: 100, budgetId: this.budgetForm.budgetId }).then(res => {
            let staffList = res.rows;
            this.userLen = res.rows.length + 1;
            for (let staff of staffList) {
              if (staff.user.deptId === 115) {
                staff.salary = { salary: 7898.75 }
              }
            }
            this.chooseUser = staffList
          })
          listBudgetCar({ pageSize: 100, budgetId: this.budgetForm.budgetId }).then(res => {
            this.chooseCar = res.rows;
            this.carLen = res.rows.length + 1;
          })
          listBudgetSettle({ pageSize: 100, budgetId: this.budgetForm.budgetId }).then(res => {
            this.workList = res.rows;
            this.workLen = res.rows.length;

            for (let work of this.workList) {
              if (work.groundType == '0') {
                if (work.cmcPrice) {
                  work.price = work.cmcPrice.commonPrice
                  work.scaleGrade = work.cmcPrice.scaleGrade
                  work.unit = work.cmcPrice.unit
                }
              } else {
                if (work.cmcPrice) {
                  work.price = work.cmcPrice.complexPrice
                  work.scaleGrade = work.cmcPrice.scaleGrade
                  work.unit = work.cmcPrice.unit
                }
              }
            }
            this.loading = false;
            this.getProjectWorkList();
          })
          this.getProjectList();
          listProjectContract({ projectId: this.taskForm.formId }).then(res => {
            if (res.total == 1) {
              getContract(res.rows[0].contractId).then(response => {
                this.contract = response.data;
                this.profit = Number(this.contract.amount) - Number(this.budgetForm.totalBudget)
              })
            }
          })
        }
      });
    },
    setSignName() {
      const signUser = this.$store.getters.userId
      const times = this.parseTime(new Date(), '{y}-{m}-{d}')
      if (this.taskName == '分管审核') {
        this.budgetForm.manager = signUser
        this.budgetForm.managerTime = times
      } else if (this.taskName == '总经理审核') {
        this.budgetForm.auditor = signUser
        this.budgetForm.zjlTime = times
      } else if (this.taskName == '预算批准') {
        this.budgetForm.approver = signUser
        this.budgetForm.dszTime = times
      }
    },
    // 查询项目列表
    getProjectList() {
      getProject(this.taskForm.formId).then(response => {
        this.projectForm = response.data;
      });
    },
    getProjectWorkList() {
      listProjectWork({ pageSize: 999, projectId: this.taskForm.formId }).then(res => {
        this.workContentList = res.rows;
      })
    },
    confirmSucess(taskName) {
      const params = { taskId: this.taskForm.taskId };
      if (taskName == '分管审核') {
        if (this.budgetForm.managerComment == '' || this.budgetForm.managerComment == null) {
          this.$modal.msgError('请填写审核意见');
          return
        }
        this.updateBudgetForm();
        getNextFlowNode(params).then(res => {
          getUserByPost({ postName: "总经理" }).then(res => {
            const userId = res.data[0].userId;
            this.$set(this.taskForm.variables, "approval", userId);
            complete(this.taskForm).then(response => {
              this.$modal.msgSuccess(response.msg);
              this.$emit("goBack");
            });
          })

        })
      } else if (taskName == '总经理审核') {
        if (this.budgetForm.zjlComment == '' || this.budgetForm.zjlComment == null) {
          this.$modal.msgError('请填写审核意见');
          return
        }
        this.updateBudgetForm();
        getNextFlowNode(params).then(res => {
          getUserByPost({ postName: "董事长" }).then(res => {
            const userId = res.data[0].userId;
            this.$set(this.taskForm.variables, "approval", userId);
            complete(this.taskForm).then(response => {
              this.$modal.msgSuccess(response.msg);
              this.$emit("goBack");
            });
          })
        })
      } else {
        if (this.budgetForm.dszComment == '' || this.budgetForm.dszComment == null) {
          this.$modal.msgError('请填写审核意见');
          return
        }
        this.updateBudgetForm();
        getNextFlowNode(params).then(res => {
          complete(this.taskForm).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.$emit("goBack");
          });
        })
      }
    },
    updateBudgetForm() {
      updateBudget(this.budgetForm).then(res => {
        this.updateBudgetSubItem(this.chooseCar, updateBudgetCar);
        this.updateBudgetSubItem(this.chooseDevice, updateBudgetDevice);
        this.updateBudgetSubItem(this.chooseUser, updateBudgetStaff);
        this.updateBudgetSubItem(this.workList, updateBudgetSettle, this.showSuccessMessage);
      });
    },
    updateBudgetSubItem(items, updateFunction, onSuccess) {
      // 假设所有更新都成功  
      let allUpdatesSuccessful = true;
      // 遍历项目数组，并对每个项目调用更新函数  
      for (let item of items) {
        try {
          updateFunction(item);
        } catch (error) {
          // 如果有任何更新失败，设置标志并可能记录错误  
          allUpdatesSuccessful = false;
          console.error('更新失败:', error);
        }
      }
      // 如果所有更新都成功，调用onSuccess回调函数  
      if (allUpdatesSuccessful && typeof onSuccess === 'function') {
        onSuccess();
      }
    },
    showSuccessMessage() {
      this.$message.success('预算更新成功！')
    },
    // 计算作业结算金额
    computeWorkSettle(work) {
      let workload = Number(work.workload);
      let price = Number(work.price);
      let coefficient = Number(work.coefficient);
      if (!isNaN(workload) && !isNaN(price) && !isNaN(coefficient)) {
        let result = workload * price * coefficient;
        if (result < 600) {
          result = 600
          this.$message.warning('不足600，按600算')
        }
        this.$set(work, 'settle', result.toFixed(2));
        this.computedSettleExpense();
        this.computedDirectExpense();
      } else {
        this.$message.error('请确保参与计算的值都为数字')
      }
    },
    computedFixCostSettle(item, type) {
      if (type == 'user') {
        let salaryPerDay = (Number(item.salary.salary) + 1780 || 0) / 21.75; // 转换为每天的薪资，或默认为0  
        let totalDays = Number(item.days) || 0; // 转换为天数，或默认为0  
        // 计算总薪资  
        let total = (salaryPerDay * totalDays).toFixed(2);
        this.$set(item, 'staffCost', total);
        this.getCost("staffCost", "staffCost", this.chooseUser);
      } else if (type == 'car') {
        let total1 = (Number(item.fuel) || 0) * (Number(item.distance) || 0);
        let total2 = (Number(item.car.dayCost) || 0) * (Number(item.days) || 0);
        this.$set(item, "depreciation", total2);
        let sum = (total1 + total2).toFixed(2); // sum 是一个字符串  
        this.$set(item, "expense", sum); // expense 将是一个字符串，包含两位小数的总和   
        this.getCost("expense", "carCost", this.chooseCar);
      } else {
        let total = (Number(item.device.dayCost) || 0) * (Number(item.days) || 0);
        this.$set(item, "depreciation", total.toFixed(2));
        this.getCost("depreciation", "deviceCost", this.chooseDevice);
      }
      this.getFixCost();
      this.computedTotalBudget();
    },
    getCost(name1, name2, list) {
      let sum = 0;
      for (let user of list) {
        sum = sum + Number(user[name1]);
      }
      this.budgetForm[name2] = sum.toFixed(2);
    },
    getFixCost() {
      let total =
        Number(this.budgetForm.staffCost) +
        Number(this.budgetForm.carCost) +
        Number(this.budgetForm.deviceCost);
      this.budgetForm.fixCost = total.toFixed(2);
    },
    computedSettleExpense() {
      let sum = this.workList.reduce((accumulator, work) => {
        const settleValue = Number(work.settle);
        // 如果settleValue不是NaN（即它可以被转换为数字）  
        if (!isNaN(settleValue)) {
          return accumulator + settleValue;
        }
        return accumulator;
      }, 0); // 初始累加器值为0  
      this.$set(this.budgetForm, 'settleExpense', sum.toFixed(2))
    },
    computedDirectExpense() {
      const { settleExpense, outExpense, businessExpense, taxExpense, rentExpense, otherExpense } = this.budgetForm;
      const expenses = [settleExpense, outExpense, businessExpense, taxExpense, rentExpense, otherExpense];
      // 使用 reduce 函数计算总和  
      let sum = expenses.reduce((acc, curr) => {
        // 确保每个当前值都是数字（如果不是，则默认为0）  
        const num = Number(curr) || 0;
        return acc + num;
      }, 0);
      this.$set(this.budgetForm, 'directExpense', `${sum.toFixed(2)}`);
      this.computedTotalBudget();
    },
    computedTotalBudget() {
      const { fixCost, directExpense } = this.budgetForm;
      // 确保 fixCost 和 directExpense 是数字，如果不是则默认为 0  
      const totalBudget = (Number(fixCost) || 0) + (Number(directExpense) || 0);
      this.$set(this.budgetForm, 'totalBudget', totalBudget.toFixed(2));
      this.profit = (Number(this.contract.amount) || 0) - (Number(totalBudget) || 0);
    },
    getCoefficientRemark(work) {
      let workType = work.cmcPrice.workType
      getPriceRemarkByWorkType({ workType }).then(res => {
        if (res.code == 200) {
          if (workType != undefined)
            this.$notify({
              title: workType,
              dangerouslyUseHTMLString: true,
              message: res.msg,
              duration: 0
            });
        }
      })
    },
    commentByRole() {
      if (this.taskName == '分管审核') {
        return this.budgetForm.managerComment
      } else if (this.taskName == '总经理审核') {
        return this.budgetForm.zjlComment
      } else if (this.taskName == '董事长批准') {
        return this.budgetForm.dszComment
      }
    }
  },
};
</script>

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

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

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

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

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

.head {
  line-height: 35px;
  font-weight: bold;
}

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

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

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