<template>
  <div class="member-center">
    <!-- 头部 -->
    <MemberHeader />
    <!-- /头部 -->
    <div class="content buy-member">
      <div class="tit">
        <div class="tit-bg"></div>
        <div class="text">
          {{$t('memberCenter.currentGrowthValue')}}：
          <span class="number">{{memberInfo.growth}}</span>
        </div>
        <div class="tit-bg tit-r"></div>
        <!-- 会员等级 -->
      </div>
      <!-- 会员等级 -->
      <div class="item-box">
        <div class="item" v-for="(item,index) in userLevels" :key="index">
          <div class="bg">
            <img :src="item.img" alt />
          </div>
          <div class="text-box">
            <div class="level">{{item.levelName}}</div>
            <!-- 期数类型 1:日 2:周 3:月 4:季 5:年 -->
            <div class="time">{{$t('memberCenter.shoppingMall')}}：{{item.term}} {{['',$t('dayRi'),$t('week'),$t('month'),$t('season'),$t('year')][item.termType]}}</div>
            <div class="price">
              ￥
              <span class="big">{{item.needAmount}}</span>
            </div>
            <div class="btn-box">
              <div class="limit">{{$t('memberCenter.memberGrowthValue')}} ≥ {{item.needGrowth}} {{$t('memberCenter.availablePurchase')}}</div>
              <div
                class="btn"
                :class="(memberInfo.growth < item.needGrowth) ? 'default' : ''"
                @click="buyNow(item,index)"
              >{{$t('buyNow')}}</div>
            </div>
          </div>
        </div>
      </div>
      <!-- /会员等级 -->
    </div>
    <!-- 支付弹窗 -->
    <div class="popup-mask" v-if="isShowPop"></div>
    <div class="popup-box" v-if="isPayPop">
      <div class="tit">
        <div class="text">{{$t('memberCenter.purchaseMembership')}}</div>
        <div class="close" @click="closePop"></div>
      </div>
      <div class="con">
        <div class="pay-number">
          <div class="text">{{$t('memberCenter.openingTips1')}}</div>
          <div class="number">{{userLevels[curIndex].levelName}}</div>
          <div class="text">{{$t('memberCenter.openingTips2')}}</div>
          <div class="number">{{userLevels[curIndex].needAmount}}</div>
          <div class="text">{{$t('memberCenter.yuan')}}</div>
        </div>
        <div class="pay-way">
          <div class="item" @click="choosePayWay(PayTypeConstant.ALIPAY)">
            <img src="~/assets/images/payment-aliPay.png" alt />
            <span class="payment-text">{{$t('payment.aliPay')}}</span>
          </div>
          <div v-if="payHtml" v-rich="payHtml"></div>
          <div class="item" @click="choosePayWay(PayTypeConstant.WECHATPAY_SWEEP_CODE)">
            <img src="~/assets/images/payment-wechatPay.png" alt />
            <span class="payment-text">{{$t('payment.wechatPay')}}</span>
          </div>
          <div class="item" @click="choosePayWay(PayTypeConstant.BALANCEPAY)">
            <img class="item-balance-img" src="~/assets/images/balancePay.png" alt>
            <span class="item-balance-span">
              {{$t("payment.balancePay")}}
            </span>
          </div>
        </div>
      </div>
    </div>
    <!-- /支付弹窗 -->
    <!-- 微信支付弹窗 -->
    <div class="popup-box" v-if="isWxPop">
      <div class="tit">
        <div class="text">{{$t('memberCenter.weChatPayment')}}</div>
        <div class="close" @click="closePop"></div>
      </div>
      <div class="con">
        <div class="weixin-pay-code">
          <div class="text">{{$t('memberCenter.weChatSweepPayment')}}</div>
          <div class="qrcode">
            <canvas id="wxPayQrCode"></canvas>
          </div>
          <div class="btn-box">
            <a href="javascript:void(0)" class="btn" @click="paySuccess">{{$t('memberCenter.completedPayment')}}</a>
            <a href="javascript:void(0)" class="btn gray" @click="closePop">{{$t('memberCenter.cancel')}}</a>
          </div>
        </div>
      </div>
    </div>
    <!-- /微信支付弹窗 -->
  </div>
</template>

<script src='~/assets/js/load-transition'></script>
<script>

