<template>
  <div class='pay'>
    <x-header></x-header>
    <template>
      <div class="section-edge-all">
        <template>
          <div class="pay-account">
            您的余额：
            <span class="red">{{ balance }}</span>
            书币
            <span class="red" v-if="showTip">(余额不足)</span>
          </div>
          <div class="pay-explain">
            选择充值金额
            <span class="red">（1元=100书币）</span>
          </div>
        </template>

        <div class="pay-coupon">
          <p class="pay-coupon__img">
            <img src="../assets/coupon _pay.png" />优惠券
          </p>
          <p class="pay-coupon__right" @click="changeCoupon">
            <span v-if="!isCouponChecked">您有{{ availdCouponList.length }}张优惠券待使用</span><span class="usecoupon" v-else>- &yen;{{ currentCoupon.price }}</span>
            <img src="../assets/个人中心-进入.png" />
          </p>
        </div>
        <ul class="pay-product">
          <template v-for="(v, i) in product">
            <template>
              <template>
                <v-touch :class="[
                    'pay-product__item',
                    {
                      'is-active': i === selectedProduct,
                      'is-recommend': i === defaultProduct,
                      'is-first': i === cheaperProduct
                    }
                  ]" :key="v.product_id" @tap="selectProduct(i)">
                  <p class="pay-product__name">{{ v.price }}</p>
                  <p class="pay-product__intro">{{ v.text }}</p>
                  <p class="pay-product__intro cheaper-box" v-if="v.save_text">
                    <span class="text" v-if="v.type=='TICKET_RECHARGE' || v.type=='NEW_USER'">省</span>
                    <span class="text" v-else><i class="is_year"></i></span>
                    <span>{{ v.save_text }}</span>
                  </p>
                  <p class="item-tag" v-if="v.angle_sign_text">
                    {{ v.angle_sign_text }}
                  </p>
                </v-touch>
              </template>
            </template>
          </template>
          <template v-if="showAd_entry && !is_iPhone">
            <v-touch class="pay-product__adwrap" v-if="product.length" @tap="toFreeAds()">
              <img src="../assets/cz.jpg" alt="" />
            </v-touch>
          </template>
        </ul>
        <template>
          <div class="pay-box__fixed">
            <!-- <div v-if="showHelpPay" class="help-pay__btn" @click="toHelpPay">
              请好友代充
            </div> -->
            <div class="pay-btn" @click="pay">
              立即充值
            </div>
          </div>
        </template>
        <p class="pay-shubi-tip">书币属于虚拟商品，一经充值不得退还</p>
        <div class="reader-loading" v-show="loading">
          <mt-spinner class="reader-loading-icon" type="fading-circle" color="#32a1ff"></mt-spinner>
        </div>
      </div>
    </template>
    <mt-popup v-model="popupVisible" position="bottom">
      <div class="pop-coupon" ref="couponList">
        <div class="coupon-list">
          <div class="coupon-item" v-for="(coupon,index) in availdCouponList" :key="index">
            <p class="coupon-item__amount">
              <span>&yen;</span>{{ coupon.price }}
            </p>
            <div class="coupon-item__info">
              <div class="info-amount">
                <p class="title">大于{{ coupon.use_condition }}元可用</p>
                <p class="desc">
                  {{
                    coupon.expire_time && coupon.expire_time.slice(0, 16)
                  }}到期
                </p>
              </div>
              <v-touch class="info-button" @tap="chooseCoupon(coupon)">
                立即使用
              </v-touch>
            </div>
          </div>
        </div>
      </div>
    </mt-popup>
  </div>
</template>
<script>
import { adPay, HelpPayQrcode } from "./namespace.js";
import {
  getProductList,
  orderProductInfo,
  subscribeByRMB,
  adRecharge,
  getUserInfo,
  isMonthOrderSuc,
  getOrderCoupon
} from "../api";

import { PayForGift } from "../components/prompt";

