<template>
  <div class="app-container" v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading">
    <el-button type="success" @click="printOpen = true">打印</el-button>
    <el-row :gutter="20">
      <el-col :span="24" :md="flowDisabled ? 18 : 24">
        <h2 class="text-center">借款申请</h2>
        <el-divider></el-divider>
        <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>
        <el-form ref="form" :model="form" :rules="rules" class="borrow-table-form">
          <div class="form-table-wrap">
            <table class="form-table">
              <tr>
                <td colspan="2" class="label-cell">申请人</td>
                <td colspan="2">
                  <el-form-item prop="user.nickName" class="table-form-item">
                    {{ form.applierUser ? form.applierUser.nickName : form.user.nickName }}
                  </el-form-item>
                </td>
                <td colspan="2" class="label-cell">申请部门</td>
                <td colspan="2">
                  <el-form-item prop="dept.deptName" class="table-form-item">
                    {{ form.dept.deptName }}
                  </el-form-item>
                </td>
                <td colspan="2" class="label-cell">申请日期</td>
                <td colspan="2">
                  <el-form-item prop="date" class="table-form-item">
                    <el-date-picker style="width: 100%;" v-model="form.applyDate" value-format="yyyy-MM-dd" type="date"
                      placeholder="选择日期" disabled>
                    </el-date-picker>
                  </el-form-item>
                </td>
              </tr>

              <template v-if="taskForm.procDefName == '借款审批'">
                <tr>
                  <td colspan="2" class="label-cell">借款类型</td>
                  <td colspan="10">
                    <el-form-item prop="borrowUsage" class="table-form-item">
                      <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>
                  </td>
                </tr>
                <tr v-if="!isProject">
                  <td colspan="2" class="label-cell">借款事由</td>
                  <td colspan="10">
                    <el-form-item prop="applyReason" class="table-form-item">
                      <el-input v-model="form.applyReason" :disabled="taskName != '借款申请'"></el-input>
                    </el-form-item>
                  </td>
                </tr>
                <template v-if="isProject">
                  <tr>
                    <td colspan="2" class="label-cell">项目信息</td>
                    <td colspan="10">
                      <el-button type="primary" size="mini" @click="openProject = true"
                        v-if="taskName == '借款申请'">选择项目</el-button>
                      <template v-if="isSelect">
                        <table class="inner-table">
                          <tr>
                            <td class="label-cell">项目编号</td>
                            <td>{{ chooseProject.projectNumber }}</td>
                            <td class="label-cell">项目名称</td>
                            <td>{{ chooseProject.projectName }}</td>
                          </tr>
                          <tr>
                            <td class="label-cell">项目负责人</td>
                            <td>{{ chooseProject.projectLeaderUser ? chooseProject.projectLeaderUser.nickName : '' }}
                            </td>
                            <td class="label-cell">承担部门</td>
                            <td>{{ chooseProject.undertakingDeptName }}</td>
                          </tr>
                          <tr>
                            <td class="label-cell">项目类型</td>
                            <td colspan="3">{{ chooseProject.projectType }}</td>
                          </tr>
                        </table>
                      </template>
                      <el-form-item prop="projectId" class="table-form-item" style="display: none;"></el-form-item>
                    </td>
                  </tr>
                </template>
              </template>

              <tr>
                <td colspan="2" class="label-cell">借款明细</td>
                <td colspan="10">
                  <table class="inner-table detail-inner-table">
                    <tr>
                      <td class="label-cell" style="width: 50px;">序号</td>
                      <td class="label-cell" style="min-width: 150px;">开支项目</td>
                      <td class="label-cell">单位</td>
                      <td class="label-cell">单价</td>
                      <td class="label-cell">数量</td>
                      <td class="label-cell">申请金额</td>
                      <td class="label-cell" v-if="form.borrowUsage == 0 || form.borrowUsage == 1">分管领导审核金额</td>
                      <td class="label-cell">操作</td>
                    </tr>
                    <tr v-for="(detail, index) in detailList" :key="index">
                      <td>{{ index + 1 }}</td>
                      <td>
                        <el-select v-model="detail.borrowItem" placeholder="请选择开支项" clearable
                          @change="handleExpenseChange" style="width: 100%;" :disabled="taskName != '借款申请'"
                          v-if="form.borrowUsage == 0">
                          <el-option v-for="dict in dict.type.cmc_borrow_expense" clearable :key="dict.value"
                            :label="dict.label" :value="dict.value" />
                        </el-select>
                        <el-autocomplete v-model="detail.borrowItem" :fetch-suggestions="querySearchAsync"
                          placeholder="请输入内容" style="width: 100%;" :disabled="taskName != '借款申请'"
                          v-else></el-autocomplete>
                      </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.managerAmount" :disabled="taskName != '分管审核' && taskName != '总经理审核'"
                          @input="calculateManagerAmount"></el-input>
                      </td>
                      <td>
                        <el-button type="text" style="color: #F56C6C;" icon="el-icon-delete" size="mini"
                          :disabled="taskName != '借款申请'" @click="deleDetailItem(index)">删除</el-button>
                      </td>
                    </tr>
                  </table>
                  <el-button class="mt10" icon="el-icon-plus" size="mini" @click="addDetailList()" type="primary" plain
                    :disabled="taskName != '借款申请'">添加明细行</el-button>
                </td>
              </tr>

              <tr v-if="isSelect" class="budget-row">
                <td colspan="2" class="label-cell">最大借款金额</td>
                <td colspan="2" class="budget-value-cell">
                  <div class="budget-amount">
                    <span class="amount-num">{{ siteExpenses.toFixed(2) }}</span>
                    <span class="amount-cn">大写：{{ formatNumberWithWan(siteExpenses) }}</span>
                  </div>
                  <el-button type="text" size="mini" class="budget-link-btn" @click="openBudget = true"
                    v-hasPermi="['oa:budget:list']">查看预算</el-button>
                </td>
                <td colspan="2" class="label-cell">已申请借款</td>
                <td colspan="2" class="budget-value-cell">
                  <div class="budget-amount is-danger">
                    <span class="amount-num">{{ hasBorrow.toFixed(2) }}</span>
                    <span class="amount-cn">大写：{{ formatNumberWithWan(hasBorrow) }}</span>
                  </div>
                  <el-button type="text" size="mini" class="budget-link-btn"
                    @click="openBorrow = true">查看历史借款</el-button>
                </td>
                <td colspan="2" class="label-cell">可用借款</td>
                <td colspan="2" class="budget-value-cell">
                  <div class="budget-amount is-success">
                    <span class="amount-num">{{ (siteExpenses - hasBorrow).toFixed(2) }}</span>
                    <span class="amount-cn">大写：{{ formatNumberWithWan((siteExpenses - hasBorrow)) }}</span>
                  </div>
                </td>
              </tr>

              <tr>
                <td colspan="2" class="label-cell">申请金额</td>
                <td colspan="4">
                  <el-form-item prop="applyAmount" class="table-form-item">
                    <el-input v-model="form.applyAmount" placeholder="请输入申请金额" :disabled="taskName != '借款申请'" />
                    <span class="exceed-tip" v-if="exceed && form.borrowUsage == 0">超过预算金额：{{ getMoreAmount('0')
                      }}</span>
                  </el-form-item>
                </td>
                <td colspan="2" class="label-cell">核准金额</td>
                <td colspan="4">
                  <el-form-item prop="managerAmount" class="table-form-item">
                    <el-input v-model="form.managerAmount" placeholder="请输入核准金额"
                      :disabled="taskName != '分管审核' && taskName != '总经理审核' && taskName != '党工团审核'" />
                    <span class="exceed-tip" v-if="exceed && form.managerAmount && form.borrowUsage == 0">超过预算金额：{{
                      getMoreAmount('1') }}</span>
                  </el-form-item>
                </td>
              </tr>

              <tr>
                <td colspan="2" class="label-cell">申请人说明</td>
                <td colspan="10">
                  <el-form-item prop="remark" class="table-form-item">
                    <el-input type="textarea" :rows="4" v-model="form.remark" placeholder="请输入申请人说明"
                      :disabled="taskName != '借款申请'" />
                  </el-form-item>
                </td>
              </tr>

              <tr>
                <td colspan="2" class="label-cell">附件上传</td>
                <td colspan="10">
                  <el-form-item prop="borrowDocument" class="table-form-item">
                    <FileUpload v-if="form.borrowDocument == null || form.borrowDocument == ''"
                      :disabled="taskName != '借款申请'" :limit="1" :filePathName="'借款/申请附件'"
                      :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']" @input="getBorrowPath">
                    </FileUpload>
                    <div v-if="form.borrowDocument">
                      <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>
                      <FileUpload v-if="taskName == '借款申请'" :limit="1" :filePathName="'借款/申请附件'"
                        :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']" @input="getBorrowPath">
                      </FileUpload>
                    </div>
                  </el-form-item>
                </td>
              </tr>

              <template v-if="form.borrowUsage == 0 || form.borrowUsage == 1">
                <tr>
                  <td colspan="2" class="label-cell">部门负责人意见</td>
                  <td colspan="10">
                    <el-form-item prop="deptComment" class="table-form-item">
                      <el-input type="textarea" v-model="form.deptComment" placeholder="请输入部门负责人意见"
                        :disabled="taskName != '部门审核'" :autosize="{ minRows: 4 }" />
                    </el-form-item>
                    <el-row class="sign-line" v-if="showFormItem('部门审核')">
                      <el-col :span="6" :offset="11">
                        签名：<span class="auditor">{{ form.deptUser ? form.deptUser.nickName : deptUser }}</span>
                      </el-col>
                      <el-col :span="6">
                        日期：<span>{{ form.deptTime ? form.deptTime : deptTime }}</span>
                      </el-col>
                    </el-row>
                  </td>
                </tr>
                <tr>
                  <td colspan="2" class="label-cell">分管领导审核</td>
                  <td colspan="10">
                    <el-form-item prop="managerComment" class="table-form-item">
                      <el-input type="textarea" v-model="form.managerComment" placeholder="请输入分管领导审核意见"
                        :disabled="taskName != '分管审核'" :autosize="{ minRows: 4 }" />
                    </el-form-item>
                    <el-row class="sign-line" v-if="showFormItem('分管审核')">
                      <el-col :span="6" :offset="11">
                        签名：<span class="auditor">{{ form.managerUser ? form.managerUser.nickName : managerUser }}</span>
                      </el-col>
                      <el-col :span="6">
                        日期：<span>{{ form.managerTime ? form.managerTime : managerTime }}</span>
                      </el-col>
                    </el-row>
                  </td>
                </tr>
                <tr>
                  <td colspan="2" class="label-cell">总经理审批</td>
                  <td colspan="10">
                    <el-form-item prop="zjlComment" class="table-form-item">
                      <el-input type="textarea" v-model="form.zjlComment" placeholder="请输入总经理审批意见"
                        :disabled="taskName != '总经理审核'" :autosize="{ minRows: 4 }" />
                    </el-form-item>
                    <el-row class="sign-line" v-if="showFormItem('总经理审核')">
                      <el-col :span="6" :offset="11">
                        签名：<span class="auditor">{{ form.zjlUser ? form.zjlUser.nickName : zjlUser }}</span>
                      </el-col>
                      <el-col :span="6">
                        日期：<span>{{ form.zjlTime ? form.zjlTime : zjlTime }}</span>
                      </el-col>
                    </el-row>
                  </td>
                </tr>
                <tr v-if="exceed && !form.cwUser">
                  <td colspan="2" class="label-cell">董事长批准</td>
                  <td colspan="10">
                    <el-form-item prop="dszComment" class="table-form-item">
                      <el-input type="textarea" v-model="form.dszComment" placeholder="请输入董事长批准意见"
                        :disabled="taskName != '董事长批准'" :autosize="{ minRows: 4 }" />
                    </el-form-item>
                    <el-row class="sign-line" v-if="showFormItem('董事长批准')">
                      <el-col :span="6" :offset="11">
                        签名：<span class="auditor">{{ form.dszUser ? form.dszUser.nickName : dszUser }}</span>
                      </el-col>
                      <el-col :span="6">
                        日期：<span>{{ form.dszTime ? form.dszTime : dszTime }}</span>
                      </el-col>
                    </el-row>
                  </td>
                </tr>
              </template>

              <tr v-if="form.borrowUsage != 0 && form.borrowUsage != 1">
                <td colspan="2" class="label-cell">{{ dgtLabel }}</td>
                <td colspan="10">
                  <el-form-item prop="unionComment" class="table-form-item">
                    <el-input type="textarea" v-model="form.unionComment" placeholder="请输入审核意见"
                      :disabled="taskName != '党工团审核'" />
                  </el-form-item>
                  <el-row class="sign-line" v-if="showFormItem('党工团审核')">
                    <el-col :span="6" :offset="11">
                      签名：<span class="auditor">{{ form.unionUser ? form.unionUser.nickName : unionUser }}</span>
                    </el-col>
                    <el-col :span="6">
                      日期：<span>{{ form.unionTime ? form.unionTime : unionTime }}</span>
                    </el-col>
                  </el-row>
                </td>
              </tr>

              <tr>
                <td colspan="2" class="label-cell">财务部处理</td>
                <td colspan="10">
                  <div class="table-form-item">
                    <div class="sub-label">支付凭证</div>
                    <el-form-item prop="lendDocument" class="table-form-item">
                      <FileUpload v-if="taskName == '财务处理'" :disabled="taskName != '财务处理'" :limit="1"
                        :filePathName="'借款/支付凭证'" :isShowTip="false"
                        :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']" @input="getLendPath">
                      </FileUpload>
                      <div v-if="form.lendDocument && taskName != '财务处理'">
                        <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>
                    <div class="sub-label">支付备注</div>
                    <el-form-item prop="cwComment" class="table-form-item">
                      <el-input type="textarea" v-model="form.cwComment" placeholder="请输入财务部支付备注"
                        :disabled="taskName != '财务处理'" :autosize="{ minRows: 2 }" />
                    </el-form-item>
                  </div>
                  <el-row class="sign-line" v-if="showFormItem('财务处理')">
                    <el-col :span="6" :offset="11">
                      经办人：<span class="auditor">{{ form.cwUser ? form.cwUser.nickName : cwUser }}</span>
                    </el-col>
                    <el-col :span="6">
                      支付日期：
                      <el-form-item prop="lendTime" class="table-form-item inline-item">
                        <el-date-picker style="width: 160px;" v-model="form.lendTime" value-format="yyyy-MM-dd"
                          type="date" placeholder="选择日期" :disabled="taskName != '财务处理'">
                        </el-date-picker>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </td>
              </tr>
            </table>
          </div>
        </el-form>
        <div class="form-footer" v-if="taskName != ''">
          <el-button type="warning" @click="saves()">保 存</el-button>
          <el-button type="danger" v-if="taskName != '借款申请'" @click="returnOpen = true">退 回</el-button>
          <el-button type="primary" @click="submitForm">提 交</el-button>
        </div>
      </el-col>
      <el-col :span="24" :md="6" 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>
    <el-dialog title="打印预览" :visible.sync="printOpen" width="70%" append-to-body>
      <borrow-print :form="form" :exceed="exceed" :chooseProject="chooseProject" :detailList="detailList"
        @cancel="printOpen = false"></borrow-print>
    </el-dialog>
    <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>
    <el-dialog title="新增开支项" :visible.sync="openNewExpense" width="400px" append-to-body>
      <el-form ref="newExpenseForm" :model="newExpenseForm" :rules="newExpenseRules" label-width="120px">
        <el-form-item label="开支项名称" prop="name">
          <el-input v-model="newExpenseForm.name" placeholder="请输入开支项名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitNewExpense">确 定</el-button>
        <el-button @click="openNewExpense = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="查看预算" :visible.sync="openBudget" width="65%" append-to-body>
      <new-budget-info :taskForm="budgetTaskForm" :taskName="''" v-if="budgetTaskForm.formId"></new-budget-info>
      <div v-else>
        <el-empty description="暂无预算信息" />
      </div>
    </el-dialog>
    <el-drawer title="查看历史借款" :visible.sync="openBorrow" direction="rtl" size="35%" append-to-body>
      <history-borrow :historyBorrowList="historyBorrowList"></history-borrow>
    </el-drawer>
    <el-button type="success" @click="printOpen = true">打印</el-button>
  </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 { addData, getDicts } from "@/api/system/dict/data";
