<template>
  <div class="content">
    <div style="width: 100%">
      <van-form label-width="25%" @submit="onSubmit">
        <mobile-input border="true" :formatter="formatter" required format-trigger="reset" v-model="loanMoney"
                      label="逾期金额(元):" type="number"
                      vtype="decimals"
                      :required="true"
                      placeholder="请输入逾期金额" />
        <mobile-input border="true" :formatter="formatter" required format-trigger="reset" v-model="allMonths"
                      type="digit"
                      :required="true"
                      placeholder="请输入逾期时间"
                      :rules="[{ validator: validatorIntRules, message: msg }]" label="贷款期限(月):" />
        <mobile-input border="true" :formatter="formatter" required format-trigger="reset" v-model="lprRate"
                      label="逾期利率(%):" @input="onMothRate"
                      :required="true"
                      :rules="[{ validator: validatorRules, message: LprMsg }]" />
        <div style="margin: 16px; display: flex; justify-content: space-around">
          <van-button @click="reset" style="width: 40%" round color="#999999" native-type="button" plain>重置</van-button>
          <van-button style="width: 40%" round type="info" native-type="submit">提交</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { Calendar } from "vant";
import { Picker } from "vant";
import { Button } from "vant";

Vue.use(Button);

Vue.use(Picker);

Vue.use(Calendar);
/**
 * @Description 贷款测算
 * @Author JiangTao
 * @Date 2021-10-25 下午 08:53
 */
@Component({
  name: "LoanCalculation"
})
export default class LoanCalculation extends Vue {

  listShow = false; //计算结果显示
  floatRate = ""; //浮动利率
  lprRate: any = ""; //LPR利率
  loanMoney: any = ""; //总贷款金额
  allMonths: any = ""; //贷款月日期
  monthRate: any = ""; //月利率
  monthRateFormat: any = ""; //月利率显示格式
  refundType = ""; //还款方式
  title = "贷款试算";
  showPicker = false;
  list: any[] = [];
  keyBase = [];
  keyBase1 = [
    "贷款金额（万元）:",
    "每月还款本金（元）:",
    "首月还款额（元）:",
    "每月递减（元）:",
    "累计还贷款本息额（元）:",
    "累计还贷款利息额（元）:"
  ];
  LprMsg = "年利率为正整数或小数";
  keyBase2 = ["贷款金额（万元）:", "每月还款额（元）:", "累计还贷款本息额（元）:", "累计还贷款利息额（元）:"];
  keyBase3 = ["贷款金额（万元）:", "累计还贷款本息额（元）:", "累计还贷款利息额（元）:", "每月利息约为（元）:"];
  msg = "";

  reset() {
  }

  formatter() {
  }

  //toFixed四舍五入精度丢失重写
  toFixed(num: any, s: any) {
    var times = Math.pow(10, s);
    var des: any = num * times + 0.5;
    des = parseInt(des, 10) / times;
    return des + "";
  }

  //输入内容为整数进行校验
  validatorIntRules(val: any) {
    if (val > 360 || val < 1) {
      this.msg = "期数必须大于0小于360";
      return false;
    } else {
      this.msg = "期数必须为整数";
      return /^[0-9]*$/.test(val);
    }
  }

  //输入内容进行校验
  validatorRules(val: any) {
    let reg = new RegExp("^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$");
    if (!reg.test(val)) {
      this.LprMsg = "年利率为正整数或小数";
      return false;
    } else if (val > 100) {
      this.LprMsg = "年利率不能大于100";
      return false;
    }
    return true;
  }

  //给monthRate动态绑定输入值
  onMothRate() {
    let lprRate = this.lprRate == "" ? 0 : parseFloat(this.lprRate);
    let floatRate = this.floatRate == "" ? 0 : parseFloat(this.floatRate);
    this.monthRate = lprRate / 12; //月利率用于计算
    // this.monthRate = parseFloat(this.monthRate).toFixed(2);
    this.monthRateFormat = this.monthRate * 100 || 0; //月利率用于展示
    this.monthRateFormat = this.toFixed(this.monthRateFormat, 3);
  }

  /**
   * 清除页面信息
   */
  onClearInfo() {
    this.listShow = false;
    this.loanMoney = ""; //总贷款金额
    this.allMonths = ""; //贷款月日期
    this.monthRate = ""; //月利率
    this.monthRateFormat = ""; //月利率显示格式
    this.refundType = ""; //还款方式
    this.floatRate = ""; //浮动利率
    this.lprRate = ""; //LPR利率(年利率)
  }

