<!--
 * @Author: ysh
 * @Date: 2025-02-20 10:20:22
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-03-03 17:23:02
-->
<!--
 * @Author: ysh
 * @Date: 2025-02-20 10:20:22
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-03-03 17:19:59
-->
<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">
      <!-- 当前节点 -->
      <uni-forms-item label="当前节点" class="form-item">
        <uni-tag :inverted="true" type="primary" :text="taskName"></uni-tag>
      </uni-forms-item>

      <!-- 流程发起人 -->
      <uni-forms-item label="填报人" class="form-item">
        <uni-tag :inverted="true" type="primary" :text="startUserName"></uni-tag>
      </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 != '借款申请'"></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="请输入借款事由"></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"></BorrowDetail>
      </uni-forms-item>

      <uni-forms-item label="申请金额" required class="form-item">
        <view class="amount-text">¥ {{ (this.form.applyAmount).toFixed(2) }}</view>
        <view class="warning-text" v-if="exceed && form.borrowUsage == '0'">
          超过预算金额：¥ {{ getMoreAmount('0') }}
        </view>
      </uni-forms-item>

      <uni-forms-item label="最大借款金额" class="form-item">
        <view class="amount-text">¥ {{ totalBudget.toFixed(2) }}</view>
      </uni-forms-item>

      <uni-forms-item label="已申请借款" class="form-item">
        <view class="amount-text">¥ {{ hasBorrow.toFixed(2) }}</view>
      </uni-forms-item>

      <uni-forms-item label="可用借款" class="form-item">
        <view class="amount-text">¥ {{ (totalBudget - hasBorrow).toFixed(2) }}</view>
      </uni-forms-item>
      <uni-forms-item label="申请人说明" required class="form-item">
        <uv-textarea v-model="form.remark" placeholder="请输入申请人说明" :disabled="taskName != '借款申请'"></uv-textarea>
      </uni-forms-item>


      <uni-forms-item label="部门负责人意见" required class="form-item" v-if="taskName != '借款申请'">
        <uv-textarea v-model="form.deptComment" placeholder="请输入部门负责人意见"></uv-textarea>
      </uni-forms-item>

      <view class="form-button">
        <u-button type="warning" size="normal" @click="saves" style="margin-right: 10px"
          v-if="taskName == '借款申请'">保存</u-button>
        <u-button type="primary" size="normal" @click="submit">{{ taskName == '借款申请' ? '提交申请' : '提交审核' }}</u-button>
      </view>
    </uni-forms>

  </view>
</template>

<script>
import ProjectPicker from '@/pages/components/ProjectPicker.vue';
import ProjectInfo from '@/pages/components/ProjectInfo.vue';
import { parseTime } from "@/utils/common.js"
import { listBorrow, getBorrow, delBorrow, addBorrow, updateBorrow } from "@/api/oa/borrow/borrow";
import { listProject, getProject } from "@/api/oa/project/project";
import { listBudget } from "@/api/oa/budget/budget";
import { getUserByPost, getUsersDeptLeader, getUsersDeptLeaderByDept, getUsersViceDeptLeaderByDept, getUsersManageLeaderByDept } from '@/api/system/post.js'
import { complete, getNextFlowNode } from "@/api/flowable/todo";
import config from '@/config'
import BorrowDetail from './borrowDetail.vue';
export default {
  components: {
    ProjectPicker,
    ProjectInfo,
    BorrowDetail
  },
  props: {
    taskForm: Object,
    taskName: String, // 当前节点
    startUserName: String, // 流程发起人
  },
  created() {
    this.form.borrowId = this.taskForm.formId;
    this.deptId = this.$store.getters.deptId;
    this.initForm();
    uni.setNavigationBarTitle({
      title: '借款审批'
    });
  },
  data() {
    return {
      form: {
        submitTime: '',
        borrowUsage: '0',
        applyAmount: 0,
        remark: '',
      },
      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,
    }
  },
  methods: {
    async initForm() {
      getBorrow(this.taskForm.formId).then(async res => {
        if (res.data) {
          this.formTotal = 1;
          this.form = res.data;
          console.log(this.form);
          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}");
        }
      })

    },
    // 计算超过预算的金额
    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
    },
    handleConfirm(project) {
      console.log('选中的项目:', 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.form.borrowUsage == '0' && !this.form.projectId) {
          this.$modal.msgError('请选择项目！')
          return
        }
        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 };
          console.log('params', params);
          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.$emit('goBack');
      })
    },
    // 借款申请提交方法
    async borrowApprovalFun() {
      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.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.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);
    },
  },
}
</script>

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

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

.form-button {
  display: flex;
}

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