import { listSite, delSite } from "@/api/oa/budget/budgetSite.js";
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';
import BorrowPrint from '../components/print/borrowPrint.vue';
import ReturnComment from '@/views/flowable/form/components/flowBtn/returnComment.vue';
import ReturnBtn from '@/views/flowable/form/components/flowBtn/returnBtn.vue';
import newBudgetInfo from '@/views/flowable/form/budget/adjust/newBudgetInfo.vue';
import HistoryBorrow from './historyBorrow.vue';
import { sendQyMessage } from "@/api/qywx/index"
import { getUser } from "@/api/system/user"

export default {
  dicts: ['cmc_borrow_expense', 'cmc_unit'],
  components: {
    flow,
    projectChoose,
    FileItem,
    BorrowPrint,
    ReturnComment,
    ReturnBtn,
    newBudgetInfo,
    HistoryBorrow
  },
  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, //是否超预算
      need: true, //是否需要分管审批
      deptId: undefined,
      dgtLabel: '工会审核意见',
      siteExpenses: 0,
      hasBorrow: 0,
      printOpen: false,
      showAlter: true,
      returnOpen: false,
      borrowItemList: [],
      openNewExpense: false,
      newExpenseForm: {
        name: ''
      },
      newExpenseRules: {
        name: [
          { required: true, message: '请输入开支项名称', trigger: 'blur' }
        ]
      },
      openBudget: false,
      budgetTaskForm: {
        formId: '',
      },
      openBorrow: false,
      historyBorrowList: [],
    };
  },
  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 = {
          remark: [
            { required: true, message: '请输入说明', trigger: 'blur' },
          ],
        }
      } else if (this.taskName == '部门审核') {
        this.rules = {
          deptComment: [
            { required: true, message: '请输入部门负责人意见', trigger: 'blur' },
          ],
        }
      } else if (this.taskName == '分管审核') {
        this.rules = {
          managerComment: [
            { required: true, message: '请输入分管领导审核意见', trigger: 'blur' }
          ],
          managerAmount: [
            { required: true, message: '请输入核准金额', trigger: 'blur' }
          ]
        }
      } else if (this.taskName == '总经理审核') {
        this.rules = {
          zjlComment: [
            { required: true, message: '请输入总经理审批意见', trigger: 'blur' }
          ],
          managerAmount: [
            { 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({ pageSize: 9999 }).then(res => {
        let oArray = res.rows.map(item => item.borrowItem).filter(item => item != null);
        let originalArray = [...new Set(oArray)]
        this.borrowItemList = originalArray.map((item) => ({
          value: item,      // 去除字符串前后空格
          label: item, // 转大写
        }));
      })
      Promise.all([
        listBorrowDetail({ pageSize: 999, borrowId: this.taskForm.formId }),
        getBorrow(this.taskForm.formId)
      ]).then(([detailRes, borrowRes]) => {
        if (detailRes.rows.length != 0) {
          this.detailList = detailRes.rows
        }
        if (this.isEmptyObject(borrowRes.data)) {
          this.formTotal = 0;
          this.form.applier = this.$store.getters.userId;
        }
        else {
          this.formTotal = 1;
          this.form = borrowRes.data;
          if (this.form.applyDept == 104) //董事长分管的综合事务部，跳过分管审批
            this.need = false;
          this.hanldeChangeType();
          this.handleSelectProject(borrowRes.data.projectId)
          this.getBudgetSettle()
        }
        this.initManagerReviewAmount();
        this.loading = false;
      })

    },
    async getBudgetSettle() {
      let budgetData = await listBudget({ projectId: this.form.projectId })
      if (budgetData.total == 1) {
        let budget = budgetData.rows[0];
        this.budgetTaskForm.formId = this.form.projectId;
        let siteRes = await listSite({ pageSize: 9999, budgetId: budget.budgetId });
        let maxExpense = siteRes.rows.reduce((sum, site) => sum + (Number(site.amount) || 0), 0);
        this.siteExpenses = maxExpense
      }
      if (budgetData.total == 0) {
        this.siteExpenses = 0
        this.budgetTaskForm.formId = '';
      }
      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);
        this.historyBorrowList = borrowList; //获取历史借款的列表
        borrowList.forEach(element => {
          if (element.managerAmount) {
            hasBorrow = hasBorrow + element.managerAmount
          }
          if (!element.managerAmount && element.applyAmount) {
            hasBorrow = hasBorrow + element.applyAmount
          }
        });
        this.hasBorrow = hasBorrow
      } else {
        this.hasBorrow = 0;
        this.historyBorrowList = [];
      }
      if (this.form.borrowUsage == '0') {
        if ((this.siteExpenses - this.hasBorrow - this.form.applyAmount) < 0) {
          this.exceed = true;
        } else {
          this.exceed = false;
        }
      } else {
        this.exceed = false;
      }
    },
    // 查询项目列表
    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: '',
      });
    },
    // 保存
    async saves() {
      if (this.formTotal == 0) {
        this.form.borrowId = this.taskForm.formId;
        await addBorrow(this.form)
        // 更新借款明细项
        await delBorrowDetail(this.taskForm.formId)
        for (let detail of this.detailList) {
          detail.borrowId = this.taskForm.formId;
          await addBorrowDetail(detail);
        }
        this.initForm();
      } else {
        // 更新借款审批表
        await updateBorrow(this.form);
        // 更新借款明细项
        await delBorrowDetail(this.taskForm.formId)
        for (let detail of this.detailList) {
          detail.borrowId = this.taskForm.formId;
          await addBorrowDetail(detail);
        }
      }
      this.$message.success('保存成功')
    },
    /** 提交按钮 */
    async submitForm() {
      if (this.taskName == '借款申请') {
        await this.VerificationAmount();
      }
      let msg;
      if (this.taskName == '财务处理') {
        msg = '最后一个节点，提交将结束流程，是否提交？'
      } else {
        msg = '是否提交到下一个流程？'
      }
      this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        type: 'warning'
      }).then(async () => {
        this.$refs["form"].validate(async (valid) => {
          if (valid) {
            if (this.form.borrowUsage == '0' && !this.form.projectId) {
              this.$message.error('请选择项目！')
              return
            }
            let formData = new FormData();
            let message = ''
            let userIds = [];
            let userString = []
            if (this.formTotal != 0) {
              // 更新借款明细项
              delBorrowDetail(this.taskForm.formId).then(res => {
                this.detailList.forEach(detail => {
                  detail.borrowId = this.taskForm.formId;
                  addBorrowDetail(detail)
                })
              })
              if (this.taskName == '部门审核') {
                this.form.deptUserId = this.$store.getters.userId;
                this.form.deptTime = parseTime(new Date(), '{y}-{m}-{d}')
              }
              if (this.taskName == '分管审核') {
                this.form.managerUserId = this.$store.getters.userId;
                this.form.managerTime = parseTime(new Date(), '{y}-{m}-{d}')
              }
              if (this.taskName == '总经理审核') {
                this.form.zjlUserId = this.$store.getters.userId;
                this.form.zjlTime = parseTime(new Date(), '{y}-{m}-{d}')
              }
              if (this.taskName == '董事长批准') {
                this.form.dszUserId = this.$store.getters.userId;
                this.form.dszTime = parseTime(new Date(), '{y}-{m}-{d}')
              }
              if (this.taskName == '党工团审核') {
                this.form.unionUserId = this.$store.getters.userId;
                this.form.unionTime = parseTime(new Date(), '{y}-{m}-{d}')
              }
              if (this.taskName == '财务处理') {
                this.form.cwUserId = this.$store.getters.userId;
                this.form.lendTime = parseTime(new Date(), '{y}-{m}-{d}')
              }
              // 更新借款审批表
              updateBorrow(this.form);
              const params = { taskId: this.taskForm.taskId };
              const res = await getNextFlowNode(params);
              if (this.taskName == '借款申请') {
                let userId = await this.borrowAprrovalFun()
                userIds.push(userId);
              }
              else if (this.taskName == '部门审核') {
                this.$set(this.taskForm.variables, "need", this.need);
                if (this.need) {
                  const res1 = await getUsersManageLeaderByDept({ deptId: this.form.applyDept });
                  if (res1.data) {
                    res1.data.forEach(item => {
                      userIds.push(item.userId)
                    })
                  }
                  this.$set(this.taskForm.variables, "approvalList", userIds);
                  this.handleComplete(this.taskForm);
                }
                else {
                  const res1 = await getUsersManageLeaderByDept({ deptId: this.form.applyDept });
                  if (res1.data) {
                    res1.data.forEach(item => {
                      userIds.push(item.userId)
                    })
                  }
                  this.$set(this.taskForm.variables, "approvalList", userIds);
                  const res2 = await getUserByPost({ postName: '总经理' });
                  userIds = []
                  userIds.push(res2.data[0].userId)
                  this.$set(this.taskForm.variables, "approval", res2.data[0].userId);
                  this.handleComplete(this.taskForm);
                }
              }
              else if (this.taskName == '分管审核') {
                const res1 = await getUserByPost({ postName: '总经理' });
                userIds.push(res1.data[0].userId)
                this.$set(this.taskForm.variables, "approval", res1.data[0].userId);
                this.handleComplete(this.taskForm);
              }
              else if (this.taskName == '总经理审核') {
                this.$set(this.taskForm.variables, "exceed", this.exceed);
                if (!this.exceed) {
                  userIds = await this.submitFD();
                }
                else {
                  const res1 = await getUserByPost({ postName: '董事长' });
                  userIds.push(res1.data[0].userId)
                  this.$set(this.taskForm.variables, "approval", res1.data[0].userId);
                  this.handleComplete(this.taskForm);
                }
              }
              else if (this.taskName == '董事长批准') {
                userIds = await this.submitFD();
              }
              else if (this.taskName == '党工团审核') {
                userIds = await this.submitFD();
              }
              else if (this.taskName == '财务处理') {
                this.handleComplete(this.taskForm);
              }
              for (let u of userIds) {
                let { data } = await getUser(u)
                userString.push(data.pinyin)
              }
              message = "您有一条新的借款申请： \n>" +
                "申请人：<font color='info'>" + this.getUserName(this.form.applier) + "</font> \n>" +
                "借款金额：<font color='warning'>" + (this.form.managerAmount ? this.form.managerAmount : this.form.applyAmount) + "</font> 元 \n>" +
                "借款说明：" + (this.form.applyReason ? this.form.applyReason : this.form.remark) + " \n>" +
                "\n>" +
                "已办流程：<font color='comment'>" + this.taskName + "</font> \n>";
              formData.append('message', message)
              formData.append('userString', userString.join('|') + '|YuSiHan|WangRongHua')

              if (userIds.length > 0)
                await sendQyMessage(formData);

            } else {
              delBorrowDetail(this.taskForm.formId).then(() => {
                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 };
              // 提交到下一个流程
              const res = await getNextFlowNode(params);
              let userId = await this.borrowAprrovalFun()
              userIds.push(userId);
              for (let u of userIds) {
                let { data } = await getUser(u)
                userString.push(data.pinyin)
              }
              message = "您有一条新的借款申请： \n>" +
                "申请人：<font color='info'>" + this.getUserName(this.form.applier) + "</font> \n>" +
                "借款金额：<font color='warning'>" + (this.form.managerAmount ? this.form.managerAmount : this.form.applyAmount) + "</font> 元 \n>" +
                "借款说明：" + (this.form.applyReason ? this.form.applyReason : this.form.remark) + " \n>" +
                "\n>" +
                "已办流程：<font color='comment'>" + this.taskName + "</font> \n>";
              formData.append('message', message)
              formData.append('userString', userString.join('|') + '|YuSiHan|WangRongHua')

              if (userIds.length > 0)
                await sendQyMessage(formData);
            }
          } else {
            this.$message.error('请完善必填项')
          }
        });
      })
    },
    handleComplete(taskForm) {
      complete(taskForm).then(response => {
        this.$modal.msgSuccess(response.msg);
        this.$emit('goBack');
      })
    },
    // 借款申请提交方法
    async borrowAprrovalFun() {
      let userId = 0;
      // 如果是党工团申请 deptId == 0 为党工团申请
      if (this.deptId == 0) {
        // 2为工会、3为党委
        if (this.form.borrowUsage == 2 || this.form.borrowUsage == 3) {
          const res = await getUserByPost({ postName: '党总支书记' });
          userId = res.data[0].userId;
        } else {
          const res = await getUserByPost({ postName: '团支部书记' });
          userId = res.data[0].userId;
        }
        this.$set(this.taskForm.variables, "dept", this.deptId);
        this.$set(this.taskForm.variables, "approval", userId);
        this.handleComplete(this.taskForm);
      } else if (this.deptId == 102) { //如果是经营管理层申请，走总经理审批
        this.form.managerAmount = this.form.applyAmount;
        await updateBorrow(this.form);
        const res = await getUserByPost({ postName: '总经理' });
        userId = res.data[0].userId;
        this.$set(this.taskForm.variables, "dept", this.deptId);
        this.$set(this.taskForm.variables, "approval", userId);
        this.handleComplete(this.taskForm);
      } else if (this.deptId == 101) {//如果是董事会申请，走董事长批准
        const res = await getUserByPost({ postName: '董事长' });
        userId = res.data[0].userId;
        this.$set(this.taskForm.variables, "dept", this.deptId);
        this.$set(this.taskForm.variables, "approval", userId);
        this.$set(this.taskForm.variables, "exceed", true);
        this.handleComplete(this.taskForm);
      }
      else { //普通员工申请项目借款
        const res = await getUsersDeptLeader({ userId: this.$store.getters.userId });
        userId = res.data.userId;
        this.$set(this.taskForm.variables, "approval", userId);
        this.$set(this.taskForm.variables, "dept", this.deptId);
        this.handleComplete(this.taskForm);
      }
      return userId
    },
    // 提交给财务部审核
    async submitFD() {
      let approvalList = [];
      const res = await getUsersDeptLeaderByDept({ deptId: 106 });
      approvalList.push(res.data.userId);
      const res1 = await getUsersViceDeptLeaderByDept({ deptId: 106 });
      approvalList.push(res1.data.userId);
      this.$set(this.taskForm.variables, "approvalList", approvalList);
      this.handleComplete(this.taskForm);
      return approvalList
    },
    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.$set(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() {
      this.getTotal("managerAmount", "managerAmount", this.detailList);
    },
    initManagerReviewAmount() {
      if (this.taskName !== '分管审核') return;
      if (this.form.borrowUsage != '0' && this.form.borrowUsage != '1') return;
      this.detailList.forEach(detail => {
        if (detail.managerAmount === '' || detail.managerAmount === null || detail.managerAmount === undefined) {
          this.$set(detail, 'managerAmount', detail.applyAmount);
        }
      });
      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);
    },
    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.siteExpenses - this.hasBorrow)) {
          return this.$confirm('借款总额已经超过项目预算，将走《超预算或预算外支付（报销）》流程，即需要董事长批准，才可到财务。', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          }).then(() => {
            this.exceed = true;
            this.$set(this.taskForm.variables, "exceed", true);
            return '1'
          }).catch(() => {
            return
          })
        } else {
          this.exceed = false;
          this.$set(this.taskForm.variables, "exceed", false);
          return
        }
      }
    },
    // 计算超过预算的金额
    getMoreAmount(type) {
      let result;
      if (type == '0') {
        result = this.form.applyAmount - (this.siteExpenses - this.hasBorrow);
      } else {
        result = this.form.managerAmount - (this.siteExpenses - this.hasBorrow);
      }
      return result.toFixed(2)
    },
    isReturn(val) {
      this.showAlter = val
    },
    commentByRole() {
      if (this.taskName == '部门审核') {
        return this.form.deptComment
      } else if (this.taskName == '分管审核') {
        return this.form.managerComment
      } else if (this.taskName == '总经理审核') {
        return this.form.zjlComment
      } else if (this.taskName == '董事长批准') {
        return this.form.dszComment
      } else if (this.taskName == '党工团审核') {
        return this.form.unionComment
      } else if (this.taskName == '财务处理') {
        return this.form.cwComment
      }
    },
    querySearchAsync(queryString, cb) {
      let borrowItemList = this.borrowItemList;
      let results = queryString ? borrowItemList.filter(this.createFilter(queryString)) : borrowItemList;
      cb(results)
    },
    createFilter(queryString) {
      return (borrowItem) => {
        return (borrowItem.value.indexOf(queryString) === 0);
      };
    },
    handleExpenseChange(value) {
      if (value === 'new_expense') {
        this.openNewExpense = true;
      }
    },
    submitNewExpense() {
      this.$refs["newExpenseForm"].validate(valid => {
        if (valid) {
          let length = this.dict.type.cmc_borrow_expense.length;
          this.newExpenseForm.dictType = 'cmc_borrow_expense';
          this.newExpenseForm.dictLabel = this.newExpenseForm.name;
          this.newExpenseForm.dictValue = this.newExpenseForm.name;
          this.newExpenseForm.listClass = 'default'
          this.newExpenseForm.dictSort = length;
          addData(this.newExpenseForm).then(res => {
            this.$modal.msgSuccess("新增成功");
            this.openNewExpense = false;
            this.newExpenseForm.name = '';
            // 刷新字典数据
            getDicts("cmc_borrow_expense").then(res => {
              let arr = [];
              for (let i = 0; i < res.data.length; i++) {
                arr.push({
                  label: res.data[i].dictLabel,
                  value: res.data[i].dictValue,
                  raw: res.data[i]
                })
              }
              this.dict.type.cmc_borrow_expense = arr;
            })
          })
        }
      })
    }
  }
};
</script>

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

