<!--
 * @Author: ysh
 * @Date: 2024-04-30 09:03:14
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-06-07 10:00:28
-->
<template>
  <div class="app-container" v-loading="loading">
    <el-button type="warning" icon="el-icon-printer" @click="printOpen = true">打印</el-button>
    <el-dialog title="结算表格预览" :visible.sync="printOpen" width="65%" append-to-body>
      <settle-print :form="form" :chooseProject="chooseProject" :workList="settleWorkList"
        :settleList="oldSettleSumList" @cancel="printOpen = false"></settle-print>
    </el-dialog>
    <el-row :gutter="20">
      <el-col :span="19" :xs="24">
        <h2 class="text-center">项目结算表</h2>
        <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="projectId">
            <el-button icon="el-icon-plus" size="mini" type="primary" @click="prOpen = true">选择项目</el-button>
            <el-descriptions border v-if="isSelect" style="margin-top: 10px" :column="2">
              <el-descriptions-item label="项目编号" label-class-name="my-label">
                {{ chooseProject.projectNumber }}
              </el-descriptions-item>
              <el-descriptions-item label="项目名称" label-class-name="my-label">
                {{ chooseProject.projectName }}
              </el-descriptions-item>
              <el-descriptions-item label="合同编码" label-class-name="my-label">
                {{ chooseProject.contractCode }}
              </el-descriptions-item>
              <el-descriptions-item label="合同编号" label-class-name="my-label">
                {{ chooseProject.contractNumber }}
              </el-descriptions-item>
              <el-descriptions-item label="项目负责人" label-class-name="my-label">
                {{ chooseProject.projectLeaderUser ? chooseProject.projectLeaderUser.nickName : "" }}
              </el-descriptions-item>
              <el-descriptions-item label="甲方单位" label-class-name="my-label">
                {{ chooseProject.partyA }}
              </el-descriptions-item>
              <el-descriptions-item label="联系人" label-class-name="my-label">
                {{ chooseProject.contactPerson }}
              </el-descriptions-item>
              <el-descriptions-item label="联系电话" label-class-name="my-label">
                {{ chooseProject.telephone }}
              </el-descriptions-item>
              <el-descriptions-item label="项目类型" label-class-name="my-label">
                {{ chooseProject.projectType }}
              </el-descriptions-item>
              <el-descriptions-item label="项目级别" label-class-name="my-label">
                {{
    chooseProject.projectLevel == "0" ? " 一般项目" : "重大项目"
  }}
              </el-descriptions-item>
              <el-descriptions-item label="承担部门" label-class-name="my-label">
                {{ chooseProject.undertakingDeptName }}
              </el-descriptions-item>
              <el-descriptions-item label="项目登记人" label-class-name="my-label">
                {{ chooseProject.projectRegistrantUser ? chooseProject.projectRegistrantUser.nickName:"" }}
              </el-descriptions-item>
            </el-descriptions>
          </el-form-item>
          <el-form-item label="工作量上报说明" prop="workloadReport">
            <el-input v-model="form.workloadReport" type="textarea" :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 }}
                </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']" @input="setSettleDocument">
            </FileUpload>
            <div v-if="form.settleDocument && taskName != '结算发起'" class="upload-list">
              <!-- <el-link :href="`${baseUrl}${'/profile/upload' + form.settleDocument}`" :underline="false"
                target="_blank">
                <span class="el-icon-document" style="color: #00f">
                  {{ getFileName(form.settleDocument) }}
                </span>
              </el-link> -->
              <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']" @input="setModifyDocument">
            </FileUpload>
            <div v-if="taskName != '项目管理部结算' && form.modifyDocument" class="upload-list">
              <el-link :href="`${baseUrl}${'/profile/upload' + form.modifyDocument}`" :underline="false"
                target="_blank">
                <span class="el-icon-document" style="color: #00f">
                  {{ getFileName(form.modifyDocument) }}
                </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']" @input="setFinalDocument">
            </FileUpload>
            <div v-if="taskName != '分管审核' && form.finalDocument" class="upload-list">
              <el-link :href="`${baseUrl}${'/profile/upload' + form.finalDocument}`" :underline="false" target="_blank">
                <span class="el-icon-document" style="color: #00f">
                  {{ getFileName(form.finalDocument) }}
                </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"
                    @click="handleChoosePrice(work, index)">选择工作内容</el-button>
                </td>
              </tr>
              <tr>
                <td>
                  <el-input v-model="work.content" type="textarea" clearable
                    :autosize="{ minRows: 4, maxRows: 10 }"></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
                  @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
                    @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
                  :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
                    :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 }">
                  </el-input>
                </td>
                <td>
                  <el-input-number :min="0" :precision="2" style="width: 200px" v-model="work.amount" clearable
                    :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 }">
                  </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>表2：部门结算金额</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">
                <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%;">
                    <el-option v-for="item in 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"
                    @blur="calculateDeptAmount(index)"></el-input-number>
                </td>
                <td>
                  <el-input v-model="dept.remark" type="textarea" clearable :autosize="{ minRows: 2, maxRows: 10 }">
                  </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 }">
                  </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.zhComment" 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.zhUserName }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px">
                  <span> {{ form.zhTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="技术质量部(质量及工作量)">
              <el-input v-model="form.jsComment" 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.jsUserName }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px">
                  <span> {{ form.jsTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="项目管理部(结算)">
              <el-input v-model="form.xmComment" 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.xmUserName }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px">
                  <span> {{ form.xmTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="项目承担部门(确认)">
              <el-input v-model="form.deptComment" 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.deptUserName }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px">
                  <span> {{ form.deptTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="经营发展部(校核)">
              <el-input v-model="form.jyComment" 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.jyUserName }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px">
                  <span> {{ form.jyTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
            <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 }} </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 }} </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>
        <div style="text-align: center" v-if="!disabled">
          <el-button type="warning" @click="preserve">保存</el-button>
          <el-button type="primary" @click="submitNextFlow">提交下一个流程</el-button>
        </div>
      </el-col>
      <el-col :span="5" :xs="24">
        <el-card>
          <h2 style="text-align: center">流程进度</h2>
          <div>
            <flow :flowData="flowData" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <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="prOpen" width="70%" append-to-body>
      <choose-project @chooseProject="confirmProject"></choose-project>
    </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 { listProject, getProject } from "@/api/oa/project/project";
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 {
  listProjectContract,
  addProjectContract,
} from "@/api/oa/contract/projectContract";
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/settlePrint.vue";
import { getDept } from "@/api/system/dept";
import { getContract } from "@/api/oa/contract/contract";
import ChooseProject from "./components/chooseProject.vue";
export default {
  components: {
    flow,
    ChoosePrice,
    SettlePrint,
    ChooseProject,
  },
  props: {
    taskName: {
      type: String,
      required: true,
    },
    taskForm: {
      type: Object,
      required: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  watch: {},
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      printOpen: false,
      loading: true,
      drawer: false,
      prOpen: false,
      flag: false,
      flowData: {},
      form: {},
      rules: {
        projectId: [
          { required: true, trigger: "change", message: "请选择项目编号" },
        ],
      },
      projectList: [],
      isSelect: false,
      chooseProject: {},
      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: []
    };
  },
  created() {
    this.getProjectList(); //获取项目列表
    this.getContractDataList(); //获取合同编码和编号
    this.initForm();

    flowXmlAndNode({
      procInsId: this.taskForm.procInsId,
      deployId: this.taskForm.deployId,
    }).then((res) => {
      this.flowData = res.data;
    });
  },
  mounted() {
    if (this.$route.query.projectId) {
      getProject(this.$route.query.projectId).then((res) => {
        if (res.data) {
          this.$set(this.form, "projectId", res.data.projectId);
          this.handleSelectProject(res.data.projectId);
        }
      });
    } else {
      this.handleSelectProject(this.form.projectId);
    }
  },
  methods: {
    // 初始化表单
    initForm() {
      listSettle({ settleId: this.taskForm.formId }).then((res) => {
        if (res.total == 1) {
          this.form = res.rows[0];
          this.flag = true;
          this.handleSelectProject(res.rows[0].projectId);
          this.listSettleWorkFn();
          this.listSettleSummaryFn();
          getUser(this.form.reporter).then((res) => {
            if (res.data) {
              this.form.reporterName = res.data.nickName;
              this.deptId = res.data.deptId;
            }
          });
          this.getCurrentUser();
        } else if (res.total == 0) {
          this.flag = false;
          if (this.taskName == "结算发起") {
            this.form.reporter = this.$store.state.user.id;
            this.form.reporterName = this.$store.state.user.name;
            this.form.reportTime = parseTime(new Date(), "{y}-{m}-{d}");
          }
        }
        setTimeout(() => {
          this.loading = false;
          this.deptList = this.$store.state.user.deptList
        }, 500);
      });
    },
    // 获取当前处理人
    getCurrentUser() {
      if (this.taskName == "综合事务部处理") {
        this.form.zhUserName = this.$store.state.user.name;
        this.form.zhUserId = this.$store.state.user.id;
        this.form.zhTime = parseTime(new Date(), "{y}-{m}-{d}");
      } else if (this.taskName == "技术质量部审核") {
        this.form.jsUserName = this.$store.state.user.name;
        this.form.jsUserId = this.$store.state.user.id;
        this.form.jsTime = parseTime(new Date(), "{y}-{m}-{d}");
      } else if (this.taskName == "项目管理部结算") {
        this.form.xmUserName = this.$store.state.user.name;
        this.form.xmUserId = this.$store.state.user.id;
        this.form.xmTime = parseTime(new Date(), "{y}-{m}-{d}");
      } else if (this.taskName == "结算发起人确认") {
        this.form.deptUserName = this.$store.state.user.name;
        this.form.deptUserId = this.$store.state.user.id;
        this.form.deptTime = parseTime(new Date(), "{y}-{m}-{d}");
      } else if (this.taskName == "经营发展部校核") {
        this.form.jyUserName = this.$store.state.user.name;
        this.form.jyUserId = this.$store.state.user.id;
        this.form.jyTime = parseTime(new Date(), "{y}-{m}-{d}");
      } else 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}");
      }
      this.getReviewerName();
    },
    // 获取审核人
    getReviewerName() {
      if (this.form.zhUserId) {
        getUser(this.form.zhUserId).then((res) => {
          this.form.zhUserName = res.data.nickName;
        });
      }
      if (this.form.jsUserId) {
        getUser(this.form.jsUserId).then((res) => {
          this.form.jsUserName = res.data.nickName;
        });
      }
      if (this.form.xmUserId) {
        getUser(this.form.xmUserId).then((res) => {
          this.form.xmUserName = res.data.nickName;
        });
      }
      if (this.form.deptUserId) {
        getUser(this.form.deptUserId).then((res) => {
          this.form.deptUserName = res.data.nickName;
        });
      }
      if (this.form.jyUserId) {
        getUser(this.form.jyUserId).then((res) => {
          this.form.jyUserName = res.data.nickName;
        });
      }
      if (this.form.managerUserId) {
        getUser(this.form.managerUserId).then((res) => {
          this.form.managerUserName = res.data.nickName;
        });
      }
      if (this.form.gmUserId) {
        getUser(this.form.gmUserId).then((res) => {
          this.form.gmUserName = res.data.nickName;
        });
      }
    },
    // 保存按钮
    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 == "结算发起") {
            getUserByRole({ roleId: 4 }).then((res) => {
              this.getNextFlowNodeFn(res.data[0]);
            });
          } else if (this.taskName == "综合事务部处理") {
            this.getNextFlowNodeFn(null, 110, false);
          } else if (this.taskName == "技术质量部审核") {
            this.getNextFlowNodeFn(null, 107, false);
          } else if (this.taskName == "项目管理部结算") {
            this.getNextFlowNodeFn();
          } else if (this.taskName == "结算发起人确认") {
            this.getNextFlowNodeFn(null, 105, false);
          } else 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.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);
          complete(this.taskForm).then((response) => {
            this.$modal.msgSuccess(response.msg);
            this.$emit("goBack");
          });
        } else {
          if (deptId && isList) {
            getUsersManageLeaderByDept({ deptId }).then((res) => {
              let id = [];
              id.push(res.data.userId);
              id.push(10);
              this.$set(this.taskForm.variables, "approvalList", id);
              complete(this.taskForm).then((response) => {
                this.$modal.msgSuccess(response.msg);
                this.$emit("goBack");
              });
            });
          } else if (deptId && !isList) {
            getUsersDeptLeaderByDept({ deptId }).then((res) => {
              this.$set(this.taskForm.variables, "approval", res.data.userId);
              complete(this.taskForm).then((response) => {
                this.$modal.msgSuccess(response.msg);
                this.$emit("goBack");
              });
            });
          } else {
            complete(this.taskForm).then((response) => {
              this.$modal.msgSuccess(response.msg);
              this.$emit("goBack");
            });
          }
        }
      });
    },
    // 查询项目列表
    getProjectList() {
      listProject({
        pageNum: 1,
        pageSize: 99999999,
      }).then((response) => {
        this.projectList = response.rows;
      });
    },
    // 选择项目
    handleSelectProject(val) {
      if (val != "" && val != undefined && val != null) {
        getProject(val).then((res) => {
          this.chooseProject = res.data;
          this.isSelect = true;
          getUser(this.chooseProject.projectRegistrant).then((res) => {
            if (res.data) {
              this.$set(
                this.chooseProject,
                "projectRegistrantName",
                res.data.nickName
              );
            }
          });
        });
      } else {
        this.isSelect = false;
      }
    },
    isEmptyObject(obj) {
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          return false;
        }
      }
      return true;
    },
    // 获取合同
    getContractDataList() {
      listProjectContract({ projectId: this.taskForm.formId }).then((res) => {
        if (res.rows) {
          for (let row of res.rows) {
            getContract(row.contractId).then((res) => {
              if (res.data) {
                if (this.form.contractCode != "") {
                  this.form.contractCode =
                    this.form.contractCode + "、" + res.data.contractCode;
                } else {
                  this.form.contractCode = res.data.contractCode;
                }
                if (this.form.contractNumber != "") {
                  this.form.contractNumber =
                    this.form.contractNumber + "、" + res.data.contractNumber;
                } else {
                  this.form.contractNumber = res.data.contractNumber;
                }
              }
            });
          }
        }
      });
    },
    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;
      work.settle = Number(sum).toFixed(2);
      this.calculateSumSettle();
      this.calculateActualSumSettle();
    },
    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;
    },
    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);
          });
        }
      });
    },
    addSettleWorkFn(settleId) {
      for (let work of this.settleWorkList) {
        work.settleId = settleId;
        addSettleWork(work);
      }
    },
    addSettleSummaryFn(settleId) {
      this.settleSumTr.settleId = settleId;
      addSettleSummary(this.settleSumTr);
      for (let item of this.settleSumList) {
        item.settleId = settleId;
        addSettleSummary(item);
      }
      for (let item of this.deptSettleList) {
        item.settleId = settleId;
        addSettleSummary(item);
      }
    },
    // 获取数据
    listSettleWorkFn() {
      listSettleWork({ settleId: this.taskForm.formId }).then((res) => {
        this.settleWorkList = res.rows;
        for (let work of this.settleWorkList) {
          getPrice(work.priceId).then((res) => {
            if (res.data) {
              this.setValue(work, "scale", res.data.scaleGrade);
              this.setValue(work, "unit", res.data.unit);
              if (work.groundType == "0") {
                work.price = res.data.commonPrice;
              } else {
                work.price = res.data.complexPrice;
              }
            }
          });
        }
      });
    },
    listSettleSummaryFn() {
      listSettleSummary({ settleId: this.taskForm.formId }).then((res) => {
        this.oldSettleSumList = res.rows;
        for (let s of res.rows) {
          if (s.content == "结算费用合计") {
            this.settleSumTr = s;
            break;
          }
        }
        this.settleSumList = res.rows.filter((item) => item.tableNumber == "0");
        this.deptSettleList = res.rows.filter(
          (item) => item.tableNumber == "1"
        );
        this.calculateActualSumSettle();
      });
    },
    // 更新数据
    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] = "";
        }
      }
    },
    confirmProject(val) {
      if (val.length == 1) {
        this.prOpen = false;
        this.chooseProject = val[0];
        let undertakingDeptName = []
        if (val[0].undertakingDept) {
          let deptArr = val[0].undertakingDept.split(',');
          for (let dept of deptArr) {
            undertakingDeptName.push(this.getDeptName(dept))
          }
        }
        this.chooseProject.undertakingDeptName = undertakingDeptName.join(',');
        this.$set(this.form, 'projectId', val[0].projectId)
        this.isSelect = true;
      } else {
        this.$message.error("项目只能选择一个！");
        return;
      }
    },
    // 获取系数备注
    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
          // });
        }
      });
    },
  },
};
</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;
  /*设置背景颜色*/
  /* background-color: #bfa; */
}

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