<template>
  <div class="recharge">
    <section class="plan">
      <p class="title">请选择充值燃料</p>
      <ul>
        <li v-for="({id, name, price, chain_times, chain_price}) in planList" 
          :key="id" class="item" 
          :class="id === selectedPlan.id? 'active': ''"
          @click=" selectedPlan = {id , price, chain_times}">
          <div class="times">{{chain_times}}次</div>
          <div class="right price">¥{{price}}</div>
          <div class="name">{{name}}</div>
          <div class="right">均价：{{chain_price}}</div> 
          <common-svg
            name="gerenzhongxin-xuanze"
            width="30px"
            height="30px"
            class="selected-icon"
            v-show="id === selectedPlan.id"></common-svg>  
        </li>
      </ul>
    </section>
    <section class="method">
      <p class="title">选择支付方式</p>
      <van-radio-group v-model="method">
        <van-cell 
          v-for="(item, key) in payMethods"
          :key="key"
          :title="item.title"
          @click="method = item.method"
          center clickable>
          <template #icon>
            <common-svg :name="item.icon" style="margin-right:10px;"></common-svg>
          </template>
          <template #right-icon>
            <van-radio :name="item.method" />
          </template>
        </van-cell>
      </van-radio-group>
    </section>
    <div @click="recharge" class="slc-btn-common btn">充值</div>
    <section style="display:flex;align-items:center;justify-content:center;color:#3F79FE;font-size:12px;margin-top:15px;">
      <router-link tag="span" to="/rechargeRecord">充值记录</router-link>
      <router-link to="/contect" tag="span" style="margin-left:10px;">联系客服</router-link>
    </section>
    <section class="explain">
      <p class="title">年费说明</p>
      <p>1、燃料充值年费说明：开通年费会员后，充值的套餐有效期一年，隔年自动作废，请尽快使用。</p>
      <p>2、套餐选购：按需购买套餐，套餐金额越大，单价越低，根据您的上链数量进行选购；</p>
      <p>3、充值未完成时请不要切换账户，或者退出，否则可能出现充值不到账的情况。</p>
    </section>
    <van-popup v-model="confirm" :overlay="false" :style="{ height: '100%', width: '100%'}">
      <div class="bg"></div>
      <section class="confirm-recharge" >
          <div class="box">
              <div style="font-size:20px;">确认付款</div>
              <div style="font-size: 40px;margin-top:60px;">￥{{selectedPlan.price}}</div>
              <div style="color:#B6B7B9;font-size: 16px;">燃料次数：{{selectedPlan.chain_times}}次</div>
              <div style="text-align:left;margin-top:42px"> 
                <common-svg :name="payMethods[method].icon" style="margin-right:10px;"></common-svg>{{payMethods[method].title}}
              </div>
              <div @click="payHandler" class="slc-btn-common" style="display:inline-block;width:200px;height:40px;line-height:40px;margin-top:12px;">立即充值</div>
          </div>
      </section>
    </van-popup>
    <van-popup v-model="isCallback" style="padding: 30px; margin: 0 auto;width: 70%;color:#353535;font-size:18px;text-align:center;border-radius:4px;">
        <div>请确定微信支付是否已完成</div>
        <div
          @click="confrimPayed"
          style="color:#3F79FE;border: 1px solid;margin-top:19px;line-height: 40px;">已完成支付</div>
        <div
          @click="rePay"
          style="margin-top:19px;color:#B6B5BA;">支付遇到问题，重新支付</div>
    </van-popup>
  </div>
</template>
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import { Cell, Form, Field, CellGroup, Button, Image, RadioGroup, Radio, Popup, Dialog } from 'vant';
import { Getter, State } from 'vuex-class';
import { Route } from 'vue-router';
@Component({
  components: {
    [Form.name]: Form,
    [Field.name]: Field,
    [Button.name]: Button,
    [Image.name]: Image,
    [Cell.name]: Cell,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Popup.name]: Popup,
    [Dialog.Component.name]: Dialog.Component,
  },
})
export default class Recharge extends Vue {
  @State('userInfo') private userInfo!: any;
  private redirectUrl: string = '';
  @Prop()
  private isCallback!: boolean;
  private readonly payMethods: any = {
    0: {
      title: '支付宝',
      icon: 'gerenzhongxin-zhifubaozhifu',
      method: 0,
    },
    1: {
      title: '微信',
      icon: 'gerenzhongxin-weixinzhifu2',
      method: 1,
    },
  };
  private planList: any[] = [];
  private selectedPlan: any = {
    planId: -1,
    price: -1,
    chain_times: 0,
  };
  private method: number = 0;

  private orderId: string = '';