$border-light: #dcdfe6;
$border-soft: #e4e7ed;
$label-bg: #f0f2f5;
$label-color: #606266;
$text-primary: #303133;
$text-secondary: #909399;
$accent: #409eff;

.borrow-table-form {
  margin-top: 16px;

  .table-form-item {
    margin-bottom: 0;

    ::v-deep .el-form-item__content {
      margin-left: 0 !important;
      line-height: normal;
    }

    ::v-deep .el-form-item__error {
      position: relative;
      padding-top: 2px;
    }
  }

  ::v-deep .el-input__inner,
  ::v-deep .el-textarea__inner {
    border-color: $border-light;
    border-radius: 6px;
    transition: border-color 0.2s, box-shadow 0.2s;

    &:hover {
      border-color: #c0c4cc;
    }

    &:focus {
      border-color: $accent;
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.12);
    }
  }

  ::v-deep .el-input.is-disabled .el-input__inner,
  ::v-deep .el-textarea.is-disabled .el-textarea__inner {
    background-color: #f5f7fa;
    color: #606266;
  }

  .inline-item {
    display: inline-block;
    vertical-align: middle;
  }

  .exceed-tip {
    display: block;
    margin-top: 4px;
    color: #f56c6c;
    font-size: 12px;
  }

  .sub-label {
    margin: 8px 0 4px;
    font-size: 13px;
    color: $label-color;
    font-weight: 500;

    &:first-child {
      margin-top: 0;
    }
  }
}

