<!--
 * @Author: ysh
 * @Date: 2024-04-30 09:03:14
 * @LastEditors: wrh
 * @LastEditTime: 2024-12-19 16:52:40
-->
<template>
  <div class="app-container" v-loading="loading">
    <el-row :gutter="20">
      <el-col :span="flowDisabled ? 19 : 24" :xs="24">
        <el-button type="success" icon="el-icon-printer" @click="printOpen = true">打印</el-button>
        <h2 class="text-center">其他结算表</h2>
        <div class="mt20 mb20" v-if="showAlter && flowDisabled">
          <el-alert title="任务被退回，请修改后重新提交" type="error" :closable="false">
            <return-comment :taskForm="taskForm" @isReturn="isReturn"></return-comment>
          </el-alert>
        </div>
        <div class="headers">
          项目信息
          <div class="line"></div>
        </div>
        <el-form ref="settleForm" :model="form" :rules="rules" label-width="160px" :disabled="disabled">
          <el-form-item label="其他项目名称" prop="xmName">
            <el-input v-model="form.xmName" placeholder="请输入其他项目名称" :disabled="taskName != '结算发起'" />
          </el-form-item>
          <el-form-item label="工作量上报说明" prop="workloadReport">
            <el-input v-model="form.workloadReport" type="textarea" :rows="4" :disabled="taskName != '结算发起'"
              placeholder="请输入工作量上报说明" />
          </el-form-item>
          <el-row>
            <el-col :span="6" :xs="24" :offset="12">
              <el-form-item label="工作上报人：" prop="reporterName">
                <span class="auditor">
                  {{ form.reporterName ? "" : getUserName(form.reporter) }}
                </span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="上报日期：" prop="reportTime">
                <span> {{ form.reportTime }} </span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="原始上报数据" prop="">
            <FileUpload v-if="taskName == '结算发起'" :limit="1" :filePathName="'其他结算/原始数据'"
              :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']" @input="setSettleDocument">
            </FileUpload>
            <div v-if="form.settleDocument" class="upload-list">
              <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + form.settleDocument}`)">
                {{ getFileName(form.settleDocument) }}
              </el-link>
              <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + form.settleDocument}`"
                :underline="false" target="_blank">
                <span class="el-icon-download">下载文件</span>
              </el-link>
            </div>
          </el-form-item>
          <el-form-item label="分管领导审核结算单" prop="">
            <FileUpload v-if="taskName == '分管审核'" :limit="1" :filePathName="'其他结算/分管领导审核结算单'"
              :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']" @input="setFinalDocument">
            </FileUpload>
            <div v-if="form.finalDocument" class="upload-list">
              <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + form.finalDocument}`)">
                {{ getFileName(form.finalDocument) }}
              </el-link>
              <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + form.finalDocument}`"
                :underline="false" target="_blank">
                <span class="el-icon-download">下载文件</span>
              </el-link>
            </div>
          </el-form-item>
          <div class="headers">
            项目完成工作量及经费计算
            <div class="line"></div>
          </div>
          <el-form-item label-width="60px">
            <table border="1">
              <tr>
                <td style="width: 50px">序号</td>
                <td style="width: 180px">工作内容</td>
                <td style="width: 100px">等级或比例尺</td>
                <td style="width: 100px">单位</td>
                <td style="width: 100px">地类</td>
                <td style="width: 100px">单价</td>
                <td>工作量</td>
                <td style="width: 117px">其他系数</td>
                <td style="width: 100px">项目经费</td>
                <td>备注</td>
                <td>操作</td>
              </tr>
              <tr v-for="(work, index) in settleWorkList" :key="index">
                <td>
                  {{ index + 1 }}
                </td>
                <td>
              <tr>
                <td>
                  <el-button size="mini" type="primary" icon="el-icon-plus" :disabled="isModify"
                    @click="handleChoosePrice(work, index)">选择工作内容</el-button>
                </td>
              </tr>
              <tr>
                <td>
                  <el-input v-model="work.content" type="textarea" clearable :autosize="{ minRows: 4, maxRows: 10 }"
                    :disabled="isModify"></el-input>
                </td>
              </tr>
              </td>
              <td>
                {{ work.scale == "" ? "无" : work.scale }}
              </td>
              <td>
                {{ work.unit }}
              </td>
              <td>
                {{ work.groundType == "0" ? "一般地类" : "复杂地类" }}
              </td>
              <td>
                {{ work.price }}
              </td>
              <td>
                <el-input-number :precision="2" style="width: 100px" v-model="work.workload" clearable
                  :disabled="isModify" @blur="calculateSettle(work)" :controls="false"></el-input-number>
              </td>
              <td>
                <div style="display: flex">
                  <el-input-number :precision="2" style="width: 100px" v-model="work.coefficient" clearable
                    :disabled="isModify" @blur="calculateSettle(work)" :controls="false"></el-input-number>
                  <el-popover placement="top-start" title="系数备注" width="200" trigger="click">
                    <div v-html="work.noteTip"></div>
                    <i class="el-icon-info" slot="reference" @click="getCoefficientRemark(work, work.workType)"></i>
                  </el-popover>
                </div>
              </td>
              <td>
                <!-- <el-input-number style="width:100px" v-model="work.settle" clearable :controls="false"></el-input-number> -->
                {{ work.settle }}
              </td>
              <td>
                <el-input v-model="work.remark" type="textarea" clearable :disabled="isModify"
                  :autosize="{ minRows: 4, maxRows: 10 }"></el-input>
              </td>
              <td>
                <el-button type="text" size="mini" style="color: #f56c6c"
                  @click="deletWorkItem(index, settleWorkList)">删除行</el-button>
              </td>
              </tr>
              <tr>
                <td :colspan="8">结算费用合计</td>
                <td>{{ settleSumTr.amount }}</td>
                <td>
                  <el-input v-model="settleSumTr.remark" type="textarea" clearable :disabled="isModify"
                    :autosize="{ minRows: 2, maxRows: 10 }"></el-input>
                </td>
              </tr>
            </table>
            <el-button icon="el-icon-plus" type="primary" plain size="mini" @click="addWorkList"></el-button>
          </el-form-item>

          <!-- 结算汇总 -->
          <div class="headers">
            结算汇总
            <div class="line"></div>
          </div>
          <el-form-item label-width="60px">
            <h3>表1：扣除明细</h3>
            <table border="1">
              <tr>
                <td style="width: 50px">序号</td>
                <td style="width: 280px">扣除内容</td>
                <td style="width: 200px">扣除金额（元）</td>
                <td style="width: 280px">备注</td>
                <td style="width: 100px">操作</td>
              </tr>
              <tr v-for="(  work, index  ) in settleSumList  " :key="index">
                <td>
                  {{ index + 1 }}
                </td>
                <td>
                  <el-input v-model="work.content" type="textarea" clearable :autosize="{ minRows: 2, maxRows: 10 }"
                    :disabled="isModify">
                  </el-input>
                </td>
                <td>
                  <el-input-number :min="0" :precision="2" style="width: 200px" v-model="work.amount" clearable
                    :disabled="isModify" :controls="false" @blur="calculateActualSumSettle()"></el-input-number>
                  <!-- {{ work.amount }} -->
                </td>
                <td>
                  <el-input v-model="work.remark" type="textarea" clearable :autosize="{ minRows: 2, maxRows: 10 }"
                    :disabled="isModify">
                  </el-input>
                </td>
                <td>
                  <el-button type="text" size="mini" style="color: #f56c6c"
                    @click="deletWorkItem(index, settleSumList)">删除行</el-button>
                </td>
              </tr>
            </table>
            <el-button icon="el-icon-plus" type="primary" plain size="mini" @click="addSumWorkList"></el-button>
            <h3>部门结算金额</h3>
            <table border="1">
              <tr>
                <td style="width: 150px">实际结算总金额（元）</td>
                <td style="width: 50px">序号</td>
                <td style="width: 280px">部门名称</td>
                <td style="width: 200px">结算金额（元）</td>
                <td style="width: 280px">备注</td>
                <td style="width: 100px">操作</td>
              </tr>
              <tr v-for="(  dept, index  ) in deptSettleList  " :key="index" v-if="dept.content != '实际结算总金额'">
                <td :rowspan="deptSettleList.length" v-if="index == 0">
                  {{ Number(actualSumSettle).toFixed(2) }}
                </td>
                <td>
                  {{ index + 1 }}
                </td>
                <td>
                  <!-- <el-input v-model="dept.content" type="textarea" clearable :autosize="{ minRows: 2, maxRows: 10 }">
                  </el-input> -->
                  <el-select v-model="dept.content" placeholder="请选择" filterable clearable style="width:100%;"
                    :disabled="isModify">
                    <el-option v-for="item in $store.state.user.deptList" :key="item.deptId" :label="item.deptName"
                      :value="item.deptName">
                    </el-option>
                  </el-select>
                </td>
                <td>
                  <el-input-number :precision="2" style="width: 200px" v-model="dept.amount" clearable :controls="false"
                    :disabled="isModify" @blur="calculateDeptAmount(index)"></el-input-number>
                </td>
                <td>
                  <el-input v-model="dept.remark" type="textarea" clearable :autosize="{ minRows: 2, maxRows: 10 }"
                    :disabled="isModify">
                  </el-input>
                </td>
                <td>
                  <el-button type="text" size="mini" style="color: #f56c6c"
                    @click="deletWorkItem(index, deptSettleList)">删除行</el-button>
                </td>
              </tr>
              <tr>
                <td :colspan="2">结算说明</td>
                <td :colspan="3">
                  <el-input v-model="form.settleComment" type="textarea" clearable placeholder="请输入说明"
                    :autosize="{ minRows: 2, maxRows: 10 }" :disabled="isModify">
                  </el-input>
                </td>
              </tr>
            </table>
            <el-button icon="el-icon-plus" type="primary" plain size="mini" @click="addDeptSettleList"></el-button>
          </el-form-item>

          <!-- 结算审核情况 -->
          <div v-if="taskName != '结算发起'">
            <div class="headers">
              结算审核情况
              <div class="line"></div>
            </div>
            <el-form-item label="分管领导(审核)">
              <el-input v-model="form.managerComment" type="textarea" :disabled="taskName != '分管审核'" clearable
                :autosize="{ minRows: 4, maxRows: 10 }">
              </el-input>
            </el-form-item>
            <el-row>
              <el-col :span="6" :xs="24" :offset="12">
                <el-form-item label="签名：" label-width="120px">
                  <span class="auditor"> {{ form.managerUserName ? form.managerUserName : getUserName(form.managerUserId) }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px">
                  <span> {{ form.managerTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="总经理(审批)">
              <el-input v-model="form.gmComment" type="textarea" :disabled="taskName != '总经理审批'" clearable
                :autosize="{ minRows: 4, maxRows: 10 }">
              </el-input>
            </el-form-item>
            <el-row>
              <el-col :span="6" :xs="24" :offset="12">
                <el-form-item label="签名：" label-width="120px">
                  <span class="auditor"> {{ form.gmUserName ? form.gmUserName : getUserName(form.gmUserId) }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px">
                  <span> {{ form.gmTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>

          </div>
        </el-form>
        <el-button type="success" icon="el-icon-printer" @click="printOpen = true">打印</el-button>
        <div style="text-align: center" v-if="!disabled">
          <el-button type="warning" @click="preserve">保存</el-button>
          <el-button type="danger" v-if="taskName != '结算发起'" @click="returnOpen = true">退 回</el-button>
          <el-button type="primary" @click="submitNextFlow" v-if="taskName != '总经理审批'">提交下一个流程</el-button>
          <el-button type="primary" @click="submitNextFlow" v-else>结算批准</el-button>
        </div>
      </el-col>
      <el-col :span="5" :xs="24" v-if="flowDisabled">
        <el-card>
          <h2 style="text-align: center">流程进度</h2>
          <div>
            <flow :flowData="flowData" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog title="结算表格预览" :visible.sync="printOpen" width="65%" append-to-body>
      <settle-print :form="form" :workList="settleWorkList" :settleList="oldSettleSumList"
        @cancel="printOpen = false"></settle-print>
    </el-dialog>
    <el-drawer title="选择单价" :visible.sync="drawer" direction="rtl">
      <choose-price :row="clickWork" @getPrice="getPrice" @cancel="drawer = false"></choose-price>
    </el-drawer>

    <el-dialog title="退回" :visible.sync="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 flow from "@/views/flowable/task/todo/detail/flow";
import { flowXmlAndNode } from "@/api/flowable/definition";
import { parseTime } from "@/utils/ruoyi";
import { deepClone } from "@/utils";
import { listSettle, getSettle, delSettle, addSettle, updateSettle } from "@/api/oa/settle/settle";
import { listSettleSummary, getSettleSummary, addSettleSummary, delSettleSummary, updateSettleSummary } from "@/api/oa/settle/settleSummary";
import { listSettleWork, getSettleWork, addSettleWork, updateSettleWork, delSettleWork } from "@/api/oa/settle/settleWork";
import { getPrice, getPriceRemarkByWorkType } from "@/api/oa/price/price";
import ChoosePrice from "./components/choosePrice.vue";
import { getUser } from "@/api/system/user";
import { getUserByRole } from "@/api/system/role";
import { getUserByPost } from "@/api/system/post";
import { complete, getNextFlowNode } from "@/api/flowable/todo";
import { getUsersDeptLeader, getUsersDeptLeaderByDept, getUsersManageLeaderByDept, } from "@/api/system/post.js";
import SettlePrint from "./components/print/settlePrint.vue";
import ReturnComment from '@/views/flowable/form/components/flowBtn/returnComment.vue';
import ReturnBtn from '@/views/flowable/form/components/flowBtn/returnBtn.vue';
export default {
  components: {
    flow,
    ChoosePrice,
    SettlePrint,
    ReturnComment,
    ReturnBtn
  },
  props: {
    taskName: {
      type: String,
      required: true,
    },
    taskForm: {
      type: Object,
      required: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    flowDisabled: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    'taskForm.formId'() {
      this.initForm();
    }
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      printOpen: false,
      loading: false,
      drawer: false,
      prOpen: false,
      flag: false,
      flowData: {},
      form: {},
      rules: {},
      isSelect: false,
      fileList: [],
      settleWorkList: [
        {
          content: "",
          priceId: "",
          scale: "无",
          unit: "",
          groundType: "0",
          price: "",
          workload: 0,
          coefficient: 1,
          settle: 0,
          remark: "",
        },
      ],
      oldSettleWorkList: [],
      settleSumTr: {
        content: "结算费用合计",
        amount: 0,
        remark: "",
        tableNumber: "2",
      },
      settleSumList: [
        {
          content: "",
          amount: 0,
          remark: "",
          tableNumber: "0",
        },
      ],
      deptSettleList: [
        {
          content: "",
          amount: 0,
          remark: "",
          tableNumber: "1",
        },
      ],
      oldSettleSumList: [],
      actualSumSettle: "",
      clickWork: {},
      deptId: undefined,
      deptList: [],
      isModify: false, //是否可以修改结算工作量
      showAlter: true,
      returnOpen: false,
    };
  },
  created() {
    this.initForm();
    if (this.flowDisabled)
      flowXmlAndNode({
        procInsId: this.taskForm.procInsId,
        deployId: this.taskForm.deployId,
      }).then((res) => {
        this.flowData = res.data;
      });
  },
  mounted() {
    this.isModify = this.taskName != '结算发起' && this.taskName != '分管审核'
  },
  methods: {
    // 初始化表单
    async initForm() {
      this.loading = true
      const res = await listSettle({ settleId: this.taskForm.formId });
      if (res.total === 1) {
        this.form = res.rows[0];
        this.flag = true;
        const settleId = this.taskForm.formId;
        const [
          settleWorkResponse,
          settleSummaryResponse
        ] = await Promise.all([
          listSettleWork({ settleId: settleId, pageSize: 30 }),
          listSettleSummary({ settleId, pageSize: 20 })
        ]);

        // 获取申请工作量列表
        if (settleWorkResponse) {
          this.settleWorkList = settleWorkResponse.rows;
          for (let work of this.settleWorkList) {
            getPrice(work.priceId).then((settleWorkResponse) => {
              if (settleWorkResponse.data) {
                this.setValue(work, "scale", settleWorkResponse.data.scaleGrade);
                this.setValue(work, "unit", settleWorkResponse.data.unit);
                if (work.groundType == "0") {
                  work.price = settleWorkResponse.data.commonPrice;
                } else {
                  work.price = settleWorkResponse.data.complexPrice;
                }
              }
            });
          }
        }
        // 结算汇总里的扣除明细以及部门结算金额
        if (settleSummaryResponse) {
          this.oldSettleSumList = settleSummaryResponse.rows;
          for (let s of settleSummaryResponse.rows) {
            if (s.content == "结算费用合计") {
              this.settleSumTr = s;
              break;
            }
          }
          this.settleSumList = settleSummaryResponse.rows.filter((item) => item.tableNumber == "0");
          this.deptSettleList = settleSummaryResponse.rows.filter(
            (item) => item.tableNumber == "1" && item.content != '实际结算总金额'
          );
          this.calculateActualSumSettle();
        }

        getUser(this.form.reporter).then((res) => {
          if (res.data) {
            this.deptId = res.data.deptId;
          }
        });
        this.getCurrentUser();
      } else if (res.total == 0) {
        this.flag = false;
        if (this.taskName == "结算发起") {
          this.form.reporter = this.$store.getters.userId;
          this.form.reportTime = parseTime(new Date(), "{y}-{m}-{d}");
          this.deptId = this.$store.getters.deptId;
        }
      }
      this.loading = false;
      this.deptList = this.$store.state.user.deptList
    },

    // 获取当前处理人
    getCurrentUser() {
      if (this.taskName == "分管审核") {
        this.form.managerUserName = this.$store.state.user.name;
        this.form.managerUserId = this.$store.state.user.id;
        this.form.managerTime = parseTime(new Date(), "{y}-{m}-{d}");
      } else if (this.taskName == "总经理审批") {
        this.form.gmUserName = this.$store.state.user.name;
        this.form.gmUserId = this.$store.state.user.id;
        this.form.gmTime = parseTime(new Date(), "{y}-{m}-{d}");
      }
    },
    // 保存按钮
    preserve() {
      this.$refs["settleForm"].validate((vaild) => {
        if (vaild) {
          if (this.flag) {
            this.updateSettleFn();
            this.updateSettleSummaryFn();
            this.updateSettleWorkFn();
            this.$message.success("保存成功");
          } else {
            this.addSettleFn();
            this.$message.success("保存成功");
          }
        } else {
          this.$message.error('请完善表单必填项')
        }
      });
    },
    submitNextFlow() {
      this.$refs["settleForm"].validate((vaild) => {
        if (vaild) {
          this.preserve();
          if (this.taskName == "结算发起") {
            this.getNextFlowNodeFn(null, this.deptId, true);
          } else if (this.taskName == "分管审核") {
            getUserByPost({ postName: "总经理" }).then((res) => {
              this.getNextFlowNodeFn(res.data[0].userId);
            });
          } else if (this.taskName == "总经理审批") {
            this.$modal.confirm('最后一个节点，提交将结束流程，是否提交？').then(() => {
              this.getNextFlowNodeFn();
            })
          }

        } else {
          this.$message.error('请完善表单必填项')
        }
      });
    },
    // 获取下一个节点  (下一个用户id,部门id,是否为会签)
    getNextFlowNodeFn(userId, deptId, isList) {
      const params = { taskId: this.taskForm.taskId };
      getNextFlowNode(params).then((res) => {
        if (userId) {
          this.$set(this.taskForm.variables, "approval", userId);
          this.handleComplete(this.taskForm);
        } else {
          if (deptId && isList) {
            getUsersManageLeaderByDept({ deptId }).then((res) => {
              let ids = [];
              res.data.forEach(user => {
                ids.push(user.userId)
              })
              this.$set(this.taskForm.variables, "approvalList", ids);
              this.handleComplete(this.taskForm);
            });
          } else if (deptId && !isList) {
            getUsersDeptLeaderByDept({ deptId }).then((res) => {
              this.$set(this.taskForm.variables, "approval", res.data.userId);
              this.handleComplete(this.taskForm);
            });
          } else {
            this.handleComplete(this.taskForm);
          }
        }
      });
    },
    handleComplete(taskForm) {
      complete(taskForm).then(response => {
        this.$modal.msgSuccess(response.msg);
        this.$emit('goBack');
      })
    },
    isEmptyObject(obj) {
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          return false;
        }
      }
      return true;
    },
    addWorkList() {
      this.settleWorkList.push({
        content: "",
        priceId: "",
        scale: "",
        unit: "",
        groundType: "0",
        price: "",
        workload: 0,
        coefficient: 1,
        settle: 0,
        remark: "",
      });
    },
    addSumWorkList() {
      this.settleSumList.push({
        content: "",
        amount: 0,
        remark: "",
        tableNumber: "0",
      });
    },
    addDeptSettleList() {
      this.deptSettleList.push({
        content: "",
        amount: 0,
        remark: "",
        tableNumber: "1",
      });
    },
    deletWorkItem(index, arr) {
      // let arr = this.settleWorkList;
      if (arr.length == 1) {
        return;
      }
      if (index >= 0 && index < arr.length) {
        arr.splice(index, 1);
      }
      this.calculateSumSettle();
      this.calculateActualSumSettle();
    },
    calculateSettle(work) {
      let sum = work.workload * work.coefficient * work.price;
      // if (sum < 600 && sum != 0 && work.priceId != 147) {
      //   this.$message.warning('不足600，按600算')
      //   work.remark = '不足600，按600算'
      //   sum = 600
      // }
      // else {
      //   work.remark = ''
      // }
      work.settle = Number(sum).toFixed(2);
      this.calculateSumSettle();
      this.calculateActualSumSettle();
    },
    // 置为600
    setSettle(work){
      work.settle = 600;
      this.calculateSumSettle();
      this.calculateActualSumSettle();
    },
    resetSettle(work){
      this.calculateSettle(work)
    },
    calculateSumSettle() {
      let sum = 0;
      let arr = this.settleWorkList;
      for (let a of arr) {
        sum = sum + Number(a.settle);
      }
      this.settleSumTr.amount = sum.toFixed(2);
    },
    calculateActualSumSettle() {
      let sum = 0;
      let arr = this.settleSumList;
      for (let a of arr) {
        sum = sum + Number(a.amount);
      }
      this.actualSumSettle = Number(this.settleSumTr.amount) - sum;
      if (this.deptSettleList.length == 1)
        this.deptSettleList[0].amount = this.actualSumSettle;
    },
    calculateDeptAmount(index) {
      let num = 0;
      let len = this.deptSettleList.length;
      if (len > 1) {
        if (index == len - 1) {
          for (let i = 0; i < index; i++) {
            num = num + this.deptSettleList[i].amount;
          }
          this.deptSettleList[index].amount = this.actualSumSettle - num;
        }
      }
    },
    handleChoosePrice(work, index) {
      this.clickWork = work;
      this.clickWork.index = index;
      this.drawer = true;
    },
    getPrice(val) {
      let index = this.clickWork.index;
      this.setValue(this.settleWorkList[index], "workType", val.workType);
      this.setValue(this.settleWorkList[index], "scale", val.scaleGrade);
      this.setValue(this.settleWorkList[index], "unit", val.unit);
      this.setValue(this.settleWorkList[index], "groundType", val.groundType);
      this.setValue(this.settleWorkList[index], "price", val.price);
      this.setValue(this.settleWorkList[index], "priceId", val.priceId);
      this.setValue(this.settleWorkList[index], "content", val.content);
      this.calculateSettle(this.settleWorkList[index]);
      this.drawer = false;
    },
    setValue(key, name, val) {
      this.$set(key, name, val);
    },

    // 增加数据
    addSettleFn() {
      let settleId = this.taskForm.formId;
      this.form.settleId = settleId;
      getSettle(this.taskForm.formId).then((res) => {
        if (res.data) {
          updateSettle(this.form);
          this.updateSettleWorkFn(settleId);
          this.updateSettleSummaryFn(settleId);
        } else {
          addSettle(this.form).then((res) => {
            this.addSettleWorkFn(settleId);
            this.addSettleSummaryFn(settleId);
          });
        }
      });
    },
    async addSettleWorkFn(settleId) {
      for (let work of this.settleWorkList) {
        work.settleId = settleId;
        await addSettleWork(work);
      }
    },
    async addSettleSummaryFn(settleId) {
      this.settleSumTr.settleId = settleId;
      await addSettleSummary(this.settleSumTr);
      for (let item of this.settleSumList) {
        item.settleId = settleId;
        await addSettleSummary(item);
      }
      for (let item of this.deptSettleList) {
        item.settleId = settleId;
        await addSettleSummary(item);
      }
      let obj = { settleId: settleId, content: '实际结算总金额', amount: (this.actualSumSettle).toFixed(2), tableNumber: 1 }
      await addSettleSummary(obj)
    },

    // 更新数据
    updateSettleFn() {
      updateSettle(this.form);
    },
    updateSettleWorkFn() {
      delSettleWork([this.taskForm.formId]).then((res) => {
        this.addSettleWorkFn(this.taskForm.formId);
      });
    },
    updateSettleSummaryFn() {
      delSettleSummary([this.taskForm.formId]).then((res) => {
        this.addSettleSummaryFn(this.taskForm.formId);
      });
    },
    getFileName(name) {
      if (name) {
        let arr = name.split("/");
        return arr[arr.length - 1];
      }
    },
    setSettleDocument(val) {
      this.getDoc(val, "settleDocument");
    },
    setModifyDocument(val) {
      this.getDoc(val, "modifyDocument");
    },
    setFinalDocument(val) {
      this.getDoc(val, "finalDocument");
    },
    getDoc(val, name) {
      if (val) {
        let arr = val.split("/upload");
        this.form[name] = arr[1];
        if (val == "") {
          this.form[name] = "";
        }
      }
    },
    // 获取系数备注
    getCoefficientRemark(work, workType) {
      getPriceRemarkByWorkType({ workType }).then((res) => {
        if (res.code == 200) {
          if (workType != undefined) this.$set(work, "noteTip", res.msg);
          // this.$notify({
          //   title: workType,
          //   dangerouslyUseHTMLString: true,
          //   message: res.msg,
          //   duration: 0
          // });
        }
      });
    },
    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>
@import "@/assets/styles/element-reset.scss";

.headers {
  position: relative;
  font-weight: bold;
  font-size: 18px;
  padding-left: 40px;
  padding-bottom: 40px;

  .line {
    position: absolute;
    left: 22px;
    top: 5px;
    width: 5px;
    height: 14px;
    border-radius: 10px;
    background-color: #2893e5;
  }
}

table {
  /*边框*/
  /* border: 1px solid black; */
  text-align: center;
  border-collapse: collapse;
  width: 100%;
  /*设置背景颜色*/
  /* background-color: #bfa; */
}

h3 {
  font-family: "黑体";
  font-weight: bold;
}
</style>
