<!--
 * @Author: ysh
 * @Date: 2024-06-21 18:51:51
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-01-23 14:02:18
-->
<template>
  <div class="app-container">
    <h2 class="text-center">项目直接生产成本预算表</h2>
    <p style="text-align: center;">编制人：{{ $store.getters.name }}</p>
    <el-divider></el-divider>
    <div class="mt20 mb20" v-if="showAlter">
      <el-alert title="任务被退回，请修改后重新提交" type="error" :closable="false">
        <return-comment :taskForm="taskForm" @isReturn="isReturn"></return-comment>
      </el-alert>
    </div>
    <el-descriptions title="项目信息" labelClassName="mylabel">
      <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="项目类型">{{ project.projectType }}</el-descriptions-item>
      <el-descriptions-item label="承担部门">{{ getDeptNames(project.undertakingDept) }}</el-descriptions-item>
      <el-descriptions-item label="甲方单位">{{ project.partyA ? project.partyA.partyAName : "" }}</el-descriptions-item>
    </el-descriptions>
    <el-divider><b>间接成本</b></el-divider>
    <!-- 选择人员 -->
    <people-table ref="peopleRef" :budgetId="budgetForm.budgetId" @chooseUser="getChooseUser"
      @staffCost="getStaffCost"></people-table>
    <!-- 选择车辆 -->
    <car-table ref="carRef" :budgetId="budgetForm.budgetId" @chooseCar="getChooseCar" @carCost="getCarCost"></car-table>
    <!-- 选择设备 -->
    <device-table ref="deviceRef" :budgetId="budgetForm.budgetId" @chooseDevice="getChooseDevice"
      @deviceCost="getDeviceCost"></device-table>
    <!-- 分割线 -->
    <el-divider><b>直接成本</b></el-divider>
    <!-- 预结算 -->
    <money-table ref="moneyRef" :projectId="this.taskForm.formId" :budgetId="budgetForm.budgetId"
      @settleExpense="getSettleExpense" @contentList="getContentList"></money-table>
    <!-- 其他成本 -->
    <other-table ref="otherRef" @otherCost="getOtherCost" :budgetForm="budgetForm"></other-table>
    <!-- 预算备注 -->
    <el-form :model="budgetForm" style="padding: 20px 100px 0">
      <el-form-item label="预算表单备注" label-width="100px">
        <el-input type="textarea" v-model="budgetForm.remark" placeholder="请输入预算备注" :rows="4"></el-input>
      </el-form-item>
    </el-form>
    <!-- 统计 -->
    <div class="text-center">
      <el-tag class="ml10 mr10" type="success">间接成本：{{ isNaN(budgetForm.fixCost) ? 0 : budgetForm.fixCost }}</el-tag>
      <el-tag class="ml10 mr10">直接成本：{{ isNaN(budgetForm.directExpense) ? 0 : budgetForm.directExpense }}</el-tag>
      <el-tag class="ml10 mr10" type="danger">预算总成本：{{ isNaN(budgetForm.totalBudget) ? 0 : budgetForm.totalBudget
        }}</el-tag>
    </div>
    <div class="mt20 text-center" style="color:#909399;font-size:12px;">
      tips:预览表单，请先保存之后刷新再查看
    </div>
    <el-divider></el-divider>
    <div style="text-align: center">
      <el-button type="warning" @click="preserve()">保存</el-button>
      <el-button type="success" @click="viewForm()">预览表单</el-button>
      <el-button type="primary" @click="submitNextFlow" v-if="taskName != '预算批准'">提交下一个流程</el-button>
      <el-button type="primary" @click="submitNextFlow" v-else>结算批准</el-button>
    </div>
    <el-dialog title="表单预览" :visible.sync="viewOpen" width="60%" append-to-body>
      <budget-info :taskName="taskName" :taskForm="taskForm" @goBack="$emit('goBack')"></budget-info>
    </el-dialog>
  </div>
</template>

