<template>
  <div
    :class="[
      'pay',
      {
        'has-banner':
          showPayYearBanner || showSpecialPayTempalte || xiyue_pay_template
      }
    ]"
  >
    <x-header></x-header>
    <template v-if="!xiyue_pay_template">
      <div class="section-edge-all">
        <template v-if="adjust_pay_page && showBookTip">
          <div class="pay-account" style="font-size:14px">
            您的余额：<span class="red">{{ balance }}</span
            >书币,<span v-if="balance > 0"
              >本书全本购买需要：<span class="red">{{ $route.query.fee }}</span
              >书币</span
            >
          </div>
          <div class="pay-explain">
            您的余额不足，请点击下方充值
          </div>
        </template>
        <template v-else>
          <div class="pay-account">
            您的余额：
            <span class="red">{{ balance }}</span>
            书币
            <span
              :class="[
                'red',
                {
                  'no-enough-money': showPayYearBanner || showSpecialPayTempalte
                }
              ]"
              v-if="showTip"
              >{{
                showPayYearBanner || showSpecialPayTempalte ? "" : "(余额不足)"
              }}</span
            >
          </div>
          <div class="pay-fee" v-if="showTip && !showChapterConsume">
            <template v-if="isFirstPay">
              <p v-html="isFirstPay"></p>
            </template>
            <template v-else>
              {{ showBookTip ? "此书全本" : "当前章节" }}需要消耗
              <span class="red">{{ $route.query.fee }}</span
              >书币
            </template>
          </div>
          <div
            class="pay-explain"
            v-if="!showPayYearBanner && !showSpecialPayTempalte"
          >
            选择充值金额
            <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>
        <template v-if="show_month_order_entry">
          <div
            class="pay-product__item pay-product__month"
            @click="chooseMonthOrder"
          >
            <img
              :src="
                isMonthOrder
                  ? show_month_order_entry.focus_img
                  : show_month_order_entry.unfocus_img
              "
              alt=""
            />
          </div>
        </template>
        <ul class="pay-product">
          <!-- <v-touch :class="['pay-product__item',{'is-active': i === selectedProduct, 'is-recommend': i === defaultProduct }]"
                  v-for="(v,i) in product"
                  :key="v.product_id"
                  @tap="selectProduct(i)">
            <p class="pay-product__name">{{v.price}}</p>
            <p class="pay-product__intro">
              <i class="year-vip"
                :class="{'is-active': i === selectedProduct}"
                v-if="v.vip"></i>
              <span v-for="(text,i) in v.intro"
                    :key="i"
                    :class="{red: text.important}">{{text.label}}</span>
            </p>
            <p class="pay-product__intro">
              <span v-for="(text,i) in v.intro2"
                    :key="i"
                    :class="{red: text.important}">{{text.label}}</span>
            </p>
          </v-touch> -->
          <!-- <template v-if="showPayYearBanner">
            <div class="pay-for__year"
                @click="payForYear">
              <img src="../assets/year_banner.jpg"
                  alt="">
            </div>
          </template> -->
          <template v-if="showPayYearBanner">
            <div
              class="pay-product__item"
              @click="selectProduct(product.length - 1)"
            >
              <img
                :src="
                  product.length - 1 === selectedProduct
                    ? year_item_bg_check
                    : year_item_bg
                "
                alt=""
              />
            </div>
          </template>
          <template v-for="(v, i) in product">
            <template v-if="showPayYearBanner">
              <template v-if="i < product.length - 1">
                <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="pay-product__gift">赠送价值{{calcGiftPrice(v.gift)}}书币的礼物道具</p> -->
                </v-touch>
              </template>
              <!-- <template v-else>
                <div class="pay-product__item"
                    :key="'year' + i"
                    @click="selectProduct(i)">
                  <img :src="i === selectedProduct ? year_item_bg_check : year_item_bg"
                      alt="">
                </div>
              </template> -->
            </template>
            <template v-else>
              <template v-if="showSpecialPayTempalte">
                <template v-if="i < product.length - 1">
                  <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>
                  </v-touch>
                </template>
                <template v-else>
                  <template v-if="product.length < 7">
                    <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>
                    </v-touch>
                  </template>
                  <template v-else>
                    <div
                      class="pay-product__item pay-product__item--year"
                      :key="'year' + i"
                      @click="selectProduct(i)"
                    >
                      <img
                        :src="
                          i === selectedProduct
                            ? mi_wan_year_bg_check
                            : mi_wan_year_bg
                        "
                        alt=""
                      />
                    </div>
                  </template>
                </template>
              </template>
              <template v-else>
                <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>
                  <!-- <p class="pay-product__gift">赠送价值{{calcGiftPrice(v.gift)}}书币的礼物道具</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>
        <div
          class="pay-explain"
          v-if="showPayYearBanner || showSpecialPayTempalte"
        >
          选择充值金额
          <span class="red">（1元=100书币）</span>
        </div>
        <!-- <i class="pay-for__gift--txt" v-if="giftPrice"><i @click="see">查看礼物道具详情&gt;</i></p> -->
        <!-- <p class="pay-for__gift--txt"
           v-if="giftPrice">充值赠送价值{{giftPrice}}书币的礼物道具 <i @click="see">点击查看&gt;</i></p> -->
        <div class="gift-fixed__wrap" v-if="giftPrice">
          <p class="gift-title__text">赠送价值{{ giftPrice }}书币的礼物道具</p>
          <div class="gift-preview">
            <span class="title">获赠道具详情</span>
            <div class="preview-wrap">
              <span
                class="gift-preview__item"
                v-for="(g, i) in giftList"
                :key="i"
              >
                <img :src="g.icon" :alt="g.name_desc" />
                <i>{{ g.name_desc }}x{{ g.num }}</i>
              </span>
            </div>
          </div>
        </div>
        <template v-if="showPayYearBanner || showSpecialPayTempalte">
          <div class="pay-btn-box">
            <div v-if="showHelpPay" class="help-pay__btn" @click="toHelpPay">
              请好友代充
            </div>
            <div class="pay-btn" @click="pay">立即充值</div>
          </div>
        </template>
        <template v-else>
          <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>
        <!-- <div class="pay-agreement">点击立即充值，即表示您已同意
          <router-link to="agreement"
                      class="red">《充值协议》</router-link>
        </div> -->
        <!-- <div class="pay-tip">
          <p>若充值遇到问题或充值失败，请联系客服。</p>
          <p>客服QQ：84869600</p>
        </div> -->
        <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>
    <template v-else>
      <!-- 喜悦的充值界面 -->
      <div class="section-edge-all xiyue-pay-template">
        <div class="user-balance">
          <div class="pay-account">
            您的余额：
            <span class="red">{{ balance }}</span>
            书币
            <span class="red no-enough-money" v-if="showTip"></span>
          </div>
          <div class="pay-fee" v-if="showTip && !showChapterConsume">
            <template v-if="isFirstPay">
              <p v-html="isFirstPay"></p>
            </template>
            <template v-else>
              {{ showBookTip ? "此书全本" : "当前章节" }}需要消耗
              <span class="red">{{ $route.query.fee }}</span
              >书币
            </template>
          </div>
        </div>
        <div class="xiyue-entry" @click="chooseXiYueEntry">
          <img
            :src="
              isXYEntrySelect
                ? xiyue_pay_template.xiyue_pay_focus_img
                : xiyue_pay_template.xiyue_pay_unfocus_img
            "
            alt=""
          />
        </div>
        <div class="pay-wrap">
          <div class="pay-explain">
            选择充值金额
            <span class="red">（1元=100书币）</span>
          </div>
          <ul class="pay-product">
            <template v-for="(v, i) in product">
              <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>
              </v-touch>
            </template>
          </ul>
        </div>
        <div class="pay-btn-box">
          <div v-if="showHelpPay" class="help-pay__btn" @click="toHelpPay">
            请好友代充
          </div>
          <div class="pay-btn" @click="payInXiYue">
            {{ xiyue_pay_btn_text }}
          </div>
        </div>
        <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 in availdCouponList">
            <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 { Pay, HelpPayQrcode } from "./namespace.js";
