<import name="x-page" src="../../components/page/page.ux"></import>
<template>
  <div class="consume-record__wrap">
    <div class="stack" style="background-color: #ff8b63" if="{{activity}}">
      <image
        src="https://cdn-novel.iycdm.com/h5/channelActivity/activity-2020-04-17/20200417173207-bg.jpeg"
      ></image>
      <div class="contain">
        <text class="promotion-title" if="{{activity.isForever!='1'}}"
          >活动时间:{{ activity.startTime.substring(0, 10) }} 至 {{ activity.endTime.substring(0, 10)}}</text>
        <div
          class="charge-item {{currentIdx==$idx?'charge-on':''}}"
          for="{{activity.products}}"
          @click="chooseItem($item, $idx)"
        >
          <block if="{{$item.type=='YEAR_ORDER'}}">
            <text class="limit {{currentIdx==$idx?'checked':''}}"
              >限充{{ $item.limit }}次</text
            >
            <text class="title"><span>365包年</span></text>
            <text class="desc">全站小说免费阅读</text>
          </block>
          <block elif="{{$item.type=='QUARTER'}}">
            <text class="limit {{currentIdx==$idx?'checked':''}}"
              >限充{{ $item.limit }}次</text
            >
            <text class="title"><span>98元包季</span></text>
            <text class="desc">全站小说免费阅读</text>
          </block>
          <block else>
            <text class="limit {{currentIdx==$idx?'checked':''}}"
              >限充{{ $item.limit }}次</text
            >
            <text class="title"
              >充<span>{{ $item.price }}元</span>得<span
                >{{ $item.total }}书币</span
              ></text
            >
            <text class="desc">多得{{ $item.given }}书币</text>
          </block>
        </div>

        <text class="charge-button" @click="wantCharge">
          立即充值
        </text>
      </div>
      <div class="rule">
        <text class="rule-bd">活动说明</text>
        <text>1.充值后书币到账可能有延迟，1小时内未到账请到个人中心联系客服</text>
        <text>2.未满18周岁的未成年人应在法定监护人同意后进行充值</text>
        <text>3.此充值为书币充值，1元=100书币</text>
        <text>4.充值书币，鉴于网络服务性质特殊属于不宜退货商品，不适用无理由退换规定</text>
      </div>
    </div>
    <!--  <div class="loading-wrap" if="showLoading">
			<div class="loading-content">
				<progress type="circular"></progress>
				<text class="loading-text">{{loadingText}}</text>
			</div>
		</div> -->
    <div class="mask" if="{{showPay}}" @click="closeMask">
      <div class="pop-pay">
        <div class="title-pay">
          <text class="index"></text><text>支付方式</text>
          <image src="../../assets/imgs/close.png" @click="closeMask"></image>
        </div>
        <div
          class="pay-item"
          @click="changePayType(0)"
          if="{{activity.payChannels.wechat=='1'}}"
        >
          <div class="item-left">
            <image src="../../assets/imgs/wechat.png"></image
            ><text>微信支付</text>
          </div>
          <image
            src="../../assets/imgs/pay_checked.png"
            class="checked"
            if="{{!payType}}"
          ></image>
          <image
            src="../../assets/imgs/rank_grey.png"
            class="checked"
            if="{{payType}}"
          ></image>
        </div>
        <div
          class="pay-item"
          @click="changePayType(1)"
          if="{{activity.payChannels.ali=='1'}}"
        >
          <div class="item-left">
            <image src="../../assets/imgs/zfb.png"></image
            ><text>支付宝支付</text>
          </div>
          <image
            src="../../assets/imgs/rank_grey.png"
            class="checked"
            if="{{!payType}}"
          ></image>
          <image
            src="../../assets/imgs/pay_checked.png"
            class="checked"
            if="{{payType}}"
          ></image>
        </div>
        <text class="charge-now" @click="goPay">确认充值</text>
      </div>
    </div>
  </div>
</template>
<script>
import { configWxPay, configAliPay } from '../../helper'
import { getAcitivity, getUserInfo, checkWxOrder ,advertOrders} from '../../api'
import { getAppConfig, getToken } from '../../api/utils'
import router from '@system.router'
import prompt from '@system.prompt'
import storage from '@system.storage'

