<template>
  <div class="ttyf-wrapper">
    <!--信息编辑-->
    <van-form ref="myVanform">
      <!--标题：妥妥计算器-->
      <img class="title" src="./image/icon_title@2x.png" alt="" v-show="false">
      <!--计算结果展示-->
      <div class="calculator-wrap">
        <div class="left">
          <p class="label">参考月供(元)</p>
          <p class="value">{{ meiyuehuanchuan }}</p>
          <div class="wrap">
            <span class="label">还款总额(元)</span>
            <span class="value">{{ totalPrice ? totalPrice + '万' : '' }}</span>
          </div>
        </div>
        <div class="right">
          <p class="label">{{ hkfangshiIndex === 1 ? '每月递减(元)' : '' }}</p>
          <p class="value">{{ hkfangshiIndex === 1 ? yuegongdijian : '' }}</p>
          <div class="wrap">
            <span class="label">支付利息(元)</span>
            <span class="value">{{ zonglixi ? zonglixi + '万' : '' }}</span>
          </div>
        </div>
      </div>
      <van-field
        readonly
        clickable
        name="loanType"
        :value="loanType.text"
        :border="false"
        :right-icon="iconOfarrow"
        placeholder="请选择贷款类型"
        class="ttyf-van-cell"
        @click="showPicker0 = true">
        <template #label>
          <p>
              <span v-for="(str, index) in '贷款类型'"
                    :key="index">{{ str }}</span>
          </p>
        </template>
      </van-field>
      <!--商业贷款：金额-->
      <template>
        <van-field :class="loanType.value === 1 || loanType.value === 3 ? '' : 'hide'"
                   v-model="sdjine"
                   type="tel"
                   name="sdjine"
                   :border="false"
                   placeholder="请输入您的商贷金额"
                   class="ttyf-van-cell ttyf-no-arrow"
                   @input="sdjine = sdjine.replace(/^\D*(\d*(?:\.\d{0,5})?).*$/g, '$1').replace(/^0\d*/, '0').replace(/^\./, '0.')">
          <template #label>
            <p>
            <span v-for="(str, index) in '商贷金额(万)'"
                  :key="index">{{ str }}</span>
            </p>
          </template>
        </van-field>
      </template>
      <!--公积金：金额-->
      <template>
        <van-field :class="loanType.value === 2 || loanType.value === 3 ? '' : 'hide'"
                   v-model="gjjjine"
                   type="tel"
                   name="gjjjine"
                   :border="false"
                   placeholder="请输入金额"
                   class="ttyf-van-cell ttyf-no-arrow"
                   @input="gjjjine=gjjjine.replace(/^\D*(\d*(?:\.\d{0,5})?).*$/g, '$1').replace(/^0\d*/, '0').replace(/^\./, '0.')">
          <template #label>
            <p>
            <span v-for="(str, index) in '公积金贷款金额(万)'"
                  :key="index">{{ str }}</span>
            </p>
          </template>
        </van-field>
      </template>
      <!--公积金/商贷：年限-->
      <van-field readonly
                 clickable
                 name="gjjnianxian"
                 :value="gjjnianxian.text"
                 :border="false"
                 :right-icon="iconOfarrow"
                 placeholder="请选择贷款年限"
                 class="ttyf-van-cell"
                 @click="showPicker1 = true">
        <template #label>
          <p>
              <span v-for="(str, index) in '贷款年限(年)'"
                    :key="index">{{ str }}</span>
          </p>
        </template>
      </van-field>
      <!--商业贷款：利率-->
      <template>
        <van-field :class="loanType.value === 1 || loanType.value === 3 ? '' : 'hide'"
                   name="sdlilv"
                   v-model="sdlilv"
                   :border="false"
                   placeholder="请输入利率"
                   class="ttyf-van-cell ttyf-no-arrow"
                   @input="sdlilv=sdlilv.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1').replace(/^0\d*/, '0').replace(/^\./, '0.')">
          <template #label>
            <p>
              <span v-for="(str, index) in '商贷利率(%)'"
                    :key="index">{{ str }}</span>
            </p>
          </template>
        </van-field>
      </template>
      <!--公积金：利率-->
      <template>
        <van-field :class="loanType.value === 2 || loanType.value === 3 ? '' : 'hide'"
                   name="gjjlilv"
                   v-model="gjjlilv"
                   :border="false"
                   placeholder="请输入利率"
                   class="ttyf-van-cell ttyf-no-arrow"
                   @input="gjjlilv=gjjlilv.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1').replace(/^0\d*/, '0').replace(/^\./, '0.')">
          <template #label>
            <p>
              <span v-for="(str, index) in '公积金贷款利率(%)'"
                    :key="index">{{ str }}</span>
            </p>
          </template>
        </van-field>
      </template>
      <van-field readonly
                 clickable
                 name="hkfangshi"
                 :value="hkfangshi.text"
                 :border="false"
                 :right-icon="iconOfarrow"
                 placeholder="请选择还款方式"
                 class="ttyf-van-cell"
                 @click="showPicker5 = true">
        <template #label>
          <p>
              <span v-for="(str, index) in '还款方式'"
                    :key="index">{{ str }}</span>
          </p>
        </template>
      </van-field>
      <van-button class="ttyf-get-result"
                  type="info"
                  @click="handleComputed">开始计算
      </van-button>
      <div class="footer"
           @click="$router.push({name: 'loanRecommend'})"
           v-if="recommendedProduct.length">
        <p>
          <span>妥妥可帮您节省利息</span>
          <span>{{ recommendedProduct[0].saveMoney }}</span>
          <span>元</span>
        </p>
        <a href="javascript:;">点击查看详情></a>
      </div>
    </van-form>
    <!--贷款类型选择-->
    <van-popup v-model="showPicker0"
               :close-on-click-overlay="false"
               @click-overlay="onCancel0"
               position="bottom">
      <van-picker
        show-toolbar
        :columns="columns0"
        :default-index="defaultIndex0"
        @confirm="onConfirm0"
        @cancel="onCancel0"
        ref="myPicker0"
      />
    </van-popup>
    <!--公积金年限选择-->
    <van-popup v-model="showPicker1"
               :close-on-click-overlay="false"
               @click-overlay="onCancel1"
               position="bottom">
      <van-picker
        show-toolbar
        :columns="columns1"
        :default-index="defaultIndex1"
        @confirm="onConfirm1"
        @cancel="onCancel1"
        ref="myPicker1"
      />
    </van-popup>
    <!--贷款类型选择-->
    <van-popup v-model="showPicker5"
               :close-on-click-overlay="false"
               @click-overlay="onCancel5"
               position="bottom">
      <van-picker show-toolbar
                  :columns="columns5"
                  :default-index="defaultIndex5"
                  @confirm="onConfirm5"
                  @cancel="onCancel5"
                  ref="myPicker5"
      />
    </van-popup>
  </div>