<script>
import { Snowflake } from "@/utils/snowFlake.js";
import { getProject } from "@/api/oa/project/project";
import { listBudget, addBudget, updateBudget, delBudget } from "@/api/oa/budget/budget.js";
import { listBudgetCar, addBudgetCar, delBudgetCar } from "@/api/oa/budget/budgetCar.js";
import { listBudgetStaff, addBudgetStaff, delBudgetStaff } from "@/api/oa/budget/budgetStaff.js";
import { listBudgetDevice, addBudgetDevice, delBudgetDevice } from "@/api/oa/budget/budgetDevice.js";
import { listBudgetSettle, addBudgetSettle, delBudgetSettle } from "@/api/oa/budget/budgetSettle.js";
import { getUsersDeptLeaderByDept, getUsersManageLeaderByDept } from "@/api/system/post";
import { complete, getNextFlowNode } from "@/api/flowable/todo";
import budgetInfo from "./budgetInfo.vue";
import ReturnComment from '@/views/flowable/form/components/flowBtn/returnComment.vue';
import ReturnBtn from '@/views/flowable/form/components/flowBtn/returnBtn.vue';
import CarTable from './carTable.vue';
import MoneyTable from './moneyTable.vue';
import PeopleTable from "./staffTable.vue";
import DeviceTable from './deviceTable.vue';
import OtherTable from './otherTable.vue';
export default {
  components: {
    ReturnComment,
    ReturnBtn,
    PeopleTable,
    CarTable,
    DeviceTable,
    MoneyTable,
    OtherTable,
    budgetInfo
  },
  data() {
    return {
      budgetForm: {
        budgetId: new Snowflake(1n, 1n, 0n).nextId().toString(),
        projectId: '',
        fixCost: 0,
        directExpense: 0,
        totalBudget: 0,
      },
      flag: false,
      project: {},
      showAlter: true,
      returnOpen: false,
      viewOpen: false,
    }
  },
  props: {
    taskForm: {
      type: Object,
      require: true,
    },
    taskName: {
      type: String,
      require: true,
    },
  },
  watch: {
    budgetForm: {
      handler(newVal) {
        if (newVal) {
          this.getFixCost();
          this.getDirectExpense();
          this.getTotalBudget();
        }
      },
      immediate: true, // 立即生效
      deep: true  //监听对象或数组的时候，要用到深度监听
    }
  },
  created() {
    this.getProjectInfo();
    this.initBudgetForm();
  },
  methods: {
    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];
          this.budgetId = res.rows[0].budgetId
        } else {
          this.flag = false
          this.budgetForm.projectId = this.taskForm.formId

        }
      })
    },
    getProjectInfo() {
      getProject(this.taskForm.formId).then(response => {
        this.project = response.data;
      });
    },
    // 保存
    preserve() {
      if (!this.flag) {
        this.addBudgetForm(this.budgetForm)
        this.flag = true;
      } else {
        this.updateBudgetForm(this.budgetForm)
      }
    },
    viewForm() {
      this.viewOpen = true;
    },
    // 提交下一个流程
    async submitNextFlow() {
      if (this.taskName == '预算编制') {
        this.preserve();
      }
      const params = { taskId: this.taskForm.taskId };
      const deptIdsStr = this.project.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");
        });
      });
    },
    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) {
          user.budgetId = form.budgetId;
          addBudgetStaff(user);
        }
      });
      delBudgetCar(form.budgetId).then(res => {
        for (let car of form.chooseCar) {
          car.budgetId = form.budgetId;
          addBudgetCar(car);
        }
      })
      delBudgetDevice(form.budgetId).then(res => {
        for (let device of form.chooseDevice) {
          device.budgetId = form.budgetId;
          addBudgetDevice(device);
        }
      })
      delBudgetSettle(form.budgetId).then(res => {
        for (let work of form.contentList) {
          work.budgetId = form.budgetId;
          addBudgetSettle(work)
        }
        this.$message.success('预算添加成功')
      })
    },
    getChooseUser(val) {
      this.$set(this.budgetForm, 'chooseUser', val);
    },
    getStaffCost(val) {
      this.$set(this.budgetForm, 'staffCost', val);
    },
    getChooseCar(val) {
      this.$set(this.budgetForm, 'chooseCar', val);
    },
    getCarCost(val) {
      this.$set(this.budgetForm, 'carCost', val);
    },
    getChooseDevice(val) {
      this.$set(this.budgetForm, 'chooseDevice', val);
    },
    getDeviceCost(val) {
      this.$set(this.budgetForm, 'deviceCost', val);
    },
    getContentList(val) {
      this.$set(this.budgetForm, 'contentList', val);
    },
    getSettleExpense(val) {
      this.$set(this.budgetForm, 'settleExpense', val);
    },
    getOtherCost(val) {
      this.$set(this.budgetForm, 'outExpense', val.outExpense);
      this.$set(this.budgetForm, 'rentExpense', val.rentExpense);
      this.$set(this.budgetForm, 'otherExpense', val.otherExpense);
      this.$set(this.budgetForm, 'taxExpense', val.taxExpense);
      this.$set(this.budgetForm, 'businessExpense', val.businessExpense);
    },
    getFixCost() {
      const staffCost = this.safeNumber(this.budgetForm.staffCost);
      const carCost = this.safeNumber(this.budgetForm.carCost);
      const deviceCost = this.safeNumber(this.budgetForm.deviceCost);
      const total = staffCost + carCost + deviceCost;
      this.budgetForm.fixCost = total.toFixed(2);
    },
    safeNumber(value) {
      const num = Number(value);
      return isNaN(num) ? 0 : num;
    },
    // 获取直接成本
    getDirectExpense() {
      const settleExpense = this.safeNumber(this.budgetForm.settleExpense);
      const outExpense = this.safeNumber(this.budgetForm.outExpense);
      const rentExpense = this.safeNumber(this.budgetForm.rentExpense);
      const taxExpense = this.safeNumber(this.budgetForm.taxExpense);
      const businessExpense = this.safeNumber(this.budgetForm.businessExpense);
      const otherExpense = this.safeNumber(this.budgetForm.otherExpense);
      const sum = settleExpense + outExpense + rentExpense + taxExpense + businessExpense + otherExpense;
      this.budgetForm.directExpense = sum.toFixed(2);
    },
    getTotalBudget() {
      this.budgetForm.totalBudget = (Number(this.budgetForm.fixCost) + Number(this.budgetForm.directExpense)).toFixed(2);
    },
    isReturn(val) {
      this.showAlter = val
    },
    commentByRole() {
      if (this.taskName == '分管审核') {
        return this.form.managerComment
      } else if (this.taskName == '总经理审批') {
        return this.form.gmComment
      }
    }
  },
}
</script>

<style lang="scss" scoped>
.mylabel {
  font-weight: bold;
}
</style>