<!--
 * @Author: ysh
 * @Date: 2025-02-20 10:20:22
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-03-03 11:02:06
-->
<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"></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="申请金额" class="form-item">
        <view>{{ (this.form.applyAmount).toFixed(2) }}</view>
        <view style="color:#E74C3C" v-if="exceed && form.borrowUsage == '0'">
          超过预算金额：{{ getMoreAmount('0') }}</view>
      </uni-forms-item>

      <uni-forms-item label="最大借款金额" class="form-item">
        {{ totalBudget.toFixed(2) }}
      </uni-forms-item>
      <uni-forms-item label="已申请借款" class="form-item">
        {{ hasBorrow.toFixed(2) }}
      </uni-forms-item>
      <uni-forms-item label="可用借款" class="form-item">
        {{ (totalBudget - hasBorrow).toFixed(2) }}
      </uni-forms-item>
      <view>
        <u-button type="primary" size="normal" @click="submit">提交申请</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 BorrowDetail from './borrowDetail.vue';
export default {
  components: {
    ProjectPicker,
    ProjectInfo,
    BorrowDetail
  },
  props: {
    taskForm: Object,
    taskName: String, // 当前节点
    startUserName: String, // 流程发起人
  },
  created() {
    this.initForm();
    uni.setNavigationBarTitle({
      title: '借款审批'
    });
  },
  data() {
    return {
      form: {
        submitTime: '',
        borrowUsage: '0',
        applyAmount: 0,
      },
      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: {}, //项目信息的项目
      fromTotal: 0,
      totalBudget: 0, //预结算额
      exceed: false, //是否超预算
      hasBorrow: 0, //已申请借款
    }
  },
  methods: {
    async initForm() {
      getBorrow(this.taskForm.formId).then(async res => {
        if (res.data) {
          this.fromTotal = 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.fromTotal = 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) {
      console.log(val);
      console.log(this.from);
      this.form.applyAmount = val
    },
    handleConfirm(project) {
      console.log('选中的项目:', project);
      this.selectedProject = project;
      this.projectObj = project;
    },
    submit() {
      this.$refs.form.validate().then(res => {
        console.log('表单数据信息：', res);
      }).catch(err => {
        console.log('表单错误信息：', err);
      })
    }
  },
}
</script>

<style lang="scss" scoped></style>