export default {
  public: {
    token: '',
     pay_back: 0,
  },
  private: {
    showPay: false,
    activity: null,
    payType: 0,
    currentProduct: null,
    currentIdx: 0,
    showLoading: false,
    pay_order_id:"",
    trade_no:"",
    haslogin: '',
    loginPhone: '',
    pay_success:false,
    need_check_order:false,
  },
    async onInit() {
    // getAppConfig(this);
    this.getUserInfo()
    setTimeout(() => {
      this.getAcitvy()
    }, 1000)
 
    getConfig = getAppConfig(this)
    let { pay_back_alert_show } = await getConfig('task_center')
    this.pay_back = pay_back_alert_show
  },
  changePayType(type, evt) {
    evt.stopPropagation()
    this.payType = type
    return false
  },
  closeMask() {
    this.showPay = false
  },
  async getAcitvy() {
    let activity = await getAcitivity(this.token)
    this.activity = activity
    this.currentProduct = this.activity.products[0]
  },
  wantCharge() {
    // console.log("this.send_order_id",this.send_order_id,"this.haslogin",this.haslogin,'this,loginphone',this.loginPhone);
    if (!(this.send_order_id || (this.haslogin && this.loginPhone))) {
      prompt.showDialog({
        title: '友情提示',
        message: '您还未绑定手机号，请绑定手机号后在进行相关操作',
        buttons: [
          {
            text: '前往绑定',
            color: '#33dd44'
          }
        ],
        success: function(data) {
          router.push({
            uri: '/views/Phone'
          })
        },
        cancel: function() {
          console.log('取消绑定')
        }
      })
    }else{
       this.showPay = true 
    }
  },
  async getUserInfo() {
   try{
      this.loginPhone = (await storage.get({ key: 'loginPhone' })).data
    this.haslogin = (await storage.get({ key: 'hasLogin' })).data
    let userinfo = await getUserInfo()
    if(userinfo){
      console.log('userinfo',userinfo);
      this.send_order_id = userinfo.send_order_id;
    }
   }catch(e){
    //  console.log('11111111111111',e);
   }
  },
  chooseItem(product, idx) {
    this.currentProduct = product
    this.currentIdx = idx
  },
  async goPay(evt) {
    
    evt.stopPropagation()
    
    let cur_pay_type = this.payType
    let product_id = this.currentProduct.product_id
    let ret = null
    this.need_check_order = false;
    this.pay_order_id = "";
    this.trade_no = "";
    if (cur_pay_type == 1) {
      ret = await configAliPay({
        product_id: product_id,
        send_order_id: this.send_order_id,
        activity_token: this.token
      })
      this.trade_no = ret.order;
      this.showToastByCode(ret.code);
    } else {
      ret = await configWxPay({
        product_id: product_id,
        send_order_id: this.send_order_id,
        activity_token: this.token
      })
      this.trade_no = ret.order;
      this.pay_order_id =ret.order;
      this.need_check_order = true;
    }

    return false;
    // 成功支付后的回调操作
    if (ret.code === '9000') this.showWaitingWrap(ret)
    else this.showToastByCode(ret.code)
  },
  checkOrder(order_info) {
    this.showLoading = true
    let { data, order } = order_info
    let times = 10
    /* this.loadingText = `订单查询中...${times}s`;
    this.timer = setInterval(async () => {
      if (times === 0) clearInterval(this.timer), this.showToastByCode("6004");
      else {
        times--;
        this.loadingText = `订单查询中...${times}s`;
        let fb = await checkWxOrder(order);
        if (fb && typeof fb === "object") clearInterval(this.timer), this.showToastByCode("9000");
      }
    }, 1000); */
    setTimeout(() => {
      if (router.getLength() === 1) {
        router.replace({ uri: '/views/Index' })
        return true
      } else {
        router.back()
      }
    }, 2000)
  },async onShow() {
    // console.log('11111111111111111111111-onshow');
     await this.getUserInfo();
    if(this.need_check_order && this.pay_order_id){
        this.checkOrderNew(this.pay_order_id);
    }
  },async checkOrderNew(order){
      console.log("需要查询订单",order);
      // this.showLoading = true;
      let fb = await checkWxOrder(order);
      // console.log('查询结果：',fb);
      //  this.showToastByCode('9000')
      if (fb && typeof fb === 'object'){
        this.showToastByCode('9000')
      }else{
        this.showToastByCode('6001')
      }
  },
  showToastByCode(code) {
    this.showLoading = false
    this.pay_success = false;
    let msg = '支付成功！'
    switch (code) {
      case '9000':
         this.pay_success = true;
         try{
            advertOrders(this.trade_no);
          }catch(e){
            console.log(e);
          }
         msg = '支付成功！'
        break
      case '8000':
        msg = '订单已提交，请等待结果'
        break
      case '4000':
        msg = '订单支付失败！'
        break
      case '5000':
        msg = '订单重复！'
        break
      case '6001':
        msg = '您已取消支付'
        break
      case '6002':
        msg = '网络错误！'
        break
      case '6004':
        msg = '请联系客服查询订单'
        break
      default:
        msg = '请联系客服' + code
    }

    prompt.showToast({ message: msg })
  },
  showWaitingWrap(order) {
    prompt.showDialog({
      title: '支付结果',
      message: '请确认支付结果',
      buttons: [
        {
          text: '已支付',
          color: '#EF5952'
        },
        {
          text: '重新选择金额',
          color: '#999'
        }
      ],
      success: data => {
        if (data.index === 0) this.checkOrder(order)
      },
      cancel: () => {
        console.log('cancel')
      }
    })
  },onBackPress(){
    // console.log(this.pay_success,this.pay_success);
    if (!this.pay_success) {
        let taht = this;
        prompt.showDialog({
          title: '温馨提示',
          message: '每日完成任务，可以免费获取书币~',
          buttons: [
            {
              text: '去做任务',
              color: '#EF5952'
            },
            {
              text: '我知道了',
              color: '#999'
            }
          ],
          success: function(data) {
            if (data.index === 1) {
              taht.getLastpage();
            } else {
              router.push({
                uri: '/views/Task'
              })
            }
          },
          cancel: function() {
            console.log('取消前往')
          }
        })
        return true;
    }else{
      this.getLastpage();  
    }
    return true;
  },getLastpage(){
    let backPage = {};
      try{
        let page = router.getState();
        let allPage = router.getPages();
        // console.log('page = ',page,'all pages',allPage,'length',allPage.length);
        for(var k = allPage.length -1; k >=  0;k--){
          if(allPage[k].name != page.name && allPage[k].name != "views/Phone" && allPage[k].name != "views/Pay"){
            backPage = allPage[k];
            break;
          }
        }
      } catch(e){
        backPage = {};
        // console.log('back err',e);
      }
      // console.log(backPage,backPage.length,typeof backPage);
      if(JSON.stringify(backPage) === '{}'){
         router.replace({ uri: "/views/Index" });
      }else{
        router.back(backPage);
      }
    return true;
  },
}
</script>

