<template>
  <div class="con-box balance">
    <div class="uc-nav">
      <div class="nav-box">
        <div
          :class="['nav-item', sts == 0 ? 'active' : '']"
          @click="changeTab(0)"
        >
          <span class="text">{{$t('myBalance.myBalance')}}</span>
          <i class="line"></i>
        </div>
        <div
          :class="['nav-item', sts == 1 ? 'active' : '']"
          @click="changeTab(1)"
        >
          <span class="text">{{$t('myBalance.balanceTopUp')}}</span>
          <i class="line"></i>
        </div>
      </div>
    </div>
    <!-- 我的余额 -->
    <div class="balance-detail" v-if="sts == 0">
      <!-- 当前可用余额 -->
      <div class="uc-serach">
        <div class="left">
          <div class="current-balance">
            {{$t('myBalance.currentAvailableBalance')}}：
            <span class="number">{{currentBalance}}{{$t('myBalance.yuan')}}</span>
          </div>

          <div class="right">
              <a class="search" @click="balanceTopUp"
              >{{$t('myBalance.balanceTopUp')}}</a>
          </div>
        </div>
      </div>
      <!-- 当前可用余额 -->

      <table
        cellspacing="0"
        cellpadding="0"
        class="box"
      >
        <tbody>
          <tr class="box-tit">
            <th>{{$t('myBalance.sourceUse')}}</th>
            <th width="400">{{$t('myBalance.balanceChange')}}</th>
            <th>{{$t('myBalance.Time')}}</th>
          </tr>
          <tr v-if="scoreDetList.length" align="left" class="box-hd" v-for="(item, index) in scoreDetList" :key="index">
            <td>
              <div class="text" >
                <!-- {{$t('myBalance.shopping')}}（{{$t('myBalance.orderNumber')}}：{{ item.bizId }}） -->
                <!-- 1:充值 2:赠送 3:支付 4:退款 5平台手动修改 6.充值会员 -->
                <div class="text">
                  <span v-if="item.type == 1">
                    {{$t('myBalance.balanceTopUp')}}
                  </span>
                  <span v-if="item.type == 2">
                    {{$t('myBalance.giftAmount')}}
                  </span>
                  <span v-if="item.type == 3">
                    {{$t('myBalance.shopping')}}
                  </span>
                  <span v-if="item.type == 4">
                    {{$t('myBalance.orderRefunds')}}
                  </span>
                  <span v-if="item.type == 5">
                    {{$t('myBalance.platformManualModification')}}
                  </span>
                  <span v-if="item.type == 6">
                    {{$t('myBalance.topUpMembers')}}
                  </span>
                  <span v-if="item.orderNumberList.length > 0" class="order-number">
                    {{$t('myBalance.orderNumber')}}:
                    <div class="order-number-con">
                      <span class="order-number-item" v-for="(orderNumberItem, orderNumberIndex) in item.orderNumberList" :key="orderNumberIndex">{{ orderNumberItem }}</span>
                    </div>
                  </span>
                </div>
              </div>
            </td>
            <td>
              <div class="balance-change" v-if="item.ioType == 0">
                -{{ item.changeBalance }}
              </div>
              <div class="balance-change add" v-if="item.ioType == 1">
                +{{ item.changeBalance }}
              </div>
            </td>
            <td>
              <div class="time">{{ item.createTime }}</div>
            </td>
          </tr>
          <tr v-if="!scoreDetList.length">
            <td colspan="3">{{$t('shopInfo.noData')}}</td>
          </tr>
        </tbody>
      </table>
      <!-- 页码 -->
      <pagination
        v-model="scoreCurrent"
        :pages="scorePages"
        @changePage="getScoreDet"
      ></pagination>
      <!-- /页码 -->
    </div>
    <!-- /我的余额 -->

    <!-- 余额充值 -->
    <div class="goods-list balance-exchange" v-if="sts == 1">
      <div class="topup">
        <div>
          <div class="topup-con">
            <div class="pay-box">
              <div class="pay-info">
                <div class="item">
                  <div class="tit">{{ title }}</div>
                </div>
                <div v-if="tip" class="itemTip">
                  {{ tip }}
                </div>
              </div>
            </div>
            <div class="section-topup">
              <div v-if="topUpList.length" class="items sku-text">
                <span class="tit">{{$t('myBalance.topUpAmount')}}</span>
                <div class="con">
                  <span
                    v-for="(item, index) in topUpList"
                    :key="index"
                    class="item"
                    :class="[rechargeId === item.balanceId ? 'active' : '']"
                    @click="selectAmount(item)"
                  >{{ item.rechargeAmount }}{{$t('myBalance.yuan')}}</span>
                </div>
              </div>

              <div class="items sku-text">
                <span class="tit">{{$t('myBalance.customAmounts')}}({{$t('myBalance.yuan')}})</span>
                <div class="con">
                  <input
                    type="text"
                    class="text"
                    v-model="customAmounts"
                    @input="changeNum"
                    :placeholder="$t('myBalance.upToTopUp')"
                  />
                  <span class="unit">{{$t('myBalance.yuan')}}</span>
                </div>
              </div>
              <div class="items sku-text">
                <span class="tit">{{$t('myBalance.currentBalance')}}({{$t('myBalance.yuan')}})</span>
                <div class="con">
                  <span class="number">{{currentBalance}}</span>
                </div>
              </div>

              <div class="items sku-text">
                <span class="tit">{{$t('myBalance.selectPaymentMethod')}}</span>
                <div class="con">
                  <div
                    class="itemPay"
                    :class="{active: payType === PayTypeConstant.ALIPAY}"
                    @click="payType = PayTypeConstant.ALIPAY"
                  >
                    <img src="~/assets/images/payment-aliPay.png" alt />
                    <span class="payment-text">{{$t('payment.aliPay')}}</span>
                    <div v-html="payHtml"></div>
                  </div>
                  <div
                    class="itemPay"
                    :class="{active: payType === PayTypeConstant.WECHATPAY_SWEEP_CODE}"
                    @click="payType = PayTypeConstant.WECHATPAY_SWEEP_CODE"
                  >
                    <img src="~/assets/images/payment-wechatPay.png" alt />
                    <span class="payment-text">{{$t('payment.wechatPay')}}</span>
                  </div>
                  <!-- <div
                    class="itemPay paypal"
                    :class="{active: payType === PayTypeConstant.PAYPAL}"
                    @click="payType = PayTypeConstant.PAYPAL"
                  >
                    <img class="paypal-logo" src="~/assets/images/paypal.png" alt />
                    <img class="paypal-text" src="~/assets/images/paypal-text.png" alt />
                  </div> -->
                </div>
              </div>

              <a
                href="javascript:void(0)"
                :class="[isCanTopUp ? '' : 'no-pay', 'btn']"
                @click="toTopUp"
              >{{$t('myBalance.topUpNow')}}</a>
            </div>
          </div>
        </div>
      </div>
    </div>

    <el-dialog title="" :visible.sync="dialogTableVisible" width="60%" :before-close="beforeClose">
      <weixin-pay-code :weixinCodeUrl="weixinCodeUrl"  v-if="weixinCodeUrl !== '' && dialogTableVisible" ref="weixinCod"/>
    </el-dialog>
    <!-- /余额充值 -->

  </div>