.form-table-wrap {
  border: 1px solid $border-soft;
  border-radius: 10px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

.form-table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
  font-size: 14px;
  color: $text-primary;

  tr {
    transition: background-color 0.15s;
  }

  tr:hover td:not(.label-cell) {
    background-color: #fafcff;
  }

  td {
    padding: 12px 14px;
    border-bottom: 1px solid $border-light;
    vertical-align: middle;
    word-break: break-word;
    background: #fff;
  }

  tr:last-child td {
    border-bottom: none;
  }

  .label-cell {
    width: 110px;
    text-align: right;
    font-size: 13px;
    font-weight: 600;
    color: $label-color;
    background-color: $label-bg;
    border-right: 1px solid $border-light;
    white-space: nowrap;
  }
}

.inner-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  margin-top: 8px;
  font-size: 13px;
  border: 1px solid $border-light;
  border-radius: 8px;
  overflow: hidden;

  td {
    padding: 8px 12px;
    border-bottom: 1px solid $border-light;
    border-right: 1px solid $border-light;
    vertical-align: middle;
    background: #fff;
  }

  tr:last-child td {
    border-bottom: none;
  }

  td:last-child {
    border-right: none;
  }

  .label-cell {
    text-align: center;
    font-weight: 600;
    font-size: 12px;
    color: $label-color;
    background-color: $label-bg;
    white-space: nowrap;
  }
}