// import product from "../mock/pay.js";
import {
  getProductList,
  subscribeByRMB,
  recharge,
  getUserInfo,
  isMonthOrderSuc,
  getOrderCoupon
} from "../api";

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

export default {
  name: Pay.name,
  data() {
    return {
      HelpPayQrcode: HelpPayQrcode.name,
      balance: "...",
      product: [],
      selectedProduct: 0,
      defaultProduct: null,
      cheaperProduct: null,
      prevRoute: null,
      loading: false,
      showTip: !!this.$route.query.code,
      showBookTip: this.$route.query.code == 10020 || this.$route.query.code == 10019, //全本提醒true，单本提醒false
      isFirstPay: this.$route.query.first_pay_tip,
      adjust_pay_page: !!window.options.adjust_pay_page,
      showHelpPay: window.options.showDaiChong,
      showChapterConsume: window.options.is_hide_chapter_consume,
      showAd_entry: false,
      is_iPhone: navigator.userAgent.indexOf("iPhone") !== -1,
      showPayYearBanner: window.options.outstanding_year_order,
      showSpecialPayTempalte: window.options.special_pay_template,
      year_item_bg: require("../assets/year_charge.png"),
      year_item_bg_check: require("../assets/year_charge_check.jpg"),
      mi_wan_year_bg: require("../assets/mi_wan_year.jpg"),
      mi_wan_year_bg_check: require("../assets/mi_wan_year_check.jpg"),
      month_order_bg: require("../assets/month_order_1.png"),
      month_order_bg_check: require("../assets/month_order_check.png"),
      show_month_order_entry: window.options.month_order_info,
      xiyue_pay_template: window.options.xiyue_info,
      isMonthOrder: false,
      isXYEntrySelect: false,
      xiyue_pay_btn_text: "立即充值",
      isCouponChecked: false,
      couponList: [],
      availdCouponList: [],
      popupVisible: false,
      currentCoupon: {
        id: "",
        price: 0
      }
    };
  },
  computed: {
    giftList() {
      const { product, selectedProduct } = this;
      return selectedProduct && product.length
        ? product[selectedProduct].gift
        : [];
    },
    giftPrice() {
      return this.giftList.reduce((a, b) => {
        return a + b.cost * b.num;
      }, 0);
    },
    chargePrice() {
      let select_pro = this.product[this.selectedProduct];
      let normal_value = select_pro ? select_pro.price : "0";
      let special_value = this.isMonthOrder
        ? this.show_month_order_entry.price
        : normal_value;
      return Number(special_value.replace("元", ""));
    }
  },
  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.isMonthOrder = false;
      this.isXYEntrySelect = false;
      this.xiyue_pay_btn_text = "立即充值";
      this.getAvaildCoupon(
        Number(this.product[this.selectedProduct].price.replace("元", ""))
      );
    },
    pay() {
      if (this.isMonthOrder) {
        this.toMonthOrder();
      } else {
        recharge({
          product_id: this.product[this.selectedProduct].product_id,
          bid: this.$route.query.book_id,
          cid: this.$route.query.chapter_id,
          use_coupon: this.currentCoupon.id
        });
      }
    },
    payForYear() {
      let product_id = this.product[this.product.length - 1].product_id;
      recharge({
        product_id,
        bid: this.$route.query.book_id,
        cid: this.$route.query.chapter_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}`;
    },
    see() {
      PayForGift({ list: this.giftList });
    },
    calcGiftPrice(list) {
      return list.reduce((a, b) => {
        return a + b.cost * b.num;
      }, 0);
    },
    toMonthOrder() {
      const origin = window.location.origin;
      const href = window.location.href;
      // const r = origin + "/monthpay/wait?r=" + encodeURIComponent(href);
      location.href =
        this.show_month_order_entry.link +
        `&use_coupon=${this.currentCoupon.id}`;
    },
    chooseMonthOrder() {
      this.selectedProduct = null;
      this.isMonthOrder = true;
      this.defaultProduct = null;
      console.log("我被选中了");
      this.getAvaildCoupon(
        Number(window.options.month_order_info.price.replace("元", ""))
      );
    },
    //获取当前金额的可用优惠券
    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);
    },
    chooseXiYueEntry() {
      this.selectedProduct = null;
      this.isXYEntrySelect = true;
      this.xiyue_pay_btn_text = "了解更多";
    },
    payInXiYue() {
      if (this.isXYEntrySelect) {
        location.href = this.xiyue_pay_template.xiyue_pay_page;
      } else {
        recharge({
          product_id: this.product[this.selectedProduct].product_id,
          bid: this.$route.query.book_id,
          cid: this.$route.query.chapter_id
        });
      }
    }
  },
  created() {
    this.loading = true;
    getOrderCoupon().then(r => {
      this.couponList = r;
      getProductList(this.$route.query.book_id).then(r => {
        this.product = r;
        this.showAd_entry = !!r[0].show_free_ads;
        this.loading = false;
        this.product_len = r.length;
        r.forEach((p, i) => {
          if (this.product_len === 6 && !this.is_iPhone && this.showAd_entry) {
            if (p.price === "100元") {
              this.product.splice(i, 1);
              i = i - 1;
            }
          }
          if (p.today_special) {
            this.defaultProduct = i;
            this.selectedProduct = i;
            this.getAvaildCoupon(Number(p.price.replace("元", "")));
          }
          if (p.first_charge) {
            this.cheaperProduct = i;
          }
          if (this.show_month_order_entry) {
            this.chooseMonthOrder();
          }

          if (this.xiyue_pay_template) {
            this.chooseXiYueEntry();
          }
        });
      });
    });

    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>