</template>

<script>
import { PayType } from '~/plugins/constant'
import Pagination from '~/components/pagination'
import weixinPayCode from '~/components/weixin-pay-code'
export default {
  data () {
    return {
      scoreDetList: [], // 列表
      sts: this.$route.query.sts || 0,  //tab状态
      customAmounts: '',  //自定义金额
      isCanTopUp: true,  //是否能充值
      currentBalance: 0,  //当前可用余额
      topUpList: [], // 套餐
      rechargeId: '',

      scoreCurrent: 1,
      scorePages: 1, // 总页数
      scoreSize: 10,

      PayTypeConstant: PayType,  //支付类型常量
      payType: PayType.ALIPAY,  //支付类型，默认支付宝
      payHtml: '',  //支付宝页面
      weixinCodeUrl: '', //微信二维码数据

      dialogTableVisible: false,
      checkIsPay: null,
      title: '',
      tip: ''
    }
  },
  components: {
    weixinPayCode,
    Pagination
  },
  mounted () {
    // 设置网页标题
    document.title = this.$i18n.t('myBalance.myBalance')
    //中心信息
    this.$axios.get('/p/userBalance/getBalanceInfo').then(({ data }) => {
      this.currentBalance = data
    })

    //获取
    // this.getScoreDet()

    // 切换tab
    this.changeTab(this.sts)

    this.getList()

  },

  methods: {

    //获取
    getScoreDet () {
      let params = {
        current: this.scoreCurrent,
        size: this.scoreSize,
      }
      this.$axios.get('/p/userBalanceLog/log', { params }).then(({ data }) => {
        this.scoreDetList = data.records
        this.scorePages = data.pages
        this.scoreCurrent = data.current
      })
    },

    // 获取充值数据列表
    getList() {
      this.$axios.get('/p/userBalance/getList').then(({ data }) => {
        this.topUpList = data
        if (this.topUpList.length === 0) {
          this.changeNum()
          return
        }
        this.selectAmount(data[0])
      })
    },

    // 选择充值金额
    selectAmount(item) {
      this.rechargeId = item.balanceId
      // this.title = this.$t('myBalance.topUp') + item.rechargeAmount + this.$t('myBalance.yuan')
      this.title = item.balanceTitle
      let tip = ''
      const head = this.$t('myBalance.rechargeoffer')
      if (item.presAmount) {
        tip += this.$t('myBalance.give') + item.presAmount + this.$t('myBalance.yuan') + this.$t('myBalance.comma')
      }
      if (item.presGrowth) {
        tip += this.$t('myBalance.give') + item.presGrowth + this.$t('myBalance.growthValue') + this.$t('myBalance.comma')
      }
      if (item.presScore) {
        tip += this.$t('myBalance.give') + item.presScore + this.$t('myBalance.integral') + this.$t('myBalance.comma')
      }
      if(item.couponList !== null) {
        if (item.couponList.length > 0) {
          tip += this.$t('myBalance.give') + item.couponList.length + this.$t('myBalance.coupons')
          tip += '【'
          let couponStr = ''
          item.couponList.forEach((coupon, index) => {
            couponStr += coupon.couponName + (index < item.couponList.length - 1 ? '、' : '')
          });
          tip += couponStr + '】'
        }
      }
      if (tip !== '') {
        tip = head + tip
      }
      this.tip = tip
      this.customAmounts = ''
    },

    //切换tab
    changeTab (sts) {
      this.sts = sts  //0 1余额充值
      this.current = 1
      this.pages = 1
      if (sts == 0) {
        // 获取
        this.getScoreDet()
      } else {
        
      }
    },
    
    //余额充值
    balanceTopUp() {
      this.sts = 1
    },

    changeNum () {
      this.rechargeId = -1
      this.title = this.$t('myBalance.customAmounts')
      this.tip = this.$t('myBalance.upToTopUp')
      const customAmounts = this.customAmounts
      this.customAmounts = this.checkInput(customAmounts)
      if (Number.parseFloat(this.customAmounts) > 100000) {
        this.customAmounts = 100000
      }
    },    
    /**
     * input输入框只允许输入正数和小数(保留小数点后两位)
     */
    checkInput (num) {
      if (num) {
        var tmpVal = num.replace(/[^\d^\\.]/g, '')
        var reg = /^(0|([1-9]\d*))(\.\d{1,2})?$/ // 最多允许后输入两位小数
        if (!reg.test(tmpVal)) {
          tmpVal = tmpVal + ''
          tmpVal = tmpVal.substring(0, tmpVal.indexOf('.') + 3)
          var n = (tmpVal.split('.')).length - 1
          if (n > 1) {
            tmpVal = tmpVal.substring(0, tmpVal.indexOf('.'))
          }
        }
        return tmpVal
      } else {
        return ''
      }
    },

    // 立即充值
    toTopUp() {
      if(this.rechargeId === '' ) {
        this.$message({
            message: this.$t('myBalance.amountNull'),
            type: 'warning',
            duration: 1000
          })
          return
      }
      if(this.rechargeId === -1 && this.customAmounts === '') {
        this.$message({
            message: this.$t('myBalance.amountNull'),
            type: 'warning',
            duration: 1000
          })
          return
      }
      let {
        protocol,
        host
      } = window.location
      let redirectUrl = `${protocol}//${host}` + '/user-center/uc-balance'
      let payType = this.payType
      let customRechargeAmount = this.customAmounts
      let rechargeId = this.rechargeId
      const rechargeBalanceData = {
        payType: payType,
        returnUrl: redirectUrl,
        id: rechargeId,
        customRechargeAmount: Number.parseFloat(customRechargeAmount),
        scene: ''
      }
      this.$axios.post('/p/balance/pay', rechargeBalanceData).then(({ data }) => {
        if(payType === 2) {
          this.payHtml = data
          this.$nextTick(() => {
            document.forms[0].submit()
          })
        }
        if(payType === 3) {
          this.weixinCodeUrl = data
          this.dialogTableVisible = true
          this.isPay()
        }
      }).catch((err) => {
        console.log(err)
      //   // util.getSysPaySwitch(true)
      })
    },

    // 判断是否支付
    isPay() {
      this.checkIsPay = window.setInterval(() => {
        if(!this.dialogTableVisible) {
          window.clearInterval(this.checkIsPay)
        }
        this.$axios.get('/p/balance/isPay').then(({ data }) => {
          if (data === 1) {
            window.clearInterval(this.checkIsPay)
            this.$router.go(0)
          }
        })
      }, 3000)
    },

    beforeClose(done) {
      this.dialogTableVisible = false
      done()
    }

  }

}
</script>

<style scoped src='~/assets/css/uc-balance.css'></style>
<style scoped src='~/assets/css/user-center.css'></style>
