<!--
 * @Author: ysh
 * @Date: 2025-02-20 10:20:22
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-03-26 16:08:38
-->
<template>
  <view class="form-container">
    <!-- 表单标题 -->
    <view class="form-title">
      <text class="title-text">借款审批</text>
      <view class="title-line"></view>
    </view>
    <!-- 表单内容 -->
    <uni-forms ref="form" :modelValue="form" :rules="rules" label-position="top" label-width="150" class="custom-form">
      <flow-note :taskForm="taskForm" v-if="taskName"></flow-note>
      <!-- 当前节点 -->
      <uni-forms-item label="当前节点" class="form-item" v-if="taskName">
        <uni-tag :inverted="true" type="primary" :text="taskName"></uni-tag>
      </uni-forms-item>

      <!-- 流程发起人 -->
      <uni-forms-item label="填报人" class="form-item">
        <b style="font-size:35rpx;">{{ applierUserName }}</b>
      </uni-forms-item>

      <!-- 填报日期 -->
      <uni-forms-item label="填报日期" class="form-item">
        <text>{{ form.applyDate }}</text>
      </uni-forms-item>

      <!-- 借款类型 -->
      <uni-forms-item label="借款类型" required class="form-item" name="borrowUsage">
        <uni-data-checkbox v-model="form.borrowUsage" :localdata="borrowUsageOptions" :disabled="taskName != '借款申请'"
          @change="hanldeChangeType"></uni-data-checkbox>
      </uni-forms-item>

      <!-- 借款事由 -->
      <uni-forms-item label="借款事由" required class="form-item" name="applyReason" v-if="form.borrowUsage != 0">
        <uv-textarea v-model="form.applyReason" placeholder="请输入借款事由" :disabled="taskName != '借款申请'"></uv-textarea>
      </uni-forms-item>

      <!-- 选择项目 -->
      <uni-forms-item label="选择项目" required class="form-item" v-if="form.borrowUsage == 0" name="projectId">
        <u-button type="primary" @click="openProject = true" v-if="taskName == '借款申请'">+ 选择项目</u-button>
        <ProjectPicker :visible.sync="openProject" :selected.sync="selectedProject" @confirm="handleConfirm" />
        <ProjectInfo :project="projectObj"></ProjectInfo>
      </uni-forms-item>

      <!-- 借款明细 -->
      <uni-forms-item label="借款明细" required class="form-item">
        <BorrowDetail :borrowId="form.borrowId" :taskName="taskName" @getApplyAmount="setApplyAmount"
          @getManagerAmount="setManagerAmount"></BorrowDetail>
      </uni-forms-item>

      <!-- 最大借款金额限制 -->
      <uni-forms-item label="最大借款金额" class="form-item" v-if="form.borrowUsage == '0'">
        <view class="amount-text">¥ {{ totalBudget.toFixed(2) }}</view>
      </uni-forms-item>
      <uni-forms-item label="已申请借款" class="form-item" v-if="form.borrowUsage == '0'">
        <view class="amount-text">¥ {{ hasBorrow.toFixed(2) }}</view>
      </uni-forms-item>
      <uni-forms-item label="可用借款" class="form-item" v-if="form.borrowUsage == '0'">
        <view class="amount-text">¥ {{ (totalBudget - hasBorrow).toFixed(2) }}</view>
      </uni-forms-item>
      <uni-forms-item label="申请金额" required class="form-item">
        <view class="amount-text">¥ {{ (this.form.applyAmount ? this.form.applyAmount : 0).toFixed(2) }}</view>
        <view class="warning-text" v-if="exceed && form.borrowUsage == '0'">
          超过预算金额：¥ {{ getMoreAmount('0') }}
        </view>
      </uni-forms-item>
      <uni-forms-item label="校准金额" required class="form-item"
        v-if="taskName != '借款申请' && taskName != '部门审核' && taskName != '党工团审核'">
        <view class="amount-text">¥ {{ (this.form.managerAmount ? this.form.managerAmount : 0).toFixed(2) }}</view>
        <view class="warning-text" v-if="exceed && form.borrowUsage == '0'">
          超过预算金额：¥ {{ getMoreAmount('1') }}
        </view>
      </uni-forms-item>

      <!-- 申请人说明 -->
      <uni-forms-item label="申请人说明" required class="form-item" name="remark">
        <uv-textarea v-model="form.remark" placeholder="请输入申请人说明" :disabled="taskName != '借款申请'"></uv-textarea>
      </uni-forms-item>

      <!-- 附件上传 -->
      <uni-forms-item label="附件上传" class="form-item" name="borrowDocument">
        <file-upload :fileType="'借款/申请附件'" :showBtn="taskName == '借款申请'" :fileName="form.borrowDocument"
          @deleteFile="form.borrowDocument = ''" @success="uploadSuccess"></file-upload>
      </uni-forms-item>

      <view v-if="form.borrowUsage == '0' || form.borrowUsage == '1'">
        <!-- 部门审核 -->
        <uni-forms-item label="部门负责人意见" required class="form-item" v-if="taskName != '借款申请'" name="deptComment">
          <uv-textarea v-model="form.deptComment" placeholder="请输入部门负责人意见" :disabled="taskName != '部门审核'"></uv-textarea>
          <auditor :name="form.deptUser ? form.deptUser.nickName : ''" :time="form.deptTime"></auditor>
        </uni-forms-item>

        <!-- 分管审核 -->
        <uni-forms-item label="分管领导审核意见" required class="form-item" v-if="taskName != '借款申请'" name="managerComment">
          <uv-textarea v-model="form.managerComment" placeholder="请输入分管领导审核意见"
            :disabled="taskName != '分管审核'"></uv-textarea>
          <auditor :name="form.managerUser ? form.managerUser.nickName : ''" :time="form.managerTime"></auditor>
        </uni-forms-item>

        <!-- 总经理审核 -->
        <uni-forms-item label="总经理审核意见" required class="form-item" v-if="taskName != '借款申请'" name="zjlComment">
          <uv-textarea v-model="form.zjlComment" placeholder="请输入总经理审核意见" :disabled="taskName != '总经理审核'"></uv-textarea>
          <auditor :name="form.zjlUser ? form.zjlUser.nickName : ''" :time="form.zjlTime"></auditor>
        </uni-forms-item>
      </view>

      <!-- 党工团审核 -->
      <view v-if="form.borrowUsage != '0' && form.borrowUsage != '1'">
        <uni-forms-item :label="dgtLabel" required class="form-item" v-if="taskName != '借款申请'" name="unionComment">
          <uv-textarea v-model="form.unionComment" placeholder="请输入审核意见" :disabled="taskName != '党工团审核'"></uv-textarea>
          <auditor :name="form.unionUser ? form.unionUser.nickName : ''" :time="form.unionTime"></auditor>
        </uni-forms-item>
      </view>

      <!-- 财务处理 -->
      <uni-forms-item label="财务部支付备注" class="form-item" v-if="taskName != '借款申请'" name="cwComment">
        <uv-textarea v-model="form.cwComment" placeholder="请输入财务部支付备注" :disabled="taskName != '财务处理'"></uv-textarea>
      </uni-forms-item>
      <uni-forms-item label="支付时间" required class="form-item" v-if="taskName != '借款申请'" name="lendTime">
        <uni-datetime-picker type="date" :clear-icon="false" v-model="form.lendTime" :disabled="taskName != '财务处理'" />
        <auditor :name="form.cwUser ? form.cwUser.nickName : ''" :time="form.lendTime"></auditor>
      </uni-forms-item>

      <!-- 操作栏 -->
      <view class="form-button" v-if="taskName">
        <u-button type="warning" size="normal" @click="saves" style="margin-right: 10px" v-if="taskName">保存</u-button>
        <u-button type="error" size="normal" style="margin-right: 10px" @click="$refs.returnPopup.open()"
          v-if="taskName != '借款申请'">退回</u-button>
        <u-button type="primary" size="normal" @click="submit">{{ taskName == '借款申请' ? '提交申请' : '提交审核' }}</u-button>
      </view>
    </uni-forms>

    <!-- 退回弹窗 -->
    <uni-popup ref="returnPopup" background-color="#fff">
      <return-popup @cancel="$refs.returnPopup.close()" :taskForm="taskForm" :comment="commentByRole()"
        @goBack="goHome"></return-popup>
    </uni-popup>

  </view>