export default {
  name: adPay.name,
  data () {
    return {
      HelpPayQrcode: HelpPayQrcode.name,
      balance: "...",
      product: [],
      selectedProduct: 0,
      defaultProduct: null,
      cheaperProduct: null,
      loading: false,
      showTip: !!this.$route.query.code,
      showHelpPay: window.options.showDaiChong,
      showAd_entry: false,
      is_iPhone: navigator.userAgent.indexOf("iPhone") !== -1,
      isCouponChecked: false,
      couponList: [],
      availdCouponList: [],
      popupVisible: false,
      currentCoupon: {
        id: "",
        price: 0
      }
    };
  },
  computed: {
  },
  methods: {
    changeCoupon () {
      if (this.availdCouponList.length <= 0) {
        this.$MessageBox.alert(
          "当前暂无可用优惠券，请检查充值额度是否满足优惠券使用条件，优惠券是否在有效期",
          "温馨提示"
        );
        return false;
      } else {
        this.popupVisible = true;
        this.$nextTick(() => {
          if (this.$refs.couponList) {
            this.$refs.couponList.scrollTop = 0;
          }
        });
      }
    },
    //选择优惠券
    chooseCoupon (coupon) {
      this.currentCoupon = coupon;
      this.popupVisible = false;
      this.isCouponChecked = true;
    },
    selectProduct (i) {
      this.selectedProduct = i;
      this.getAvaildCoupon(
        Number(this.product[this.selectedProduct].price.replace("元", ""))
      );
    },
    pay () {
      console.log(this.product[this.selectedProduct], this.$route.query.book_id, this.$route.query.chapter_id, this.currentCoupon.id);
      adRecharge({
        product_id: this.product[this.selectedProduct].product_id,
        from_id: this.$route.query.id,
        bid: this.$route.query.book_id,
        cid: this.$route.query.chapter_id,
        use_coupon: this.currentCoupon.id
      });
    },
    toHelpPay () {
      this.$router.push({
        name: this.HelpPayQrcode,
        query: { product_id: this.product[this.selectedProduct].product_id }
      });
    },
    toFreeAds () {
      window.location.href = `${window.location.origin +
        window.options.appad_url}`;
    },
    //获取当前金额的可用优惠券
    getAvaildCoupon (price) {
      this.currentCoupon = { id: "", price: 0 };
      this.isCouponChecked = false;
      this.availdCouponList = this.couponList.filter(
        item => item.use_condition < price
      );
    },
    findMonthOrder () {
      this.$Indicator.open("查询订单中...请稍等");
      let time = 0;
      this.timer = setInterval(() => {
        if (time === 10) {
          this.$Indicator.close();
          window.clearInterval(this.timer);
          this.$Toast("订单可能延迟几分钟，稍后到个人中心查看或联系客服");
          return;
        }
        isMonthOrderSuc()
          .then(_ => {
            this.$Indicator.close();
            window.clearInterval(this.timer);
            this.$Toast("包月订购成功！");
          })
          .catch(e => {
            time++;
            console.log(e, "continue");
          });
      }, 1000);
    },
  },
  created () {
    console.log('-------------', this.$route.query);
    this.loading = true;
    getOrderCoupon().then(r => {
      this.couponList = r;
      orderProductInfo({ id: this.$route.query.product_id }).then(res => {
        res.price = `${res.price}元`
        res.product_id = res.id
        this.product = [res]
        this.loading = false;
      })
    });

    getUserInfo().then(r => {
      this.balance = r.balance;
    });
    // 是否包月回调
    const { from_wxpay } = this.$route.query;
    if (from_wxpay) this.findMonthOrder();
  }
};
</script>

<style lang="scss">
.pay-product {
  // margin-bottom: 2.3rem;
}

.pay-box__fixed {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 1.2rem;
  background: #fff;
  border-top: 1px solid #f7f7f7;
  padding: 0 0.24rem;
  overflow: hidden;

  display: flex;
  justify-content: space-between;
  align-items: center;

  z-index: 999;

  .help-pay__btn {
    width: 3.2rem;
    border-radius: 20px;
    border-color: #e6e6e6;
    color: #e6e6e6;
    height: 0.76rem;
    line-height: 0.76rem;
    margin-right: 0.26rem;
    margin-top: 0;
    font-size: 0.28rem;
  }

  .pay-btn {
    flex: 1;
    margin: 0;
    background: #ef5952;
    border-radius: 20px;
    border: 1px solid #ef5952;
    height: 0.76rem;
    line-height: 0.76rem;
    font-size: 0.28rem;
    font-weight: bold;
    box-shadow: none;
  }
}

.gift-fixed__wrap {
  position: fixed;
  bottom: 1.2rem;
  max-height: 1.1rem;
  left: 0;
  right: 0;
  background: #f7f7f7;
  padding: 0.22rem 0.24rem;

  .gift-title__text {
    color: #ef5952;
    font-size: 0.26rem;
    font-weight: bold;

    &.text-align {
      text-align: center;
    }
  }

  .gift-preview {
    font-size: 0.24rem;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    // overflow: auto;
    // -webkit-overflow-scrolling: touch;

    .title {
      flex-basis: 2rem;
      flex-shrink: 0;
      white-space: nowrap;
      color: #333;
    }

    .preview-wrap {
      flex: 1;
      display: flex;
      overflow: auto;
      -webkit-overflow-scrolling: touch;

      &::-webkit-scrollbar {
        display: none;
      }
    }

    .gift-preview__item {
      font-size: 0;
      flex-shrink: 0;
      white-space: nowrap;
      display: flex;

      i {
        font-size: 0.22rem;
        color: #666;
        font-style: normal;
      }

      &:not(:last-child) {
        margin-right: 0.18rem;
      }
    }

    img {
      width: 0.34rem;
      height: 0.34rem;
    }
  }
}
</style>