</template>

<script>
import { Form, Field, Popup, Picker, Button, Toast } from 'vant'
import { loanConfig } from './config'
import { calcute } from './config/calculate'
import { getRecommendProduct } from './api'

export default {
  name: 'index',
  components: {
    'van-form': Form,
    'van-field': Field,
    'van-popup': Popup,
    'van-picker': Picker,
    'van-button': Button
  },
  props: {
    role: {
      type: [Number, String],
      default: 0
    }
  },
  data () {
    return {
      loanTypeIndx: 0,
      gjjjine: '', // 公积金贷款金额
      gjjlilv: '', // 公积金贷款利率
      gjjnianxianIndex: 19,
      sdjine: '', // 商贷金额
      sdlilv: '', // 商贷利率
      hkfangshiIndex: 0,
      meiyuehuanchuan: '0.00', // 每月还款
      zonglixi: '0.00', // 总共支付利息
      totalPrice: '0.00', // 还款总额
      yuegongdijian: '0.00', // 月供递减
      showPicker0: false,
      columns0: loanConfig.loanType,
      defaultIndex0: 0,
      showPicker1: false,
      columns1: loanConfig.loanYear,
      defaultIndex1: 19,
      showPicker5: false,
      columns5: loanConfig.payType,
      defaultIndex5: 0
    }
  },
  computed: {
    iconOfarrow () {
      return require('./image/btn_next@2x.png')
    },
    recommendedProduct: {
      get () {
        return this.$store.state.loan.recommendedProduct
      },
      set (val) {
        this.$store.commit('loan/UPDATE_RECOMMENDEDPRODUCT', val)
      }
    },
    // 贷款类型
    loanType: {
      get () {
        return loanConfig.loanType[this.loanTypeIndx]
      }
    },
    // 公积金贷款年限
    gjjnianxian: {
      get () {
        return loanConfig.loanYear[this.gjjnianxianIndex]
      }
    },
    // 还款方式
    hkfangshi: {
      get () {
        return loanConfig.payType[this.hkfangshiIndex]
      }
    }
  },
  activated () {
    if (!this.$route.meta.isUseCache) {
      this.loanTypeIndx = 0
      this.gjjjine = ''
      this.gjjlilv = ''
      this.gjjnianxianIndex = 19
      this.sdjine = ''
      this.sdlilv = ''
      this.hkfangshiIndex = 0
      this.meiyuehuanchuan = '0.00'
      this.zonglixi = '0.00'
      this.totalPrice = '0.00'
      this.yuegongdijian = '0.00'
      this.showPicker0 = false
      this.columns0 = loanConfig.loanType
      this.defaultIndex0 = 0
      this.showPicker1 = false
      this.columns1 = loanConfig.loanYear
      this.defaultIndex1 = 19
      this.showPicker5 = false
      this.columns5 = loanConfig.payType
      this.defaultIndex5 = 0
    }
    this.$refreshTitle('房贷计算器')
    this.$route.meta.isUseCache = false
  },
  watch: {
    loanTypeIndx: {
      handler: function () {
        this.handleComputed()
      }
    },
    gjjjine: {
      handler: function () {
        this.handleComputed()
      }
    },
    gjjlilv: {
      handler: function () {
        this.handleComputed()
      }
    },
    gjjnianxianIndex: {
      handler: function () {
        this.handleComputed()
      }
    },
    sdjine: {
      handler: function () {
        this.handleComputed()
      }
    },
    sdlilv: {
      handler: function () {
        this.handleComputed()
      }
    },
    hkfangshiIndex: {
      handler: function () {
        this.handleComputed()
      }
    }
  },
  methods: {
    // 贷款类型
    onConfirm0 (value, index) {
      this.loanTypeIndx = index
      this.showPicker0 = false
    },
    onCancel0 () {
      this.$refs.myPicker0.setIndexes([this.loanTypeIndx])
      this.showPicker0 = false
    },
    // 公积金贷款年限
    onConfirm1 (value, index) {
      this.gjjnianxianIndex = index
      this.showPicker1 = false
    },
    onCancel1 () {
      this.$refs.myPicker1.setIndexes([this.gjjnianxianIndex])
      this.showPicker1 = false
    },
    // 还款方式
    onConfirm5 (value, index) {
      this.hkfangshiIndex = index
      this.showPicker5 = false
    },
    onCancel5 () {
      this.$refs.myPicker5.setIndexes([this.hkfangshiIndex])
      this.showPicker5 = false
    },
    // 将数值四舍五入(保留2位小数)后格式化成金额形式
    formatCurrency (val) {
      let num = val.toString().replace(/\$|\,/g, '')
      if (isNaN(num)) {
        num = '0'
      }
      num = Math.floor(num * 100 + 0.50000000001)
      let cents = num % 100
      num = Math.floor(num / 100).toString()
      if (cents < 10) {
        cents = '0' + cents
      }
      for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
        num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3))
      }
      return num + '.' + cents
    },
    async handleComputed () {
      await this.$nextTick()
      const sdlilv = this.sdlilv / 100
      const gjjlilv = this.gjjlilv / 100
      let result = {}
      let yuegong = '0.00'
      let totalLixi = '0.00'
      let totalPrice = '0.00'
      let yuegongdijian = '0.00'
      // 还款方式
      const payType = this.hkfangshi.value
      switch (this.loanType.value) {
        case 1:
          if (this.sdjine) {
            result = calcute.singleDk(payType, this.sdjine, this.gjjnianxian.value, sdlilv)
          }
          break
        case 2:
          if (this.gjjjine) {
            result = calcute.singleDk(payType, this.gjjjine, this.gjjnianxian.value, gjjlilv)
          }
          break
        case 3:
          if (this.sdjine && this.gjjjine) {
            result = calcute.zuhe(payType, this.sdjine, this.gjjjine, this.gjjnianxian.value, this.gjjnianxian.value, sdlilv, gjjlilv)
          }
          break
      }
      this.recommendedProduct = []
      if (result.yuegong) {
        yuegong = this.formatCurrency(result.yuegong)
      }

      if (result.totalPrice) {
        totalPrice = this.formatCurrency(result.totalPrice / 10000)
      }

      if (result.totalLixi) {
        totalLixi = this.formatCurrency(result.totalLixi / 10000)
        this.fetchRecommendProduct(result.totalLixi)
      }

      if (result.yuegongdijian) {
        yuegongdijian = result.yuegongdijian.toFixed(2)
      }

      this.meiyuehuanchuan = yuegong
      this.zonglixi = totalLixi
      this.totalPrice = totalPrice
      this.yuegongdijian = yuegongdijian
    },
    fetchRecommendProduct (moneyRate) {
      const productMmaxYear = this.gjjnianxian.value
      let totalMoney = 0
      if (this.loanType.value === 1) {
        totalMoney = parseFloat(this.sdjine) * 10000
      } else if (this.loanType.value === 2) {
        totalMoney = parseFloat(this.gjjjine) * 10000
      } else if (this.loanType.value === 3) {
        totalMoney = parseFloat(this.gjjjine) * 10000 + parseFloat(this.sdjine) * 10000
      }
      const postData = {
        total_money: totalMoney, // 总贷款金额(单位：元)
        product_max_year: productMmaxYear, // 贷款年限
        product_back_method: this.hkfangshi.text, // 还款方式(先息后本、等额本息、等额本金)
        money_rate: moneyRate // 计算器计算的利息
      }
      getRecommendProduct(postData).then(res => {
        if (res.status) {
          if (Object.prototype.toString.call(res.data) === '[object Array]') {
            // 查找最大优惠值
            this.recommendedProduct = JSON.parse(JSON.stringify(res.data)).sort((a, b) => {
              return b.saveMoney - a.saveMoney
            })
          }
          return
        }
        Toast(res.msg)
      }).catch(err => {
        Toast(err.msg)
      })
    }
  },
  beforeDestroy () {
    this.Compressor = null
  },
  beforeRouteLeave (to, from, next) {
    if (['loanIndex', 'loanMine', 'loanRecommend'].findIndex(item => item === to.name) > -1) {
      this.$route.meta.isUseCache = true
    }
    next()
  }
}
</script>