</template>

<script>
import { parseTime } from "@/utils/common.js"
import { listBudget } from "@/api/oa/budget/budget";
import ProjectInfo from '@/pages/components/ProjectInfo.vue';
import { complete, getNextFlowNode } from "@/api/flowable/todo";
import ProjectPicker from '@/pages/components/ProjectPicker.vue';
import { listProject, getProject } from "@/api/oa/project/project";
import { listBorrow, getBorrow, delBorrow, addBorrow, updateBorrow } from "@/api/oa/borrow/borrow";
import { getUserByPost, getUsersDeptLeader, getUsersDeptLeaderByDept, getUsersViceDeptLeaderByDept, getUsersManageLeaderByDept } from '@/api/system/post.js'
import BorrowDetail from './borrowDetail.vue';
import FlowNote from '@/pages/components/flowNote.vue';
import ReturnPopup from '@/pages/components/returnPopup.vue';
import FileUpload from '@/pages/components/fileUpload.vue';
import Auditor from "@/pages/components/auditor.vue";
export default {
  components: {
    ProjectPicker,
    ProjectInfo,
    BorrowDetail,
    FlowNote,
    ReturnPopup,
    FileUpload,
    Auditor
  },
  props: {
    taskForm: Object,
    taskName: String, // 当前节点
    startUserName: String, // 流程发起人
  },
  created() {
    this.form.borrowId = this.taskForm.formId;
    this.deptId = this.$store.getters.deptId;
    this.applierUserName = this.startUserName;
    this.initForm();
    this.initRules();
    uni.setNavigationBarTitle({
      title: '借款审批'
    });
  },
  watch: {
    form: {
      handler(newVal) {
        this.initRules();
      },
      deep: true // 启用深度监测
    }
  },
  data() {
    return {
      applierUserName:'',
      form: {
        submitTime: '',
        borrowUsage: '0',
        applyAmount: 0,
        managerAmount: 0,
        remark: '',
        applyDate: ''
      },
      rules: {},
      borrowUsageOptions: [{
        text: '项目借款',
        value: '0',
        disable: false
      }, {
        text: '非项目借款',
        value: '1',
        disable: false
      }, {
        text: '工会借款',
        value: '2',
        disable: false
      }, {
        text: '党委借款',
        value: '3',
        disable: false
      }, {
        text: '团委借款',
        value: '4',
        disable: false
      }
      ],
      openProject: false,
      selectedProject: null, //选中的项目
      projectObj: {}, //项目信息的项目
      formTotal: 0,
      totalBudget: 0, //预结算额
      exceed: false, //是否超预算
      hasBorrow: 0, //已申请借款
      deptId: undefined,
      returnBack: false,
      dgtLabel: '工会审核意见',
    }
  },
  methods: {
    initRules() {
      this.rules = {
        // 借款类型验证（必填）
        borrowUsage: {
          rules: [{
            required: true,
            errorMessage: '请选择借款类型'
          }]
        },
        // 借款事由验证（当 borrowUsage != 0 时必填）
        applyReason: {
          rules: [{
            required: this.form.borrowUsage != '0', // 动态控制必填
            errorMessage: '请输入借款事由'
          }]
        },
        // 项目选择验证（当 borrowUsage == 0 时必填）
        projectId: {
          rules: [{
            required: this.form.borrowUsage == '0', // 动态控制必填
            errorMessage: '请选择项目'
          }]
        },
        // 申请人说明验证（必填）
        remark: {
          rules: [{
            required: true,
            errorMessage: '请输入申请人说明'
          }]
        },
        // 部门意见验证（仅在部门审核步骤必填）
        deptComment: {
          rules: [{
            required: this.taskName === '部门审核',
            errorMessage: '请输入部门意见'
          }]
        },
        // 分管意见验证（仅在分管审核步骤必填）
        managerComment: {
          rules: [{
            required: this.taskName === '分管审核',
            errorMessage: '请输入分管意见'
          }]
        },
        // 总经理意见验证（仅在总经理审核步骤必填）
        zjlComment: {
          rules: [{
            required: this.taskName === '总经理审核',
            errorMessage: '请输入总经理意见'
          }]
        },
        lendTime: {
          rules: [{
            required: this.taskName === '财务处理',
            errorMessage: '请选择支付时间'
          }]
        }
      }
    },
    async initForm() {
      getBorrow(this.taskForm.formId).then(async res => {
        if (res.data) {
          this.formTotal = 1;
          this.form = res.data;
          if (!this.applierUserName) {
            this.applierUserName = this.form.applierUser.nickName;
          }
          this.hanldeChangeType();
          if (this.form.projectId) {
            getProject(this.form.projectId).then(res => {
              if (res.data) {
                this.selectedProject = res.data;
                this.projectObj = res.data;
              }
            })
            let budgetData = await listBudget({ projectId: this.form.projectId })
            if (budgetData.total == 1) {
              let budget = budgetData.rows[0];
              this.totalBudget = budget.settleExpense
            } else if (budgetData.total == 0) {
              this.totalBudget = 0
            }
            if (this.form.borrowUsage == '0') {
              if ((this.totalBudget - this.form.applyAmount) < 0) {
                this.exceed = true;
              } else {
                this.exceed = false;
              }
            } else {
              this.exceed = false;
            }
            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
            }
          }
        } else {
          this.formTotal = 0;
          this.form.applier = this.$store.getters.userId;
          this.form.applyDate = parseTime(new Date(), "{y}-{m}-{d}");
        }
      })

    },
    hanldeChangeType() {
      if (this.form.borrowUsage == '2') {
        this.dgtLabel = '工会审核意见'
      } else if (this.form.borrowUsage == '3') {
        this.dgtLabel = '党委审核意见'
      } else {
        this.dgtLabel = '团委审核意见'
      }
    },
    // 计算超过预算的金额
    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)
    },
    setApplyAmount(val) {
      this.form.applyAmount = val
    },
    setManagerAmount(val) {
      this.form.managerAmount = val
    },
    handleConfirm(project) {
      this.selectedProject = project;
      this.projectObj = project;
      this.form.projectId = project.projectId;
    },
    // 保存
    async saves() {
      if (this.formTotal == 0) {
        this.form.borrowId = this.taskForm.formId;
        await addBorrow(this.form)
        this.initForm();
      } else {
        // 更新借款审批表
        await updateBorrow(this.form);
      }
      this.$modal.msgSuccess('保存成功');
    },
    submit() {
      // 显示确认提交对话框
      uni.showModal({
        title: '提示',
        content: '确认提交吗？',
        success: (res) => {
          if (!res.confirm) {
            return;
          }
          // 继续执行后续代码
          this.handleSubmit();
        }
      });
    },
    // 处理提交逻辑
    handleSubmit() {
      this.$refs.form.validate().then(async res => {
        if (this.formTotal != 0) {
          // 定义审核节点配置
          const auditConfig = {
            '部门审核': {
              userIdField: 'deptUserId',
              timeField: 'deptTime'
            },
            '分管审核': {
              userIdField: 'managerUserId',
              timeField: 'managerTime'
            },
            '总经理审核': {
              userIdField: 'zjlUserId',
              timeField: 'zjlTime'
            },
            '董事长批准': {
              userIdField: 'dszUserId',
              timeField: 'dszTime'
            },
            '党工团审核': {
              userIdField: 'unionUserId',
              timeField: 'unionTime'
            },
            '财务处理': {
              userIdField: 'cwUserId',
              timeField: 'lendTime'
            }
          }
          // 根据当前节点更新审核信息
          const currentConfig = auditConfig[this.taskName]
          if (currentConfig) {
            const currentUserId = this.$store.getters.userId
            const currentTime = parseTime(new Date(), '{y}-{m}-{d}')

            // 设置审核人和审核时间
            this.form[currentConfig.userIdField] = currentUserId
            this.form[currentConfig.timeField] = currentTime
          }
          // 更新借款申请
          await updateBorrow(this.form);
          const params = { taskId: this.taskForm.taskId };
          getNextFlowNode(params).then(async res => {
            // 处理不同的流程节点
            if (this.taskName == '借款申请') {
              // 处理借款申请节点
              await this.borrowApprovalFun();
            } else if (this.taskName == '部门审核') {
              // 得到分管领导根据部门
              const res = await getUsersManageLeaderByDept({ deptId: this.form.applyDept });
              let userIds = [];
              if (res.data) {
                res.data.forEach(item => {
                  userIds.push(item.userId)
                })
              }
              this.taskForm.variables.approvalList = userIds;
              this.handleComplete(this.taskForm);
            } else if (this.taskName == '分管审核') {
              // 得到总经理
              const res = await getUserByPost({ postName: '总经理' });
              this.taskForm.variables.approval = res.data[0].userId;
              this.handleComplete(this.taskForm);
            } else if (this.taskName == '总经理审核') {
              this.exceed = false;
              this.taskForm.variables.exceed = this.exceed;
              if (!this.exceed) {
                this.submitFD(); // 提交给财务部门
              } else {
                const res = await getUserByPost({ postName: '董事长' });
                this.taskForm.variables.approval = res.data[0].userId;
                this.handleComplete(this.taskForm);
              }
            } else if (this.taskName == '董事长批准' || this.taskName == '党工团审核') {
              this.submitFD(); // 提交给财务部门
            } else if (this.taskName == '财务处理') {
              uni.showModal({
                title: '提示',
                content: '最后一个节点，提交将结束流程，是否提交？',
                success: (res) => {
                  if (res.confirm) {
                    this.handleComplete(this.taskForm);
                  }
                }
              });
            }
          })

        }
      }).catch(err => {
        console.log('表单错误信息：', err);
      })
    },
    // 处理任务完成
    handleComplete(taskForm) {
      complete(taskForm).then(response => {
        this.$modal.msgSuccess(response.msg);
        this.goHome();
      })
    },
    // 借款申请提交方法
    async borrowApprovalFun() {
      let userId;
      if (this.form.borrowUsage == '2' || this.form.borrowUsage == '3' || this.form.borrowUsage == '4') {
        this.deptId = 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.taskForm.variables.dept = this.deptId;
        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: '总经理' });
        this.taskForm.variables.dept = this.deptId;
        this.taskForm.variables.approval = res.data[0].userId;
        this.handleComplete(this.taskForm);
      } else if (this.deptId == 101) { //如果是董事会申请，走董事长批准
        const res = await getUserByPost({ postName: '董事长' });
        this.taskForm.variables.dept = this.deptId;
        this.taskForm.variables.approval = res.data[0].userId;
        this.taskForm.variables.exceed = true;
        this.handleComplete(this.taskForm);
      } else { //普通员工申请项目借款
        const res = await getUsersDeptLeader({ userId: this.$store.getters.userId });
        let userId = res.data.userId;
        this.taskForm.variables.approval = userId;
        this.taskForm.variables.dept = this.deptId;
        this.handleComplete(this.taskForm);
      }
    },
    // 提交给财务部审核
    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.taskForm.variables.approvalList = approvalList;
      this.handleComplete(this.taskForm);
    },
    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
      }
    },
    goHome() {
      uni.switchTab({
        url: '/pages/message/index'
      })
    },
    uploadSuccess(fileName) {
      this.form.borrowDocument = fileName
      updateBorrow(this.form)
    }
  },
}
</script>

<style lang="scss" scoped>
.amount-text {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  text-align: right;
}

.warning-text {
  font-size: 14px;
  color: #ff0000;
  margin-top: 5px;
  text-align: right;
}

.form-button {
  display: flex;
}

.example-body {
  padding: 10px;
  background-color: #fff;
}
</style>