import MemberHeader from '~/components/member-header'
import { PayType } from '~/plugins/constant'
import QRCode from 'qrcode'
export default {
  layout: 'home',
  components: {
    MemberHeader
  },
  data () {
    return {
      memberInfo: {},  //会员等级信息
      userLevels: [],  //付费会员等级列表
      isShowPop: false,  //是否显示弹窗
      isPayPop: false,  //是否显示支付方式弹窗
      isWxPop: false,  //是否微信支付弹窗
      payType: null,  //支付类型
      PayTypeConstant: PayType,  //支付类型常量
      curIndex: 0,  //当前套餐
      memberLevelId: null,  //当前会员等级id
      payHtml: '',  //支付宝支付页面
      currentBalance: 0 //余额
    }
  },
  mounted () {
    // 设置网页标题
    document.title = this.$i18n.t('memberCenter.purchaseMembership')
    //获取会员等级信息
    this.$axios.get('/p/score/scoreLevel/page?levelType=' + 0).then(({ data }) => {
      this.memberInfo = data
    })

    //获取付费会员等级列表
    this.$axios.get('/p/score/scoreLevel/page?levelType=' + 1).then(({ data }) => {
      this.userLevels = data.userLevels
    })

    this.getBalanceInfo()

  },
  methods: {

    //立即购买
    buyNow (item, index) {
      if (this.memberInfo.growth >= item.needGrowth) {
        this.isShowPop = true
        this.isPayPop = true
        this.curIndex = index
        this.memberLevelId = item.id
      }
    },
    // 请求余额数据
    getBalanceInfo() {
      this.$axios.get('/p/userBalance/getBalanceInfo').then(({ data }) => {
        this.currentBalance = data
      })
    },

    //选择支付方式
    choosePayWay (type) {
      if (type == PayType.ALIPAY) {
        // 支付宝部分
        this.$axios.post('/p/level/payLevel', {
          id: this.memberLevelId,
          payType: type,
          returnUrl: window.location.origin + '/member-center/member-center'
        }).then(({ data }) => {
          this.payHtml = data
          this.$nextTick(() => {
            document.forms[0].submit()
          })
        })
      } else if (type == PayType.WECHATPAY_SWEEP_CODE) {
        // 微信部分
        this.$axios.post('/p/level/payLevel', {
          id: this.memberLevelId,
          payType: type,
        }).then(({ data }) => {
          this.isWxPop = true
          this.isPayPop = false
          this.$nextTick(function () {
            QRCode.toCanvas(document.getElementById('wxPayQrCode'), data, { version: 6, errorCorrectionLevel: 'L' })
          })
        })
      } else if (type === PayType.BALANCEPAY) {
              // 余额部分
              const that = this
              let total = this.userLevels[this.curIndex].needAmount
              if (total > parseFloat(this.currentBalance)) {
                this.$message({
                  message: this.$t("myBalance.balanceInsufficient") + this.currentBalance,
                  type: 'warning',
                  duration: 3000
                })
                return
              }
              this.closePop()
              this.$confirm(this.$t("myBalance.payTips"), this.$t("tips"),{
                distinguishCancelAndClose: true,
                confirmButtonText: this.$t("determine"),
                cancelButtonText: this.$t("cancel")
              }).then(() => {
                this.$axios.post('/p/level/payLevel', {
                  id: this.memberLevelId,
                  payType: type,
                }).then(({ data }) => {
                  if (data.type == 1) {
                        this.$message({
                          message: this.$t('payment.paymentSuccessful'),
                          type: 'success',
                          duration: 1000,
                          onClose() {
                            that.$router.push({ path: '/member-center/member-center' })
                          }
                        })             
                  } else {
                    this.$message({
                        message: res.message,
                        type: 'error',
                        duration: 1000
                    })
                  }
                })
              }).catch(action => {})

      }
    },

    //关闭弹窗
    closePop () {
      this.isShowPop = false
      this.isPayPop = false
      this.isWxPop = false
    },

    // 点击完成支付
    paySuccess () {
      this.$axios.get('/p/level/isPay', {
      }).then(({ data }) => {
        console.log(data)
        if(data === 1) {
          this.$message({
            message: this.$i18n.t('memberCenter.purchaseSuccess'),
            type: 'success',
            duration: 1500
          })
        }else {
          this.$message({
            message: this.$i18n.t('memberCenter.purchaseFailure'),
            type: 'error',
            duration: 1500
          })
        }
      })
      this.isShowPop = false
      this.isPayPop = false
      this.isWxPop = false
      this.$router.push({
        path: '/member-center/member-center'
      })
    }
  }
}
</script>

<style scoped>
@import '~/assets/css/member-center.css';
@import '~/assets/css/buy-member.css';
@import '~/assets/css/payment.css';
</style>