.detail-inner-table {
  text-align: center;

  tr:first-child td {
    background: $label-bg;
    color: $label-color;
    font-size: 12px;
    font-weight: 600;
    padding: 9px 8px;
  }

  tbody tr:hover td {
    background-color: #f5f9ff;
  }

  td {
    padding: 8px 10px;
  }
}

.budget-row {

  td.budget-value-cell,
  td:not(.label-cell) {
    // background-color: #f5f7fa;
  }

  .budget-value-cell {
    padding: 10px 12px;
    overflow: hidden;
    vertical-align: top;
  }

  .budget-amount {
    display: flex;
    flex-direction: column;
    gap: 4px;
    line-height: 1.45;
    word-break: break-all;
    overflow-wrap: anywhere;
  }

  .amount-num {
    display: block;
    font-size: 15px;
    font-weight: 600;
    color: $text-primary;
    letter-spacing: 0.02em;
  }

  .amount-cn {
    display: block;
    font-size: 12px;
    color: $text-secondary;
    white-space: normal;
  }

  .budget-amount.is-danger .amount-num {
    color: #f56c6c;
  }

  .budget-amount.is-success .amount-num {
    color: #67c23a;
  }

  .budget-link-btn {
    margin-top: 6px;
    padding: 0;
    font-size: 12px;
    color: $accent;
    white-space: normal;
    line-height: 1.3;
    text-align: left;

    &:hover {
      color: #66b1ff;
    }
  }
}

.sign-line {
  margin-top: 12px;
  padding-top: 10px;
  border-top: 1px solid $border-light;
  font-size: 13px;
  color: $label-color;
  line-height: 26px;

  .auditor {
    color: $text-primary;
    font-weight: 500;
  }
}

.form-footer {
  margin-top: 24px;
  padding-bottom: 20px;
  text-align: center;
}
</style>