<template>
  <div class="app-container" v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading">
    <el-row :gutter="20">
      <el-col :span="flowDisabled ? 18 : 24" :xs="24">
        <h2 class="text-center">借款申请</h2>
        <el-divider></el-divider>
        <el-form ref="form" :model="form" :rules="rules" label-width="150px">
          <el-row :gutter="20">
            <el-col :span="6" :xs="24">
              <el-form-item label="申请人" prop="user.nickName">
                {{ form.applierUser ? form.applierUser.nickName : form.user.nickName }}
              </el-form-item>
            </el-col>
            <el-col :span="6" :xs="24">
              <el-form-item label="申请部门" prop="dept.deptName">
                {{ form.dept.deptName }}
              </el-form-item>
            </el-col>
            <el-col :span="6" :xs="24">
              <el-form-item label="申请时间" prop="date">
                <el-date-picker style="width:140px;" v-model="form.applyDate" value-format="yyyy-MM-dd" type="date"
                  placeholder="选择日期" :disabled="taskName != '借款申请'">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="借款类型" prop="borrowUsage" v-if="taskForm.procDefName == '借款审批'">
            <el-radio-group v-model="form.borrowUsage" @change="hanldeChangeType" :disabled="taskName != '借款申请'">
              <el-radio label="0">项目借款</el-radio>
              <el-radio label="1">非项目借款</el-radio>
              <el-radio label="2">工会借款</el-radio>
              <el-radio label="3">党委借款</el-radio>
              <el-radio label="4">团委借款</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="借款事由" prop="applyReason" v-if="taskForm.procDefName == '借款审批' && !isProject">
            <el-input v-model="form.applyReason" :disabled="taskName != '借款申请'"></el-input>
          </el-form-item>
          <el-form-item label="项目编号" prop="projectId" v-if="taskForm.procDefName == '借款审批' && isProject">
            <el-button type="primary" size="mini" @click="openProject = true" v-if="taskName == '借款申请'">选择项目</el-button>
            <!-- <el-select v-model="form.projectId" filterable placeholder="请选择" @change="handleSelectProject"
              :disabled="taskName != '借款申请'" clearable>
              <el-option v-for="item in projectList" :key="item.value" :label="item.projectNumber"
                :value="item.projectId">
              </el-option>
            </el-select> -->
            <el-descriptions border v-if="isSelect" style="margin-top: .125rem;" :column="1">
              <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.projectLeaderUser ?
    chooseProject.projectLeaderUser.nickName : ''
                }}</el-descriptions-item>
              <el-descriptions-item label="承担部门" label-class-name="my-label">
                <el-tag size="small">{{ chooseProject.undertakingDeptName }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="项目类型" label-class-name="my-label">{{ chooseProject.projectType
                }}</el-descriptions-item>
            </el-descriptions>
          </el-form-item>
          <el-form-item label="借款明细">
            <table border="1" class="table">
              <tr>
                <td style="width:50px;">序号</td>
                <td style="width:200px">开支项目</td>
                <td>单位</td>
                <td>单价</td>
                <td>数量</td>
                <td>申请金额</td>
                <!-- <td v-if="form.borrowUsage == 0 || form.borrowUsage == 1">项目管理部校核金额</td> -->
                <td v-if="form.borrowUsage == 0 || form.borrowUsage == 1">分管领导审核金额</td>
                <td>操作</td>
              </tr>
              <tr v-for="(detail, index) in detailList" :key="index">
                <td>
                  {{ index + 1 }}
                </td>
                <td>
                  <el-input v-model="detail.borrowItem" type="textarea" :disabled="taskName != '借款申请'"></el-input>
                </td>
                <td>
                  <el-input v-model="detail.unit" :disabled="taskName != '借款申请'"></el-input>
                </td>
                <td>
                  <el-input-number :controls="false" style="width:100%" v-model="detail.price"
                    @change="calculateAmount(detail)" :disabled="taskName != '借款申请'"></el-input-number>
                </td>
                <td>
                  <el-input-number :controls="false" style="width:100%" v-model="detail.quantity"
                    @change="calculateAmount(detail)" :disabled="taskName != '借款申请'"></el-input-number>
                </td>
                <td>
                  <el-input v-model="detail.applyAmount" :disabled="taskName != '借款申请'"></el-input>
                </td>
                <!-- <td v-if="form.borrowUsage == 0 || form.borrowUsage == 1">
                  <el-input v-model="detail.xmAmount" :disabled="taskName != '项目部审核'"
                    @change="calculateXmAmount(detail)"></el-input>
                </td> -->
                <td v-if="form.borrowUsage == 0 || form.borrowUsage == 1">
                  <el-input v-model="detail.managerAmount" :disabled="taskName != '分管审核'"
                    @change="calculateManagerAmount(detail)"></el-input>
                </td>
                <td>
                  <el-button type="text" style="color:#F56C6C" icon="el-icon-delete" size="mini" circle
                    :disabled="taskName != '借款申请'" @click="deleDetailItem(index)">删除行</el-button>
                </td>
              </tr>
            </table>
            <el-button icon="el-icon-plus" size="mini" @click="addDetailList()" type="primary" plain
              :disabled="taskName != '借款申请'"></el-button>
          </el-form-item>
          <el-form-item label="预算金额" v-if="isSelect">
            <el-tag>{{ totalBudget.toFixed(2) }}（大写：{{ formatNumberWithWan(totalBudget) }}）</el-tag>
          </el-form-item>
          <el-form-item label="已申请借款" v-if="isSelect">
            <el-tag type="danger">{{ hasBorrow.toFixed(2) }}（大写：{{ formatNumberWithWan(hasBorrow) }}）</el-tag>
          </el-form-item>
          <el-form-item label="可用借款" v-if="isSelect">
            <el-tag type="success">{{ (totalBudget - hasBorrow).toFixed(2) }}（大写：{{ formatNumberWithWan((totalBudget -
    hasBorrow)) }}）</el-tag>
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="8" :xs="24">
              <el-form-item label="申请金额" prop="applyAmount">
                <el-input v-model="form.applyAmount" placeholder="请输入申请金额" :disabled="taskName != '借款申请'"
                  @blur="VerificationAmount" />
                <span style="color:#E74C3C" v-if="exceed && form.borrowUsage == 0">超过预算金额：{{ getMoreAmount('0') }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8" :xs="24">
              <el-form-item label="核准金额" prop="managerAmount">
                <el-input v-model="form.managerAmount" placeholder="请输入核准金额"
                  :disabled="taskName != '分管审核' && taskName != '党工团审核'" />
                <span style="color:#E74C3C" v-if="form.managerAmount && form.borrowUsage == 0">超过预算金额：{{ getMoreAmount('1') }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="申请人说明" prop="remark">
            <el-input type="textarea" :rows="4" v-model="form.remark" placeholder="请输入申请人说明" :disabled="taskName != '借款申请'" />
          </el-form-item>
          <el-form-item label="附件上传" prop="borrowDocument">
            <FileUpload v-if="form.borrowDocument == null || form.borrowDocument == ''" :disabled="taskName != '借款申请'"
              :limit="1" :filePathName="'借款/申请附件'" :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf']"
              @input="getBorrowPath"></FileUpload>
            <div v-if="form.borrowDocument && taskName != '借款申请'">
              <!-- <file-item :document="form.borrowDocument"></file-item> -->
              <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + form.borrowDocument}`)">
                {{ getFileName(form.borrowDocument) }}
              </el-link>
              <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + form.borrowDocument}`"
                :underline="false" target="_blank">
                <span class="el-icon-download">下载文件</span>
              </el-link>
            </div>
          </el-form-item>
          <el-divider></el-divider>
          <!-- 非党工团审核 -->
          <div v-if="form.borrowUsage == 0 || form.borrowUsage == 1">
            <el-form-item label="部门负责人意见" prop="deptComment">
              <el-input type="textarea" v-model="form.deptComment" placeholder="请输入部门负责人意见"
                :disabled="taskName != '部门审核'" :autosize="{ minRows: 4 }" />
            </el-form-item>
            <el-row>
              <el-col :span="6" :xs="24" :offset="12">
                <el-form-item label="签名：" label-width="120px" v-if="showFormItem('部门审核')">
                  <span class="auditor"> {{ form.deptUser ? form.deptUser.nickName : deptUser }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px" v-if="showFormItem('部门审核')">
                  <span> {{ form.deptTime ? form.deptTime : deptTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="分管领导审核意见" prop="managerComment">
              <el-input type="textarea" v-model="form.managerComment" placeholder="请输入分管领导审核意见"
                :disabled="taskName != '分管审核'" :autosize="{ minRows: 4 }" />
            </el-form-item>
            <el-row>
              <el-col :span="6" :xs="24" :offset="12">
                <el-form-item label="签名：" label-width="120px" v-if="showFormItem('分管审核')">
                  <span class="auditor"> {{ form.managerUser ? form.managerUser.nickName : managerUser }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px" v-if="showFormItem('分管审核')">
                  <span> {{ form.managerTime ? form.managerTime : managerTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="总经理审批意见" prop="zjlComment">
              <el-input type="textarea" v-model="form.zjlComment" placeholder="请输入总经理审批意见"
                :disabled="taskName != '总经理审核'" :autosize="{ minRows: 4 }" />
            </el-form-item>
            <el-row>
              <el-col :span="6" :xs="24" :offset="12">
                <el-form-item label="签名：" label-width="120px" v-if="showFormItem('总经理审核')">
                  <span class="auditor"> {{ form.zjlUser ? form.zjlUser.nickName : zjlUser }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px" v-if="showFormItem('总经理审核')">
                  <span> {{ form.zjlTime ? form.zjlTime : zjlTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="董事长批准意见" prop="dszComment">
              <el-input type="textarea" v-model="form.dszComment" placeholder="请输入董事长批准意见"
                :disabled="taskName != '董事长批准'" :autosize="{ minRows: 4 }" />
            </el-form-item>
            <el-row>
              <el-col :span="6" :xs="24" :offset="12">
                <el-form-item label="签名：" label-width="120px" v-if="showFormItem('董事长批准')">
                  <span class="auditor"> {{ form.dszUser ? form.dszUser.nickName : dszUser }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px" v-if="showFormItem('董事长批准')">
                  <span> {{ form.dszTime ? form.dszTime : dszTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <!-- 党工团审核 -->
          <div v-if="form.borrowUsage != 0 && form.borrowUsage != 1">
            <el-form-item :label="dgtLabel" prop="unionComment">
              <el-input type="textarea" v-model="form.unionComment" placeholder="请输入审核意见"
                :disabled="taskName != '党工团审核'" />
            </el-form-item>
            <el-row>
              <el-col :span="6" :xs="24" :offset="12">
                <el-form-item label="签名：" label-width="120px" v-if="showFormItem('党工团审核')">
                  <span class="auditor"> {{ form.unionUser ? form.unionUser.nickName : unionUser }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px" v-if="showFormItem('党工团审核')">
                  <span> {{ form.unionTime ? form.unionTime : unionTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <el-divider></el-divider>
          <el-form-item label="支付凭证" prop="lendDocument">
            <FileUpload v-if="taskName == '财务处理'" :disabled="taskName != '财务处理'" :limit="1" :filePathName="'借款/支付凭证'"
              :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf']" @input="getLendPath">
            </FileUpload>
            <div v-if="form.lendDocument && taskName != '财务处理'">
              <!-- <file-item :document="form.lendDocument"></file-item> -->
              <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + form.lendDocument}`)">
                {{ getFileName(form.lendDocument) }}
              </el-link>
              <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + form.lendDocument}`"
                :underline="false" target="_blank">
                <span class="el-icon-download">下载文件</span>
              </el-link>
            </div>
          </el-form-item>
          <el-form-item label="财务部支付备注" prop="cwComment">
            <el-input type="textarea" v-model="form.cwComment" placeholder="请输入财务部支付备注" :disabled="taskName != '财务处理'"
              :autosize="{ minRows: 4 }" />
          </el-form-item>
          <el-row>
            <el-col :span="6" :xs="24" :offset="12">
              <el-form-item label="经办人：" label-width="120px" v-if="showFormItem('财务处理')">
                <span class="auditor"> {{ form.cwUser ? form.cwUser.nickName : cwUser }} </span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="支付日期：" prop="lendTime" v-if="showFormItem('财务处理')">
                <el-date-picker style="width:140px;" v-model="form.lendTime" value-format="yyyy-MM-dd" type="date"
                  placeholder="选择日期" :disabled="taskName != '财务处理'">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="text-align: center;">
          <el-button type="primary" @click="submitForm">提 交</el-button>
        </div>
      </el-col>
      <el-col :span="6" :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="openProject" width="70%" append-to-body>
      <project-choose @chooseProject="confirmProject"></project-choose>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from "@/utils/ruoyi";
import { getUsersDeptLeader, getUsersDeptLeaderByDept, getUsersViceDeptLeaderByDept, getUsersManageLeaderByDept } from '@/api/system/post.js'
import { listBorrow, getBorrow, delBorrow, addBorrow, updateBorrow } from "@/api/oa/borrow/borrow";
import { listBorrowDetail, addBorrowDetail, updateBorrowDetail, delBorrowDetail } from "@/api/oa/borrow/borrowDetail";
import { listProject, getProject } from "@/api/oa/project/project";
import { getUserByPost } from "@/api/system/post";
import flow from '@/views/flowable/task/todo/detail/flow'
import { flowXmlAndNode } from "@/api/flowable/definition";
import { complete, getNextFlowNode } from "@/api/flowable/todo";
import projectChoose from '@/views/flowable/form/components/chooseProject.vue';
import { listBudget } from "@/api/oa/budget/budget";
import { listBudgetSettle } from "@/api/oa/budget/budgetSettle";
import FileItem from '../business/fileItem.vue';

export default {
  components: {
    flow,
    projectChoose,
    FileItem
  },
  name: "Borrow",
  props: {
    taskName: {
      type: String,
    },
    taskForm: {
      type: Object,
      required: true
    },
    flowDisabled: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    'taskForm.formId'() {
      this.initForm();
    },
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      deptUser: '',
      xmUser: '',
      managerUser: '',
      zjlUser: '',
      dszUser: '',
      unionUser: '',
      cwUser: '',
      deptTime: undefined,
      xmTime: undefined,
      managerTime: undefined,
      zjlTime: undefined,
      dszTime: undefined,
      unionTime: undefined,
      lendTime: undefined,
      // 遮罩层
      loading: true,
      detail: {},
      detailList: [
        {
          borrowItem: '',
          unit: '',
          price: '',
          quantity: '',
          applyAmount: '',
          xmAmount: '',
          managerAmount: '',
        }
      ],
      projectList: [],
      chooseProject: {},
      isSelect: false,
      openProject: false,
      // 表单参数
      form: {
        borrowUsage: '0',
        user: {
          nickName: '',
        },
        dept: {
          deptName: '',
        },
        applyDate: undefined,
      },
      // 表单校验
      rules: {
      },
      formTotal: 0,
      flowData: {},
      isProject: true,
      exceed: false, //是否超预算
      deptId: undefined,
      dgtLabel: '工会审核意见',
      totalBudget: 0,
      hasBorrow: 0,
    };
  },
  created() {
    if (this.taskName == '部门审核') {
      this.deptUser = this.$store.getters.name;
      this.deptTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    if (this.taskName == '分管审核') {
      this.managerUser = this.$store.getters.name;
      this.managerTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    if (this.taskName == '总经理审核') {
      this.zjlUser = this.$store.getters.name;
      this.zjlTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    if (this.taskName == '董事长批准') {
      this.dszUser = this.$store.getters.name;
      this.dszTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    if (this.taskName == '党工团审核') {
      this.unionUser = this.$store.getters.name;
      this.unionTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    if (this.taskName == '财务处理') {
      this.cwUser = this.$store.getters.name;
      this.lendTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    this.form.applyDate = new Date();
    this.form.user.nickName = this.$store.getters.name;
    this.form.dept.deptName = this.$store.getters.deptName;
    this.deptId = this.$store.getters.deptId;
    this.getProjectList();
    if (this.$route.query.projectId) {
      getProject(this.$route.query.projectId).then(res => {
        if (res.data) {
          this.form.projectId = res.data.projectId;
          this.handleSelectProject(res.data.projectId)
        }
      })
    } else {
      this.handleSelectProject(this.form.projectId)
    }
    if (this.flowDisabled)
      flowXmlAndNode({ procInsId: this.taskForm.procInsId, deployId: this.taskForm.deployId }).then(res => {
        this.flowData = res.data;
      })
  },
  mounted() {
    this.initRules();
    this.initForm();
  },
  methods: {
    initRules() {
      if (this.taskName == '部门审核') {
        this.rules = {
          deptComment: [
            { required: true, message: '请输入部门负责人意见', trigger: 'blur' },
          ],
        }
        // } else if (this.taskName == '项目部审核') {
        //   this.rules = {
        //     xmComment: [
        //       { required: true, message: '请输入项目部校核意见', trigger: 'blur' }
        //     ]
        //   }
      } else if (this.taskName == '分管审核') {
        this.rules = {
          managerComment: [
            { required: true, message: '请输入分管领导审核意见', trigger: 'blur' }
          ]
        }
      } else if (this.taskName == '总经理审核') {
        this.rules = {
          zjlComment: [
            { required: true, message: '请输入总经理审批意见', trigger: 'blur' }
          ]
        }
      } else if (this.taskName == '董事长审核') {
        this.rules = {
          dszComment: [
            { required: true, message: '请输入董事长审批意见', trigger: 'blur' }
          ]
        }
      } else if (this.taskName == '党工团审核') {
        this.rules = {
          unionComment: [
            { required: true, message: '请输入审核意见', trigger: 'blur' }
          ]
        }
      } else if (this.taskName == '财务处理') {
        this.rules = {
          lendTime: [
            { required: true, message: '请选择支付日期', trigger: 'change' }
          ]
        }
      }
    },
    initForm() {
      listBorrowDetail({ borrowId: this.taskForm.formId }).then(res => {
        if (res.rows.length != 0) {
          this.detailList = res.rows
        }
      });
      getBorrow(this.taskForm.formId).then(res => {
        if (this.isEmptyObject(res.data)) {
          this.formTotal = 0;
          this.form.applier = this.$store.getters.userId;
        }
        else {
          this.formTotal = 1;
          this.form = res.data;
          if (this.isProject) {
            if ((this.totalBudget - this.form.applyAmount) < 0) {
              this.exceed = true;
            } else {
              this.exceed = false;
            }
          }
          this.hanldeChangeType();
          this.handleSelectProject(res.data.projectId)
          this.getBudgetSettle()
        }
        this.loading = false;
      })

    },
    async getBudgetSettle() {
      let budgetData = await listBudget({ projectId: this.form.projectId })
      if (budgetData.total == 1) {
        let budget = budgetData.rows[0];
        this.totalBudget = budget.totalBudget
      }
      let borrow = await listBorrow({ projectId: this.form.projectId })
      if (borrow.total != 0) {
        let borrowList = borrow.rows;
        let hasBorrow = 0;
        borrowList = borrowList.filter(item => item.borrowId != this.taskForm.formId)
        borrowList.forEach(element => {
          if (element.managerAmount) {
            hasBorrow = hasBorrow + element.managerAmount
          }
          if (!element.managerAmount && element.applyAmount) {
            hasBorrow = hasBorrow + element.applyAmount
          }
        });
        this.hasBorrow = hasBorrow
      }
    },
    // 查询项目列表
    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
        })
      } else {
        this.isSelect = false
      }
    },
    // 取消按钮
    cancel() {
      this.reset();
    },
    isEmptyObject(obj) {
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          return false;
        }
      }
      return true;
    },
    deleDetailItem(index) {
      let arr = this.detailList;
      if (arr.length == 1) {
        return;
      }
      if (index >= 0 && index < arr.length) {
        arr.splice(index, 1);
      }
    },
    addDetailList() {
      this.detailList.push({
        borrowItem: '',
        unit: '',
        price: '',
        quantity: '',
        applyAmount: '',
        xmAmount: '',
        managerAmount: '',
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.borrowUsage == '0' && !this.form.projectId) {
            this.$message.error('请选择项目！')
            return
          }
          if (this.formTotal != 0) {
            // 更新借款明细项
            delBorrowDetail(this.taskForm.formId).then(res => {
              this.detailList.forEach(detail => {
                detail.borrowId = this.taskForm.formId;
                addBorrowDetail(detail)
              })
            })
            // 更新借款审批表
            updateBorrow(this.form);
            const params = { taskId: this.taskForm.taskId };
            getNextFlowNode(params).then(res => {
              if (this.taskName == '借款申请') {
                this.borrowAprrovalFun();
              } else if (this.taskName == '部门审核') {
                getUsersManageLeaderByDept({ deptId: this.form.applyDept }).then(res => {
                  let userIds = [];
                  if (res.data) {
                    res.data.forEach(item => {
                      userIds.push(item.userId)
                    })
                  }
                  this.$set(this.taskForm.variables, "approvalList", userIds);
                  this.handleComplete(this.taskForm);
                })
              }
              else if (this.taskName == '分管审核') {
                getUserByPost({ postName: '总经理' }).then(res => {
                  this.$set(this.taskForm.variables, "approval", res.data[0].userId);
                  this.handleComplete(this.taskForm);
                })
              }
              else if (this.taskName == '总经理审核') {
                this.$set(this.taskForm.variables, "exceed", this.exceed);
                if (!this.exceed) { //没有超预算
                  this.submitFD(); //提交到财务部审核
                }
                else {
                  getUserByPost({ postName: '董事长' }).then(res => {
                    this.$set(this.taskForm.variables, "approval", res.data[0].userId);
                    this.handleComplete(this.taskForm);
                  })
                }
              }
              else if (this.taskName == '董事长批准') {
                this.submitFD(); //提交到财务部审核
              }
              else if (this.taskName == '党工团审核') {
                this.submitFD(); //提交到财务部审核
              }
              else if (this.taskName == '财务处理') {
                this.handleComplete(this.taskForm);
              }
            })
          } else {
            for (let detail of this.detailList) {
              detail.borrowId = this.taskForm.formId;
              addBorrowDetail(detail);
            }
            this.form.borrowId = this.taskForm.formId;
            addBorrow(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
            });
            const params = { taskId: this.taskForm.taskId };
            // 提交到下一个流程
            getNextFlowNode(params).then(res => {
              this.borrowAprrovalFun();

            })
          }
        }
      });
    },
    handleComplete(taskForm) {
      complete(taskForm).then(response => {
        this.$modal.msgSuccess(response.msg);
        this.$emit('goBack');
      })
    },
    // 借款申请提交方法
    borrowAprrovalFun() {
      let userId;
      // 如果是党工团申请 deptId == 0 为党工团申请
      if (this.deptId == 0) {
        // 2为工会、3为党委
        if (this.form.borrowUsage == 2 || this.form.borrowUsage == 3) {
          userId = this.publicData.partySecretary
        } else {
          userId = this.publicData.leagueSecretary
        }
        this.$set(this.taskForm.variables, "dept", this.deptId);
        this.$set(this.taskForm.variables, "approval", userId);
        this.handleComplete(this.taskForm);
      } else if (this.deptId == 102) { //如果是经营管理层申请，走总经理审批
        getUserByPost({ postName: '总经理' }).then(res => {
          this.$set(this.taskForm.variables, "dept", this.deptId);
          this.$set(this.taskForm.variables, "approval", res.data[0].userId);
          this.handleComplete(this.taskForm);
        })
      } else if (this.deptId == 101) {//如果是董事会申请，走董事长批准
        getUserByPost({ postName: '董事长' }).then(res => {
          this.$set(this.taskForm.variables, "dept", this.deptId);
          this.$set(this.taskForm.variables, "approval", res.data[0].userId);
          this.handleComplete(this.taskForm);
        })
      }
      else { //普通员工申请项目借款
        getUsersDeptLeader({ userId: this.$store.getters.userId }).then(res => {
          let userId = res.data.userId;
          this.$set(this.taskForm.variables, "approval", userId);
          this.$set(this.taskForm.variables, "dept", this.deptId);
          this.handleComplete(this.taskForm);
        })
      }
    },
    // 提交给财务部审核
    submitFD() {
      let approvalList = [];
      getUsersDeptLeaderByDept({ deptId: 106 }).then(res => {
        approvalList.push(res.data.userId);
        getUsersViceDeptLeaderByDept({ deptId: 106 }).then(res1 => {
          approvalList.push(res1.data.userId);
          this.$set(this.taskForm.variables, "approvalList", approvalList);
          this.handleComplete(this.taskForm);
        })
      });
    },
    showFormItem(name) {
      let isShow = false;
      if (name == '借款申请')
        isShow = true;
      else if (name == '部门审核')
        isShow = (this.taskName != '借款申请');
      // else if (name == '项目部审核')
      //   isShow = (this.taskName != '借款申请' && this.taskName != '部门审核');
      else if (name == '分管审核')
        isShow = (this.taskName != '借款申请' && this.taskName != '部门审核' && this.taskName != '项目部审核');
      else if (name == '总经理审核')
        isShow = (this.taskName == '总经理审核' || this.taskName == '董事长批准' || this.taskName == '财务处理' || this.taskName == '');
      else if (name == '董事长批准')
        isShow = (this.taskName == '董事长批准' || this.taskName == '财务处理' || this.taskName == '');
      else if (name == '党工团审核')
        isShow = (this.taskName == '党工团审核' || this.taskName == '财务处理' || this.taskName == '');
      else if (name == '财务处理')
        isShow = (this.taskName == '财务处理' || this.taskName == '');
      return isShow;
    },
    confirmProject(val) {
      if (val.length > 1) {
        this.$message.error('请选择一个项目');
        return
      } else if (val.length == 1) {
        this.chooseProject = val[0]
        this.isSelect = true
        this.form.projectId = val[0].projectId
      }
      this.openProject = false
      this.getBudgetSettle();
    },
    calculateAmount(detail) {
      let total = Number(detail.price) * Number(detail.quantity);
      this.$set(detail, "applyAmount", total.toFixed(2));
      this.getTotal("applyAmount", "applyAmount", this.detailList);
    },
    calculateXmAmount(detail) {
      this.getTotal("xmAmount", "managerAmount", this.detailList);
    },
    calculateManagerAmount(detail) {
      this.getTotal("managerAmount", "managerAmount", this.detailList);
    },
    getTotal(name1, name2, list) {
      let sum = 0;
      for (let user of list) {
        sum = sum + Number(user[name1]);
      }
      this.form[name2] = sum.toFixed(2);
      this.VerificationAmount();
    },
    getBorrowPath(val) {
      let arr = val.split('/upload')
      this.form.borrowDocument = arr[1]
      if (val == "") {
        this.form.borrowDocument = ""
      }
    },
    getLendPath(val) {
      let arr = val.split('/upload')
      this.form.lendDocument = arr[1]
      if (val == "") {
        this.form.lendDocument = ""
      }
    },
    // 修改借款类型
    hanldeChangeType() {
      if (this.form.borrowUsage == '0') {
        this.deptId = this.$store.getters.deptId;
        this.isProject = true;
      } else if (this.form.borrowUsage == '1') {
        this.deptId = this.$store.getters.deptId;
        this.isProject = false;
      } else if (this.form.borrowUsage == '2' || this.form.borrowUsage == '3' || this.form.borrowUsage == '4') {
        this.deptId = 0;
        this.isProject = false;
        if (this.form.borrowUsage == '2') {
          this.dgtLabel = '工会审核意见'
        } else if (this.form.borrowUsage == '3') {
          this.dgtLabel = '党委审核意见'
        } else {
          this.dgtLabel = '团委审核意见'
        }
      }
    },
    // 验证金额
    VerificationAmount() {
      if (this.isSelect) {
        if (this.form.applyAmount > (this.totalBudget - this.hasBorrow)) {
          this.$confirm('借款总额已经超过项目预算，将走《超预算或预算外支付（报销）》流程', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          }).then(() => {
            this.exceed = true;
            this.$set(this.taskForm.variables, "exceed", true);
            return
          })
        } else {
          this.exceed = false;
          this.$set(this.taskForm.variables, "exceed", false);
        }
      }
    },
    // 计算超过预算的金额
    getMoreAmount(type) {
      let result;
      if (type == '0') {
        result = this.form.applyAmount - (this.totalBudget - this.hasBorrow);
      } else {
        result = this.form.managerAmount - (this.totalBudget - this.hasBorrow);
      }
      return result.toFixed(2)
    }
  }
};
</script>

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

table {
  text-align: center;
  border-collapse: collapse;

  td {
    padding: .0625rem;
  }
}
</style>