<style lang="scss" scoped>
.ttyf-wrapper {
  padding-top: 12px;
}

form {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 356px;
  border-radius: 16px;
  padding: 0 0 11px;
  margin: 0 auto;
  background: #fff;

  img.title {
    width: 349px;
    height: 56px;
  }
}

.calculator-wrap {
  display: flex;
  align-items: center;
  width: 100%;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
  padding: 10px 0 20px;
  margin-bottom: 16px;
  background: linear-gradient(90deg, #E5C7A5 0%, #CFAA7F 100%);

  .left,
  .right {
    width: 50%;
    padding-left: 20px;
  }

  p.label,
  span.label {
    height: 17px;
    font-size: 12px;
    line-height: 17px;
  }

  p.value,
  span.value {
    height: 22px;
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #333333;
    line-height: 22px;
  }

  span.value {
    margin-left: 4px;
  }

  .wrap {
    display: flex;
    align-items: center;
    margin-top: 10px;
  }
}

.ttyf-van-cell {
  width: 327px;
  padding: 13px 0;
  margin-bottom: 1px;
  border-radius: 4px;
  border: 1px solid #E8E8E8;

  &.ttyf-no-arrow {
    ::v-deep .van-cell__value {
      padding: 0 32px 0 0;
    }
  }

  &.hide {
    display: none;
  }

  ::v-deep .van-field__label {
    position: relative;
    left: 0;
    top: 0;
    flex: 1;
    padding: 0 0 0 12px;
    margin-right: 0;

    p {
      display: flex;
      align-items: center;
      white-space: nowrap;
    }

    span {
      font-size: 16px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #333333;
      line-height: 22px;
    }
  }

  ::v-deep .van-cell__value {
    padding: 0 10px 0 0;

    input {
      height: 22px;
      font-size: 14px;
      color: #333;
      -webkit-text-fill-color: #333;
      opacity: 1;
      background: transparent;
      text-align: right;

      &::-webkit-input-placeholder {
        -webkit-text-fill-color: #ccc;
        opacity: 1;
        color: #ccc;
      }
    }

    .van-field__right-icon {
      margin: 0;
      padding: 0;

      .van-icon {
        font-size: 0;
      }

      .van-icon__image {
        display: block;
        width: 22px;
        height: 22px;
      }
    }
  }
}

.footer {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: center;
  width: 327px;
  height: 65px;
  background: #FEF0E7;
  border-radius: 4px;
  padding-right: 15px;
  text-align: right;

  p {
    display: flex;
    align-items: center;

    span:nth-of-type(1),
    span:nth-of-type(3) {
      font-size: 12px;
      color: #FA5151;
      line-height: 17px;
    }

    span:nth-of-type(2) {
      font-size: 18px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #FF655E;
      line-height: 25px;
    }
  }

  a {
    font-size: 12px;
    color: #FA5151;
    line-height: 17px;
  }
}

.ttyf-get-result {
  width: 327px;
  height: 45px;
  border: none;
  margin: 20px 0;
  background: linear-gradient(90deg, #E5C7A5 0%, #CFAA7F 100%);
  box-shadow: 0 14px 9px -10px rgba(219, 208, 194, 1);
  border-radius: 4px;

  .van-button__text {
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #FFFFFF;
  }
}

.ttyf-tip {
  width: 327px;
  margin-bottom: 10px;
  font-size: 16px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #333333;
  line-height: 22px;
}
</style>