  onSubmit(values: any) {
    if (this.refundType == "等额本金") {
      //参数
      let loanMoney: any = parseFloat(this.loanMoney); //总贷款金额
      let allMonths: any = parseFloat(this.allMonths); //贷款月日期
      let monthRate: any = parseFloat(this.monthRate) / 100; //月利率，输入为百分比转换为小数;
      console.log(monthRate, "===============");
      let monthLoanMoney: any = (loanMoney / allMonths).toFixed(3);
      let curMonthInterest: any = 0; //本月应还利息
      let repayLoanMoney: any = 0; //已还本金总额
      let repayInterestMoney: any = 0; //已还利息
      let everyMonthMoney: any = 0; //每月还本息
      monthLoanMoney = parseFloat(monthLoanMoney).toFixed(2); //每月应还本金
      this.list = []; //结果集置空
      for (let i = 0; i < allMonths; i++) {
        let monthPayMap: any = {}; //存储每一个月的还款内容
        if (i < allMonths - 1) {
          //不是最后一个月的话
          repayLoanMoney = parseFloat(repayLoanMoney) + parseFloat(monthLoanMoney);
          repayLoanMoney = repayLoanMoney.toFixed(2);
          monthPayMap.monthLoanMoney = monthLoanMoney; //每月应还本金
          // console.log(loanMoney,'===',monthLoanMoney,'====',monthRate);
          curMonthInterest = (parseFloat(loanMoney) - i * parseFloat(monthLoanMoney)) * parseFloat(monthRate);
          curMonthInterest = curMonthInterest.toFixed(2);
          repayInterestMoney = parseFloat(repayInterestMoney) + parseFloat(curMonthInterest);
          repayInterestMoney = this.toFixed(repayInterestMoney, 2);
          everyMonthMoney = parseFloat(monthLoanMoney) + parseFloat(curMonthInterest);
          everyMonthMoney = everyMonthMoney.toFixed(2);
        } else {
          //最后一个月，消除误差
          monthLoanMoney = (parseFloat(loanMoney) - parseFloat(repayLoanMoney)).toFixed(2);
          repayLoanMoney = parseFloat(repayLoanMoney) + parseFloat(monthLoanMoney);
          repayLoanMoney = repayLoanMoney.toFixed(2);
          monthPayMap.monthLoanMoney = monthLoanMoney;
          curMonthInterest = (loanMoney - i * monthLoanMoney) * monthRate;
          curMonthInterest = curMonthInterest.toFixed(2);
          repayInterestMoney = parseFloat(repayInterestMoney) + parseFloat(curMonthInterest);
          repayInterestMoney = this.toFixed(repayInterestMoney, 2);
          everyMonthMoney = parseFloat(monthLoanMoney) + parseFloat(curMonthInterest);
          everyMonthMoney = everyMonthMoney.toFixed(2);
        }
        monthPayMap.curMonthInterest = curMonthInterest;
        monthPayMap.everyMonthMoney = everyMonthMoney; //每月应还本息
        monthPayMap.repayInterestMoney = repayInterestMoney; //已还利息
        monthPayMap.repayLoanMoney = repayLoanMoney;
        this.list.push(monthPayMap);
      }
      this.$store.commit("setEmpty");
      this.$store.commit("setCalculateRes", this.list);
      this.$router.push({ path: "/LoanCalculationDetail"});
    } else if (this.refundType == "等额本息") {
      let loanMoney: any = parseFloat(this.loanMoney); //总贷款金额
      let allMonths: any = parseFloat(this.allMonths); //贷款月日期
      let monthRate: any = parseFloat(this.monthRate) / 100; //月利率，输入为百分比转换为小数;

      let perMonthMoney: any =
        (loanMoney * monthRate * Math.pow(1 + monthRate, allMonths)) / (Math.pow(1 + monthRate, allMonths) - 1); //每月还款金额

      let allMoney: any = parseFloat(perMonthMoney) * parseFloat(allMonths); //总还款金额
      let onlyRate: any = parseFloat(allMoney) - parseFloat(loanMoney); //剩余本金
      let curMonthInterest: any = 0; //本月应还利息
      let repayLoanMoney: any = 0; //已还本金总额
      let repayInterestMoney: any = 0; //已还利息
      let everyMonthMoney: any = 0; //每月还本息
      let monthLoanMoney: any = 0; //本月还本金
      let totalRepay: any = 0; //已还本息
      perMonthMoney = this.toFixed(perMonthMoney, 2);
      allMoney = this.toFixed(allMoney, 2);
      onlyRate = this.toFixed(onlyRate, 2);
      this.list = [];
      this.keyBase = [];
      for (let i = 0; i < allMonths; i++) {
        let monthPayMap: any = {};
        if (i < allMonths - 1) {
          curMonthInterest = (parseFloat(loanMoney) - parseFloat(repayLoanMoney)) * parseFloat(monthRate); //每月还利息
          monthLoanMoney = parseFloat(perMonthMoney) - parseFloat(curMonthInterest); //每月本金
          repayInterestMoney = parseFloat(repayInterestMoney) + parseFloat(curMonthInterest); //已还利息
          repayLoanMoney = parseFloat(repayLoanMoney) + parseFloat(monthLoanMoney); //已还本金
          totalRepay = parseFloat(totalRepay) + parseFloat(perMonthMoney); //已还本息
        } else {
          everyMonthMoney = parseFloat(allMoney) - parseFloat(totalRepay); //剩余本息
          monthLoanMoney = parseFloat(loanMoney) - parseFloat(repayLoanMoney);
          repayLoanMoney = parseFloat(repayLoanMoney) + parseFloat(monthLoanMoney); //已还本金
          curMonthInterest = parseFloat(everyMonthMoney) - parseFloat(monthLoanMoney);
        }
        monthPayMap.everyMonthMoney = this.toFixed(perMonthMoney, 2);
        monthPayMap.curMonthInterest = this.toFixed(curMonthInterest, 2);
        monthPayMap.repayInterestMoney = this.toFixed(repayInterestMoney, 2); //已还利息
        monthPayMap.repayLoanMoney = this.toFixed(repayLoanMoney, 2);
        monthPayMap.monthLoanMoney = this.toFixed(monthLoanMoney, 2);
        this.list.push(monthPayMap);
      }
      this.$store.commit("setEmpty");
      this.$store.commit("setCalculateRes", this.list);
      this.$router.push({ path: "/LoanCalculationDetail"});
    } else if (this.refundType == "按月付息") {
      let loanMoney: any = parseFloat(this.loanMoney); //总贷款金额
      let allMonths: any = parseFloat(this.allMonths); //贷款月日期
      let monthRate: any = parseFloat(this.monthRate) / 100; //月利率，输入为百分比转换为小数;
      let curMonthInterest: any = 0; //本月应还利息
      let repayLoanMoney: any = 0; //已还本金总额
      let repayInterestMoney: any = 0; //已还利息
      let everyMonthMoney: any = 0; //每月还本息
      let monthLoanMoney: any = 0; //本月还本金
      let totalRepay: any = 0; //已还本息

      let onlyRate: any = loanMoney * allMonths * monthRate; //总利息
      let allMoney: any = loanMoney + onlyRate; //总还款金额
      let perOnlyRate: any = onlyRate / allMonths;
      this.list = [];
      allMoney = this.toFixed(allMoney, 2);
      onlyRate = this.toFixed(onlyRate, 2);
      perOnlyRate = this.toFixed(perOnlyRate, 2);
      curMonthInterest = parseFloat(loanMoney) * parseFloat(monthRate);
      for (let i = 0; i < allMonths; i++) {
        let monthPayMap: any = {};
        repayInterestMoney = parseFloat(repayInterestMoney) + parseFloat(curMonthInterest);
        if (i != allMonths - 1) {
          everyMonthMoney = curMonthInterest;
        } else if (i == allMonths - 1) {
          everyMonthMoney = parseFloat(curMonthInterest) + parseFloat(loanMoney);
          monthLoanMoney = loanMoney;
          repayLoanMoney = loanMoney;
        }
        monthPayMap.everyMonthMoney = this.toFixed(everyMonthMoney, 2);
        monthPayMap.curMonthInterest = this.toFixed(curMonthInterest, 2);
        monthPayMap.repayInterestMoney = this.toFixed(repayInterestMoney, 2); //已还利息
        monthPayMap.repayLoanMoney = this.toFixed(repayLoanMoney, 2);
        monthPayMap.monthLoanMoney = this.toFixed(monthLoanMoney, 2);
        this.list.push(monthPayMap);
      }
      this.$store.commit("setEmpty");
      this.$store.commit("setCalculateRes", this.list);
      this.$router.push({ path: "/LoanCalculationDetail"});
    } else {
      this.list = [];
    }
    //跳转到还款页面
  }