<style lang="less">
.mask {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.56);
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
  z-index: 2;
  .charge-now {
    width: 450px;
    height: 80px;
    margin: 20px auto 0;
    border-radius: 40px;
    background-color: #ff6200;
    font-size: 28px;
    color: #fff;
    text-align: center;
  }
  .pay-item {
    justify-content: space-between;
    padding: 10px 30px;
    .checked {
      width: 40px;
    }
    .item-left {
      image {
        width: 60px;
      }
      text {
        font-size: 28px;
        font-weight: bolder;
        margin-left: 26px;
      }
    }
  }
  .pop-pay {
    height: 420px;
    padding: 30px 0;
    background-color: #fff;
    border-top-left-radius: 18px;
    width: 100%;
    flex-direction: column;
    border-top-right-radius: 18px;
    .title-pay {
      justify-content: space-between;
      margin-bottom: 30px;
      border-bottom: 2px solid #ccc;
      padding-bottom: 30px;
      padding-left: 30px;
      padding-right: 30px;
      text {
        color: #333;
        font-weight: bold;
        font-size: 32px;
      }
      image {
        width: 30px;
      }
    }
  }
}
.stack {
  width: 100%;
  flex-direction: column;
  align-items: center;
  image {
    width: 100%;
  }
  .charge-item {
    position: relative;
    .limit {
      width: 100px;
      height: 38px;
      font-size: 20px;
      line-height: 38px;
      text-align: center;
      background-color: #e6e6e6;
      color: #b3b3b3;
      border-bottom-left-radius: 10px;
      border-top-right-radius: 10px;
      position: absolute;
      right: 0;
      top: 0;
    }
    .checked {
      color: #fff;
      background-color: #e82b2f;
    }
  }
  .rule {
    flex-direction: column;
    margin-top: 30px;
    padding: 0 0 100px 0;
    width: 600px;
    margin-left: auto;
    margin-right: auto;
    text {
      text-align: left;
      font-size: 26px;
      color: #fff;
      padding: 10px 0;
    }
    .rule-bd {
      text-align: center;
    }
  }
  .contain {
    background-color: #fff;
    width: 700px;
    padding: 28px;
    border-radius: 14px;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .promotion-title {
      font-weight: bold;
      font-size: 28px;
      text-align: center;
      margin: 10px 0 20px 0;
    }
    .charge-button {
      background-color: #e82b2f;
      width: 600px;
      height: 100px;
      line-height: 100px;
      color: #fff;
      font-weight: bold;
      text-align: center;
      margin-top: 20px;
      border-radius: 60px;
    }

    .charge-item {
      width: 600px;
      background-color: #fff;
      border: 1px solid #e6e6e6;
      color: #333;
      flex-direction: column;
      text-align: center;
      height: 110px;
      justify-content: center;
      align-items: center;
      border-radius: 10px;
      margin: 15px 0;
      .title {
        text-align: center;
        font-size: 36px;
        font-weight: bold;
        span {
          color: #fd555d;
        }
      }
      .desc {
        text-align: center;
        font-size: 28px;
        margin-top: 5px;
      }
    }
    .charge-on {
      background-color: #ffe4c4;
      border: 1px solid #e82b2f;
    }
  }
  .loading-wrap {
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: rgba(0, 0, 0, 0.6);
    justify-content: center;
    align-items: center;

    .loading-content {
      width: 300px;
      height: 100px;
      border-radius: 6px;
      background-color: #fff;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      .loading-text {
        font-size: 26px;
      }
    }
  }
}
</style>
