<!--
 * @Author: ysh
 * @Date: 2024-03-25 15:05:59
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-07-08 10:45:42
-->
<template>
  <div>
    <div>
      <el-alert v-if="reBackDescription != ''" title="预算被退回" type="warning" show-icon :description="reBackDescription">
      </el-alert>
      <div class="header">
        <div class="title">
          <div class="title-text">新增预算</div>
          <div class="title-tips">
            请精准填写预算标准，对应的人员、设备、车辆可直接选择生成间接成本
          </div>
        </div>
      </div>
      <div class="add-main">
        <el-steps :active="activeStep" align-center finish-status="success">
          <el-step title="项目信息" description="需要预算的项目"></el-step>
          <el-step title="间接成本明细" description="选择参与的人员、车辆和设备，得到间接成本"></el-step>
          <!-- <el-step title="选择车辆和设备" description="选择，得到对应预算"></el-step> -->
          <el-step title="直接成本明细" description="包含绩效预算和其他预算"></el-step>
          <el-step title="生成预算表" description="生成最终的项目预算表"></el-step>
        </el-steps>
        <!-- 选择项目 -->
        <div class="project" v-show="activeStep == 0">
          <el-form ref="form1" :model="projectForm" :rules="projectRule" label-width="120px">
            <el-form-item label="项目编号：" prop="projectNumber">
              <div style="display: flex">
                <el-input v-model="projectForm.projectNumber" placeholder="请选择项目编号" disabled style="width: 300px" />
              </div>
            </el-form-item>
            <el-form-item label="项目名称：" prop="projectName">
              {{ projectForm.projectName }}
            </el-form-item>
            <el-form-item label="项目负责人：" prop="projectLeader">
              {{
        projectForm.projectLeaderUser
          ? projectForm.projectLeaderUser.nickName
          : ""
      }}
            </el-form-item>
            <el-form-item label="项目类型：" prop="projectType">
              {{ projectForm.projectType }}
            </el-form-item>
            <el-form-item label="项目概况：">
              <table border="1">
                <tr>
                  <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 workList" :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>
            </el-form-item>
            <el-form-item label="甲方单位：">
              {{ projectForm.partyA ? projectForm.partyA.partyAName : '' }}
            </el-form-item>
            <el-form-item label="联系人：">
              {{ projectForm.contactPerson }}
            </el-form-item>
            <el-form-item label="联系方式：">
              {{ projectForm.telephone }}
            </el-form-item>
            <el-form-item label="项目登记人：">
              {{ projectForm.projectRegistrantUser.nickName }}
            </el-form-item>
            <el-form-item label="登记时间：">
              {{ projectForm.registerTime }}
            </el-form-item>
            <el-form-item label="备注：">
              {{ projectForm.remark }}
            </el-form-item>
          </el-form>
        </div>

        <!-- 选择参与人员、车辆和设备 -->
        <div class="staff" v-show="activeStep == 1">
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item>选择项目</el-breadcrumb-item>
            <el-breadcrumb-item>{{ projectForm.projectNumber }}</el-breadcrumb-item>
            <el-breadcrumb-item>{{ projectForm.projectName }}</el-breadcrumb-item>
            <el-breadcrumb-item>{{ projectForm.projectLeaderUser
        ? projectForm.projectLeaderUser.nickName
        : "" }}</el-breadcrumb-item>
          </el-breadcrumb>
          <el-form ref="form2" :model="peopleForm" style="padding: 20px 100px 0">
            <!-- 选择人员 -->
            <el-form-item label="选择人员：">
              <span v-if="chooseUser.length != 0">
                <el-tag effect="plain" type="" v-for="item in chooseUser" style="margin: 5px; font-size: 14px"
                  :key="item.userId">
                  {{ item.nickName }}
                </el-tag>
              </span>
              <el-button type="primary" plain icon="el-icon-plus" @click="openPeople = true" size="mini">选择</el-button>
            </el-form-item>
            <el-form-item label="人员预算：" v-if="chooseUser.length != 0">
              <table border="1">
                <tr>
                  <td style="width: 80px">姓名</td>
                  <td style="width: 100px">部门</td>
                  <td style="width: 100px">基础工资</td>
                  <td style="width: 100px">岗位工资</td>
                  <td style="width: 110px">人员成本(元/天)</td>
                  <!-- <td style="width: 100px">进出场单价</td> -->
                  <td style="width: 100px">预算天数</td>
                  <td style="width: 100px">总额</td>
                </tr>
                <tr v-for="user in chooseUser" :key="user.userId">
                  <td>{{ user.nickName }}</td>
                  <td>{{ user.dept ? user.dept.deptName : user.deptName }}</td>
                  <td>{{ 1780 }}</td>
                  <td>{{ user.salary.salary }}</td>
                  <td>{{ parseFloat((user.salary.salary + 1780) / 21.75).toFixed(2) }}</td>
                  <!-- <td>
                    <el-input
                      v-model="user.inOutPrice"
                      placeholder="请输入进出场单价"
                      @change="calculateUserTotal(user)"
                    ></el-input>
                  </td> -->
                  <td>
                    <el-input v-model="user.days" placeholder="请输入天数" @change="calculateUserTotal(user)"></el-input>
                  </td>
                  <td class="staffCost">{{ user.staffCost }}</td>
                </tr>
                <tr>
                  <td colspan="6">合计</td>
                  <td>{{ budgetForm.staffCost }}</td>
                </tr>
              </table>
            </el-form-item>

            <div style="color:red">tips:人员成本=(基础工资+岗位工资)/21.75，固定工资中的年功工资暂忽略不计，绩效工资计入直接成本，津贴补贴、五险一金扣除暂未考虑</div>
            <!-- 选择车辆 -->
            <el-form-item label="选择车辆：">
              <span v-if="chooseCar.length != 0">
                <el-tag effect="plain" v-for="item in chooseCar" style="margin: 5px; font-size: 14px"
                  :key="item.licensePlate">
                  {{ item.licensePlate + item.brand }}
                </el-tag>
              </span>
              <el-button type="primary" plain icon="el-icon-plus" @click="openCar = true" size="mini">选择</el-button>
            </el-form-item>
            <el-form-item label="车辆预算：" v-if="chooseCar.length != 0">
              <table border="1">
                <tr>
                  <td style="width: 120px">车牌号</td>
                  <td style="width: 100px">油耗</td>
                  <td style="width: 100px">总里程</td>
                  <td style="width: 110px">折旧成本（天）</td>
                  <td style="width: 110px">预算天数</td>
                  <td style="width: 100px">总额</td>
                </tr>
                <tr v-for="car in chooseCar" :key="car.carId">
                  <td>{{ car.licensePlate }}</td>
                  <td>
                    {{ car.mileage }}
                  </td>
                  <td>
                    <el-input v-model="car.distance" placeholder="请输入总里程" @change="calculateCarTotal(car)"></el-input>
                  </td>
                  <td>
                    {{ car.dayCost }}
                  </td>
                  <td>
                    <el-input v-model="car.days" placeholder="请输入天数" @change="calculateCarTotal(car)"></el-input>
                  </td>
                  <td class="carCost">{{ car.expense }}</td>
                </tr>
                <tr>
                  <td colspan="5">合计</td>
                  <td>{{ budgetForm.carCost }}</td>
                </tr>
              </table>
            </el-form-item>
            <!-- 选择设备 -->
            <el-form-item label="选择设备：">
              <span v-if="chooseDevice.length != 0">
                <el-tag effect="plain" type="" v-for="item in chooseDevice" style="margin: 5px; font-size: 14px"
                  :key="item.code">
                  {{ item.name + "-" + item.series + "-" + item.brand }}
                </el-tag>
              </span>
              <el-button type="primary" plain icon="el-icon-plus" @click="openDevice = true" size="mini">选择</el-button>
            </el-form-item>
            <el-form-item label="设备预算：" v-if="chooseDevice.length != 0">
              <table border="1">
                <tr>
                  <td style="width: 120px">设备名称</td>
                  <td style="width: 120px">规格型号</td>
                  <td style="width: 120px">品牌</td>
                  <td>折旧成本（天）</td>
                  <td style="width: 100px">预算天数</td>
                  <td style="width: 100px">总额</td>
                </tr>
                <tr v-for="device in chooseDevice" :key="device.deviceId">
                  <td>{{ device.name }}</td>
                  <td>{{ device.series }}</td>
                  <td>{{ device.brand }}</td>
                  <td>
                    {{ device.dayCost }}
                  </td>
                  <td>
                    <el-input v-model="device.days" placeholder="请输入天数"
                      @change="calculateDeviceTotal(device)"></el-input>
                  </td>
                  <td class="deviceCost">{{ device.depreciation }}</td>
                </tr>
                <tr>
                  <td colspan="5">合计</td>
                  <td>{{ budgetForm.deviceCost }}</td>
                </tr>
              </table>
            </el-form-item>
            <el-form-item label="间接成本小计：">
              <el-tag type="danger" style="margin-right: 20px; font-size: 14px">¥ {{ budgetForm.fixCost }}</el-tag>
            </el-form-item>
          </el-form>
        </div>
        <!-- 绩效和其他预算 -->
        <div class="other" v-show="activeStep == 2">
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item>选择项目</el-breadcrumb-item>
            <el-breadcrumb-item>{{ projectForm.projectNumber }}</el-breadcrumb-item>
            <el-breadcrumb-item>{{ projectForm.projectName }}</el-breadcrumb-item>
            <el-breadcrumb-item>{{ projectForm.projectLeaderUser
        ? projectForm.projectLeaderUser.nickName
        : "" }}</el-breadcrumb-item>
          </el-breadcrumb>
          <el-breadcrumb separator-class="el-icon-arrow-right" style="margin: 15px 0">
            <el-breadcrumb-item>间接成本小计</el-breadcrumb-item>
            <el-breadcrumb-item>¥ {{ budgetForm.fixCost }}</el-breadcrumb-item>
          </el-breadcrumb>
          <el-form>
            <choose-money :workList="workList" :settleList="contentList" :chooseUser="chooseUser"
              :budgetForm="budgetForm" @getSettle="getSettle" @getWorkList="setPreSettlement"></choose-money>
            <el-form-item label="关联合同：" label-width="90px" v-if="contract.contractId">
              <table border="1">
                <tr class="head">
                  <td>合同项目</td>
                  <td>合同编码</td>
                  <td>合同编号</td>
                  <td>合同金额</td>
                </tr>
                <tr>
                  <td>{{ contract.tender ? contract.tender.projectName : '' }}</td>
                  <td>{{ contract.contractCode }}</td>
                  <td>{{ contract.contractNumber }}</td>
                  <td>{{ contract.amount }}</td>
                </tr>
              </table>
            </el-form-item>
            <el-form-item label="其他预算：" label-width="90px">
              <table border="1">
                <tr class="head">
                  <td>内容</td>
                  <td>费用金额</td>
                  <td>备注</td>
                </tr>
                <tr>
                  <td>外协费用</td>
                  <td>
                    <el-input-number :controls="false" :precision="2" v-model="budgetForm.outExpense"
                      style="width: 100%" @change="getDirectExpense(budgetForm)"></el-input-number>
                  </td>
                  <td>
                    <el-input type="textarea" v-model="budgetForm.outRemark" style="width: 100%"></el-input>
                  </td>
                </tr>
                <tr>
                  <td>税费成本</td>
                  <td>
                    <el-input-number :controls="false" :precision="2" v-model="budgetForm.taxExpense"
                      style="width: 100%" @change="getDirectExpense(budgetForm)"></el-input-number>
                  </td>
                  <td>
                    <el-input type="textarea" v-model="budgetForm.taxRemark" style="width: 100%"></el-input>
                  </td>
                </tr>
                <tr>
                  <td>经营管理费用</td>
                  <td>
                    <el-input-number :controls="false" :precision="2" v-model="budgetForm.businessExpense"
                      style="width: 100%" @change="getDirectExpense(budgetForm)"></el-input-number>
                  </td>
                  <td>
                    <el-input type="textarea" v-model="budgetForm.businessRemark" style="width: 100%"></el-input>
                  </td>
                </tr>
                <tr>
                  <td>车船租赁</td>
                  <td>
                    <el-input-number :controls="false" :precision="2" v-model="budgetForm.rentExpense"
                      style="width: 100%" @change="getDirectExpense(budgetForm)"></el-input-number>
                  </td>
                  <td>
                    <el-input type="textarea" v-model="budgetForm.rentRemark" style="width: 100%"></el-input>
                  </td>
                </tr>
                <tr>
                  <td>其他费用</td>
                  <td>
                    <el-input-number :controls="false" :precision="2" v-model="budgetForm.otherExpense"
                      style="width: 100%" @change="getDirectExpense(budgetForm)"></el-input-number>
                  </td>
                  <td>
                    <el-input type="textarea" v-model="budgetForm.otherRemark" style="width: 100%"></el-input>
                  </td>
                </tr>
              </table>
            </el-form-item>
            <el-form-item label="小计：">
              <el-tag type="danger" style="margin-right: 20px; font-size: 14px">
                ¥{{ budgetForm.directExpense }}
              </el-tag>
            </el-form-item>
          </el-form>
        </div>

        <!-- 生成预算表 -->
        <div class="finish" v-if="activeStep == 3">
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item>选择项目</el-breadcrumb-item>
            <el-breadcrumb-item>{{ projectForm.projectNumber }}</el-breadcrumb-item>
            <el-breadcrumb-item>{{ projectForm.projectName }}</el-breadcrumb-item>
            <el-breadcrumb-item>{{ projectForm.projectLeaderUser
        ? projectForm.projectLeaderUser.nickName
        : "" }}</el-breadcrumb-item>
          </el-breadcrumb>
          <el-breadcrumb separator-class="el-icon-arrow-right" style="margin: 15px 0">
            <el-breadcrumb-item>间接成本小计</el-breadcrumb-item>
            <el-breadcrumb-item>¥ {{ budgetForm.fixCost }}</el-breadcrumb-item>
          </el-breadcrumb>
          <el-breadcrumb separator-class="el-icon-arrow-right" style="margin: 15px 0">
            <el-breadcrumb-item>直接成本和其他成本小计</el-breadcrumb-item>
            <el-breadcrumb-item>¥ {{ budgetForm.directExpense }}</el-breadcrumb-item>
          </el-breadcrumb>
          <budget-table :budgetForm="budgetForm" :projectForm="projectForm" @getTotal="getTotalBudget"></budget-table>
        </div>
        <div class="finish" v-show="activeStep == 4">
          <el-result icon="success" title="成功提示" subTitle="预算表生成完成">
            <template slot="extra"> </template>
          </el-result>
        </div>
        <el-divider></el-divider>
        <div class="btn">
          <el-button @click="activeStep -= 1" :disabled="activeStep == 0 || activeStep == 4">上一步</el-button>
          <el-button @click="confirmStep" type="primary" v-if="activeStep < 4">下一步</el-button>
          <el-button @click="submitComplete" type="primary" v-if="activeStep == 4">提交流程</el-button>
        </div>
      </div>

      <!-- 项目选择对话框 -->
      <el-dialog title="选择项目" :visible.sync="openProject" width="700px" append-to-body>
        <el-form :inline="true">
          <el-form-item label="项目编号" prop="projectNumber">
            <el-input v-model="queryParams.projectNumber" placeholder="请输入项目编号" clearable
              @keyup.enter.native="getProjectList" />
          </el-form-item>
          <el-form-item style="margin-bottom: 0; display: none">
            <el-input></el-input>
          </el-form-item>

          <el-form-item>
            <el-button @click="getProjectList" type="primary">搜索</el-button>
          </el-form-item>
        </el-form>
        <el-table :data="projectList" style="margin-top: 30px" height="600px">
          <el-table-column type="index" width="50"> </el-table-column>
          <el-table-column prop="isFinshed" label="状态" width="90px">
            <template slot-scope="scope">
              <el-tag :type="scope.row.isFinished === '0' ? 'success' : 'warning'" disable-transitions>
                {{ scope.row.isFinished == "0" ? "进行中" : "已结束" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="项目编号" align="center" key="projectNumber" prop="projectNumber" />
          <el-table-column label="项目名称" align="center" key="projectName" prop="projectName" width="200px" />
          <el-table-column label="项目负责人" align="center" key="projectLeader" prop="projectLeaderUser.nickName" />
          <el-table-column align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="chooseProject(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: right">
          <el-pagination @current-change="getProjectList" :current-page.sync="queryParams.pageNum"
            :page-size="queryParams.pageSize" layout="total, prev, pager, next" :total="projectTotal">
          </el-pagination>
        </div>
      </el-dialog>
      <!-- 选择人员对话框 -->
      <el-dialog title="选择人员" :visible.sync="openPeople" width="700px" append-to-body>
        <choosePeople @chooseUser="getChooseUser"></choosePeople>
      </el-dialog>
      <!-- 选择车辆对话框 -->
      <el-dialog title="选择车辆" :visible.sync="openCar" width="700px" append-to-body>
        <chooseCar @chooseList="getChooseCar"></chooseCar>
      </el-dialog>
      <!-- 选择设备对话框 -->
      <el-dialog title="选择设备" :visible.sync="openDevice" width="750px" append-to-body>
        <chooseDevice @chooseList="getChooseDevice"></chooseDevice>
      </el-dialog>
    </div>
    <!-- <div v-if="taskName != '预算编制'">
      <budgetForm></budgetForm>
    </div> -->
  </div>
</template>

<script>
import { listProjectContract, addProjectContract } from "@/api/oa/contract/projectContract";
import { listContract, getContract, delContract, addContract, updateContract } from "@/api/oa/contract/contract";
import { getProject } from "@/api/oa/project/project";
import { listProjectWork } from "@/api/oa/project/projectWork";
import { getSalary } from "@/api/oa/staff/salary";
import choosePeople from "./components/choosePeople.vue";
import chooseCar from "./components/chooseCar.vue";
import chooseDevice from "./components/chooseDevice.vue";
import chooseMoney from "./components/chooseMoney.vue";
import budgetTable from "./components/budgetTable.vue";
import { listBudget, addBudget, updateBudget, delBudget } from "@/api/oa/budget/budget.js";
import { listBudgetStaff, addBudgetStaff, delBudgetStaff } from "@/api/oa/budget/budgetStaff.js";
import { listBudgetCar, addBudgetCar, delBudgetCar } from "@/api/oa/budget/budgetCar.js";
import { listBudgetDevice, addBudgetDevice, delBudgetDevice } from "@/api/oa/budget/budgetDevice.js";
import { listBudgetSettle, addBudgetSettle, delBudgetSettle } from "@/api/oa/budget/budgetSettle.js";
import { Snowflake } from "@/utils/snowFlake.js";
import budgetForm from "./components/budgetForm.vue";
import { flowRecordFull } from "@/api/flowable/finished";
import {
  complete,
  rejectTask,
  returnList,
  returnTask,
  getNextFlowNode,
  delegate,
  flowTaskForm,
} from "@/api/flowable/todo";
import { getUsersDeptLeaderByDept, getUsersManageLeaderByDept } from "@/api/system/post";
export default {
  components: {
    choosePeople,
    chooseCar,
    chooseDevice,
    chooseMoney,
    budgetTable,
    budgetForm,
  },
  props: {
    taskForm: {
      type: Object,
      require: true,
    },
    taskName: {
      type: String,
      require: true,
    },
  },
  data() {
    return {
      activeStep: 0,
      budgetForm: {
        budgetId: new Snowflake(1n, 1n, 0n).nextId().toString(),
        projectId: null,
        staffCost: 0,
        carCost: 0,
        deviceCost: 0,
        fixCost: 0,
        outExpense: 0,
        businessExpense: 0,
        rentExpense: 0,
        taxExpense: 0,
        otherExpense: 0,
        directExpense: 0,
        totalBudget: 0,
        settleExpense: 0,
        compiler: "",
        auditor: "",
      }, // 预算表
      openProject: false,
      projectList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectNumber: "",
        projectLeader: "",
        projectLeaderName: undefined,
        projectName: "",
      },
      projectTotal: 0,
      projectForm: {
        projectRegistrantUser: {
          nickName: ''
        }
      },
      workList: [],
      projectRule: {
        projectNumber: [{ required: true, message: "请选择项目编号", trigger: "blur" }],
      },
      peopleForm: {},
      openPeople: false,
      chooseUser: [],
      carDeviceForm: {},
      openCar: false,
      openDevice: false,
      chooseCar: [],
      chooseDevice: [],
      contentList: [],
      contract: {},
      reBackDescription: "",
      flag: false,
    };
  },
  created() {
    this.getProjectList();
    this.getProjectContract();
    this.getProjectWorkList();
  },
  mounted() {
    this.initBudgetForm();
    this.getAlter();
  },
  methods: {
    getAlter() {
      const params = { procInsId: this.taskForm.procInsId, deployId: this.taskForm.deployId }
      flowRecordFull(params).then(res => {
        if (res.data.flowList) {
          if (res.data.flowList.length > 1 && res.data.flowList[1].comment && res.data.flowList[1].comment.type == '退回意见') {
            this.reBackDescription = res.data.flowList[1].comment.type + '：' + res.data.flowList[1].comment.comment
          }
        }
      })
    },
    // 初始化预算表，先从后台查询是否有数据
    initBudgetForm() {
      listBudget({ pageNum: 1, pageSize: 20, projectId: this.taskForm.formId }).then(res => {
        if (res.rows[0] && res.rows[0].budgetId) {
          this.flag = true
          this.budgetForm = res.rows[0];
          const budgetId = res.rows[0].budgetId
          return Promise.all([
            listBudgetCar({ budgetId }),
            listBudgetDevice({ budgetId }),
            listBudgetSettle({ budgetId }),
            listBudgetStaff({ budgetId }),
          ]);
        }
        return Promise.resolve([])
      }).then(responses => {
        const [response1 = null, response2 = null, response3 = null, response4 = null] = responses;
        if (response1 && response1.rows) {
          this.chooseCar = response1.rows
          for (let car of this.chooseCar) {
            car.licensePlate = car.car.licensePlate
            car.dayCost = car.car.dayCost
            car.brand = car.car.brand
          }
        }
        if (response2 && response2.rows) {
          this.chooseDevice = response2.rows;
          for (let device of this.chooseDevice) {
            device.brand = device.device.brand
            device.dayCost = device.device.dayCost
            device.name = device.device.name
            device.series = device.device.series
          }
        }
        if (response3 && response3.rows) {
          this.contentList = response3.rows;
        }
        if (response4 && response4.rows) {
          this.chooseUser = response4.rows;
          for (let user of this.chooseUser) {
            user.nickName = this.getUserName(user.userId)
            user.deptName = this.getDeptName(user.user.deptId)
          }
        }
      })

    },
    goBack() {
      let obj = { path: "/budget/add" };
      this.$tab.closeOpenPage(obj);
      this.$router.push({ path: "/budget" });
    },
    // 查询项目列表
    getProjectList() {
      getProject(this.$route.query.formId).then(response => {
        this.projectForm = response.data;
      });
    },
    // 查询项目是否有合同关联
    getProjectContract() {
      listProjectContract({ projectId: this.taskForm.formId }).then(res => {
        if (res.rows) {
          if (res.rows.length == 1) {
            getContract(res.rows[0].contractId).then(result => {
              if (result.data) {
                this.contract = result.data;
                this.budgetForm.contract = result.data;
              }
            })
          }
        }
      })
    },
    getProjectWorkList() {
      listProjectWork({ projectId: this.$route.query.formId }).then(res => {
        this.workList = res.rows;
      })
    },
    // 选择项目
    chooseProject(row) {
      this.projectForm = row;
      this.budgetForm.projectId = row.projectId;
      this.openProject = false;
    },
    confirmStep() {
      if (this.activeStep == 0) {
        if (this.projectForm.projectNumber == undefined) {
          this.activeStep = 0;
          this.$message.error(`请选择项目编号！`);
        } else {
          this.activeStep += 1;
        }
      } else if (this.activeStep == 2) {
        this.budgetForm.chooseUser = this.chooseUser;
        this.budgetForm.chooseCar = this.chooseCar;
        this.budgetForm.chooseDevice = this.chooseDevice;
        this.budgetForm.projectId = this.projectForm.projectId;
        this.activeStep += 1;
        this.calculateThatCost();
      } else if (this.activeStep == 3) {
        if (this.flag) {
          this.updateBudgetForm(this.budgetForm)
        } else {
          this.addBudgetForm(this.budgetForm);
        }
        this.activeStep += 1;
      } else {
        this.activeStep += 1;
      }
    },
    getChooseUser(val) {
      this.chooseUser = val;
      this.openPeople = false;
    },
    getChooseCar(val) {
      this.chooseCar = val;
      for (let car of this.chooseCar) {
        car.mileage = 1.5
      }
      this.openCar = false;
    },
    getChooseDevice(val) {
      this.chooseDevice = val;
      this.openDevice = false;
    },
    getUserSalary(userId) {
      getSalary(userId).then(res => {
        return res.data.salary;
      });
    },
    getSettle(val) {
      this.budgetForm.settleExpense = val.settle;
      this.budgetForm.workList = val.workList;
      this.budgetForm.inOutPriceSum = val.inOutPriceSum
      if (this.chooseUser.length != 0) {
        for (let s of this.chooseUser) {
          s.inOutPrice = val.inOutPrice
        }
      }
      this.getDirectExpense(this.budgetForm);
    },
    setPreSettlement(val) {
      this.budgetForm.contentList = val
    },
    // 计算单个人员的成本
    calculateUserTotal(user) {
      let total = parseFloat((user.salary.salary + 1780) / 21.75).toFixed(2) * Number(user.days);
      this.$set(user, "staffCost", total.toFixed(2));
      this.getCost("staffCost", "staffCost", this.chooseUser);
      this.getFixCost();
    },
    calculateCarTotal(car) {
      let total1 = Number(car.mileage) * Number(car.distance);
      let total2 = Number(car.dayCost) * Number(car.days);
      let sum = (total1 + total2).toFixed(2);
      this.$set(car, "depreciation", total2.toFixed(2));
      this.$set(car, "expense", sum);
      this.getCost("expense", "carCost", this.chooseCar);
      this.getFixCost();
    },
    calculateDeviceTotal(device) {
      let total = Number(device.dayCost) * Number(device.days);
      this.$set(device, "depreciation", total.toFixed(2));
      this.getCost("depreciation", "deviceCost", this.chooseDevice);
      this.getFixCost();
    },
    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);
    },
    // 获取直接成本
    getDirectExpense(form) {
      let sum =
        Number(form.settleExpense) +
        Number(form.outExpense) +
        Number(form.rentExpense) +
        Number(form.taxExpense) +
        Number(form.businessExpense) +
        Number(form.otherExpense);
      this.budgetForm.directExpense = sum.toFixed(2);
    },
    getTotalBudget(val) {
      this.budgetForm.totalBudget = val;
    },
    addBudgetForm(form) {
      addBudget(form);
      for (let user of form.chooseUser) {
        user.budgetId = form.budgetId;
        addBudgetStaff(user);
      }
      for (let car of form.chooseCar) {
        car.budgetId = form.budgetId;
        addBudgetCar(car);
      }
      for (let device of form.chooseDevice) {
        device.budgetId = form.budgetId;
        addBudgetDevice(device);
      }
      for (let work of form.contentList) {
        work.budgetId = form.budgetId;
        addBudgetSettle(work).then(res => {
          this.$message.success('预算添加成功')
        })
      }
    },
    updateBudgetForm(form) {
      updateBudget(form);
      delBudgetStaff(form.budgetId).then(res => {
        for (let user of form.chooseUser) {
          addBudgetStaff(user);
        }
      });
      delBudgetCar(form.budgetId).then(res => {
        for (let car of form.chooseCar) {
          addBudgetCar(car);
        }
      })
      delBudgetDevice(form.budgetId).then(res => {
        for (let device of form.chooseDevice) {
          addBudgetDevice(device);
        }
      })
      delBudgetSettle(form.budgetId).then(res => {
        for (let work of form.contentList) {
          addBudgetSettle(work)
        }
        this.$message.success('预算添加成功')
      })
    },
    calculateThatCost() {
      let staffCost = 0;
      let carCost = 0;
      let deviceCost = 0;
      for (let user of this.chooseUser) {
        staffCost = staffCost + Number(user.staffCost);
      }
      for (let car of this.chooseCar) {
        carCost = carCost + Number(car.expense);
      }
      for (let device of this.chooseDevice) {
        deviceCost = deviceCost + Number(device.depreciation);
      }
      this.budgetForm.staffCost = staffCost;
      this.budgetForm.carCost = carCost;
      this.budgetForm.deviceCost = deviceCost;
    },
    async submitComplete() {
      const params = { taskId: this.taskForm.taskId };
      const deptIdsStr = this.projectForm.undertakingDept;
      const deptIdsArr = (deptIdsStr.split(',')).map(Number);
      let approvalList = []
      for (let deptId of deptIdsArr) {
        let res = await getUsersManageLeaderByDept({ deptId })
        if (res.code == 200 && res.data) {
          res.data.forEach(element => {
            approvalList.push(element.userId)
          });
        }
      }
      this.$set(this.taskForm.variables, "approvalList", approvalList); //得到各部门的分管领导列表
      // 提交到下一个流程
      getNextFlowNode(params).then(res => {
        complete(this.taskForm).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.$emit("goBack");
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.header {
  background-color: #fff;
  height: 110px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #ebeef5;

  .back {
    margin-left: 30px;
    flex: 1;
  }

  .title {
    text-align: left;
    flex: 24;
    padding-left: 40px;

    .title-text {
      font-size: 20px;
      font-weight: 700;
    }

    .title-tips {
      font-size: 14px;
      color: #5a5a5a;
    }
  }
}

.add-main {
  padding: 20px;

  .project {
    padding-top: 50px;
    width: 1000px;
    margin: 0 auto;
  }

  .staff,
  .finish {
    width: 1200px;
    margin: 0 auto;
    padding-top: 50px;
  }

  .other {
    padding-top: 50px;
  }
}

.btn {
  margin-top: 20px;
  text-align: center;
}

table {
  width: 100%;
  /*居中*/
  // margin: 0 auto;
  /*边框*/
  /* border: 1px solid black; */
  text-align: center;
  border-collapse: collapse;

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

.head {
  font-weight: bold;
}

::v-deep .el-input.is-disabled .el-input__inner {
  background-color: #fff;
  color: #5a5a5a;
}
</style>