  onConfirm(value: any) {
    this.refundType = value;
    this.showPicker = false;
  }

  /**
   * @desc: keepAlive 处理代码逻辑，根据路由判断进入页面销毁缓存数据
   * @author: zmk
   * @date: 2022年01月25日23:07:36
   * */
  activated() {
    this.$router.beforeEach((to, from, next) => {
      if (from.path == "/main/workbench") {
        this.listShow = false;
        this.loanMoney = ""; //总贷款金额
        this.allMonths = ""; //贷款月日期
        this.monthRate = ""; //月利率
        this.monthRateFormat = ""; //月利率显示格式
        this.refundType = ""; //还款方式
        this.floatRate = ""; //浮动利率
        this.lprRate = ""; //LPR利率(年利率)
      }
      next();
    });
  }

// watch: {
//   lprRate() {
//     if (this.lprRate > 100) {
//       this.LprMsg = '年利率不能大于100';
//     } else {
//       this.LprMsg = '年利率为正整数或小数';
//     }
//   }
// }
}
</script>

<style scoped>
.content {
  width: 60%;
  padding-top: 10%;
  margin: 0 auto;
}

::v-deep .d-field-label {
  width: 110px !important;
  text-align: right;
}

::v-deep .van-button--info {
  background-color: #fd5065;
  border: 1px solid #fd5065;
}

::v-deep .van-button__text {
  font-size: 16px;
}

::v-deep .van-cell::after {
  border: 0;
}
</style>