  private confirm: boolean = false;
  private mounted() {
    this.$api.plan.list(1).then(({results = []}: any) => {
      this.planList = results;
      const [{ id , price, chain_times}] = this.planList;
      this.selectedPlan = {
        id,
        price,
        chain_times,
      };
    });
  }
  private beforeRouteLeave(to: Route, from: Route, next: (params?: any) => void) {
    if (!this.confirm) { return next(); }
    this.$dialog.confirm({
      title: '提示',
      message: '点击“返回”将中断操作，确定返回？',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    }).then(() => {
      next();
    }).catch(() => {
      next(false);
    });
  }
  private async recharge() {
    try {
      const { id } = await this.$api.order.add(this.selectedPlan.id, this.method);
      this.confirm = true;
      this.orderId = id;
    } catch (err) {
      if (err.code === 10603) {
        this.$dialog.confirm({
          title: '提示',
          message: '您的账户还很充足请剩余少量余额时进行充值',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        });
      }
    }
  }
  private async payHandler() {
    const { protocol, host } = location;
    const { pay_url } = await this.$api.order.pay(this.orderId, this.method);
    localStorage.setItem('orderId', this.orderId);
    const redirectUrl = encodeURIComponent(`${protocol}//${host}/#/recharge?isCallback=true`);
    this.redirectUrl = this.method === 0 ? pay_url : `${pay_url}&redirect_url=${redirectUrl}`;
    localStorage.setItem('payUrl', this.redirectUrl);
    location.href = this.redirectUrl;
    // (window as any).appslc.toPay(this.redirectUrl);
  }
  private async confrimPayed() {
    const { protocol, host } = location;
    this.orderId = String(localStorage.getItem('orderId'));
    this.redirectUrl = String(localStorage.getItem('payUrl'));
    if (!this.orderId || !this.redirectUrl) {
      return this.redirectToRecharge();
    }
    const { status } = await this.$api.order.get(this.orderId);
    if (status === 2) { // 0:未支付 1:支付中 2:支付成功 3:支付失败
      this.$router.replace({name: 'RechargeSuccess'});
    } else {
      this.$dialog.confirm({
        title: '提示',
        message: '您当前还没有完成付款，请点击[继续付款]进行支付',
        confirmButtonText: '继续付款',
        cancelButtonText: '取消',
      }).then(() => {
        location.href = this.redirectUrl;
      }).catch((err) => {
        this.$router.push({path: '/userCenter/index'});
      });
    }
  }
  private redirectToRecharge() {
    localStorage.setItem('orderId', '');
    localStorage.setItem('payUrl', '');
    this.$router.replace({name: 'Recharge'});
  }
  private rePay() {
    this.redirectToRecharge();
  }
}
</script>
<style scoped lang="scss">
  .recharge{
    position: relative;
    padding: 17px;
    text-align: left;
    display: flex;
    flex-direction: column;
    justify-content: center;
    .plan{
      p.title{
        color:#353535;
        font-size: 16px;
        font-weight: 500;
      }
      .item{
        position: relative;
        display: grid;
        grid-template-columns: repeat(2,1fr);
        grid-template-rows: repeat(2,30px);
        place-items: center start;
        padding: 3px 23px;
        margin-top: 10px;
        font-size: 12px;
        color: #B6B5BA;
        border-radius:4px;
        border:1px solid rgba(230,230,230,1);
        &.active{
          border-color: #3175FF;
        }
        .right{
          place-self: center end;
        }
        .times{
          color:#353535;
          font-size: 20px;
          font-weight: 600;
        }
        .price{
          color:#353535;
          font-size: 18px;
        }
        .selected-icon{
          position:absolute;
          left:0;
          top:0;
        }
      }
    }
    .method{
      .title{
        color:#353535;
        font-size: 16px;
        font-weight: 500;
      }
    }
    .btn{
      width: 200px;
      height: 40px;
      align-self: center;
      line-height: 40px;
      text-align: center;
      font-size: 14px;
    }
    .explain{
      .title{
        font-size: 14px;
        color: #353535;
      }
      color: #A1A1A1;
      font-size: 12px;
    }
    div.bg{
        height: 179px;
        background: #5D73F1;
      }
    .confirm-recharge{
      display: flex;
      align-items: center;
      justify-content: center;
      background: #FFFFFF;
      color: #353535;
      div.box{
        position: absolute;
        top: 39px;
        left: 30px;
        right: 30px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        padding: 26px;
        border-radius: 4px;
        box-shadow:0px 2px 10px 0px rgba(0,0,0,0.09);
        border-radius:4px;
        background: #FFFFFF;
        font-size: 16px;
        text-align: center;
      }
    }
    .confirm-result {
      font-size: 18px;
      color: $fontColorBlack;
    }
  }
</style>