<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">
        <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>
        <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>
        <div class="pay-line"></div>

        <div class="pay-type">
          <p class="title">充值方式</p>
          <div class="pay-type__list">
            <div
              :class="[
                'pay-type__item',
                currentPayType == item.nickName ? 'cur' : ''
              ]"
              v-for="item in payType"
              :key="item.name"
              @click="changePayType(item.nickName)"
            >
              <img :src="item.img" class="icon" />
              <p class="name">{{ item.name }}</p>
              <img
                src="../assets/is_check.png"
                class="check-img"
                v-show="currentPayType == item.nickName"
              />
              <img
                src="../assets/un_check.png"
                class="check-img"
                v-show="currentPayType != item.nickName"
              />
            </div>
          </div>
        </div>
        <ul class="pay-product" style="margin-bottom: 1.4rem">
          <!-- <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.is_year_order">省</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"
                    :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.is_year_order">省</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.is_year_order">省</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.is_year_order">省</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>
        <div
          class="pay-explain"
          v-if="showPayYearBanner || showSpecialPayTempalte"
        >
          选择充值金额
          <span class="red">（1元=100书币）</span>
        </div>

        <div class="fixed-content">
          <div class="pay-box__fixed">
            <div class="pay-btn" @click="pay">
              {{
                chargePrice ? "¥" + (chargePrice - currentCoupon.price) : ""
              }}立即充值
            </div>
          </div>
        </div>

        <!-- <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.is_year_order">省</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 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,
  Reader,
  Person,
  BookDetail,
  BookCatalog
} from "./namespace.js";
// import product from "../mock/pay.js";
import { MessageBox } from "mint-ui";
import {
  getProductList,
  subscribeByRMB,
  recharge,
  getUserInfo,
  getOrderCoupon,
  newRefreshTokenF,
  newDestoryToken
} from "../api";
import { getKeyByWay, setKeyByWay } from "../util/index.js";

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, //全本提醒true，单本提醒false
      isFirstPay: this.$route.query.first_pay_tip,
      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"),

      xiyue_pay_template: window.options.xiyue_info,
      isMonthOrder: false,
      isXYEntrySelect: false,
      xiyue_pay_btn_text: "立即充值",
      isCouponChecked: false,
      couponList: [],
      availdCouponList: [],
      popupVisible: false,
      payType: [
        { name: "微信", img: require("../assets/wechat.png"), nickName: "wx" }
        /* {
          name: "支付宝",
          img: require("../assets/alipay.png"),
          nickName: "zfb"
        } */
      ],
      currentCoupon: {
        id: "",
        price: 0
      },
      currentPayType: "wx"
    };
  },
  computed: {
    chargePrice() {
      let select_pro = this.product[this.selectedProduct];
      let normal_value = select_pro ? select_pro.price : "0";
      let special_value = normal_value;
      return Number(special_value.replace("元", ""));
    }
  },
  mounted() {
    this.popup();
  },
  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;
          }
        });
      }
    },
    //修改支付方式
    changePayType(name) {
      this.currentPayType = name;
    },
    //选择优惠券
    chooseCoupon(coupon) {
      this.currentCoupon = coupon;
      this.popupVisible = false;
      this.isCouponChecked = true;
    },
    selectProduct(i) {
      this.selectedProduct = i;
      this.isXYEntrySelect = false;
      this.xiyue_pay_btn_text = "立即充值";
      this.getAvaildCoupon(
        Number(this.product[this.selectedProduct].price.replace("元", ""))
      );
    },
    async popup() {
      const from_detail_catalog = this.$route.query.from_detail_catalog; //判断是否是从详情页BookDetail or 目录BookCatalog 跳转到页面  1详情页  2目录  3阅读页
      const last_bid = this.$route.query.last_bid; //如果是从上一页跳转，获取上一页bid和cid，跳转到上一页
      const last_cid = this.$route.query.last_cid;
      const bid = this.$route.query.bid;
      const cid = this.$route.query.cid;
      const send_order_id = this.$route.query.send_order_id;
      const yun = this.$route.query.yun;
      const sequence = this.$route.query.sequence;
      if (this.$route.query.isRecharge) {
        let urlToken = this.$route.query.token;
        let hashUser = this.$route.query.hashuser;
        if (urlToken) {
          //先存本地
          setKeyByWay("token", urlToken);
          setKeyByWay("hashuser", hashUser);
          /*        try {
            const { token, hashuser } = await newrefreshToken({
              hashuser: hashUser,
              token: urlToken
            });
            setKeyByWay("token", token);
            setKeyByWay("hashuser", hashuser);
          } catch (e) {
            this.$Toast(e.data.msg);
          }
          //拿到token 先作废旧token在保存新token;
          try {
            await newDestoryToken({ destroy_token: urlToken });
          } catch (e) {
            this.$Toast(e.data.msg);
          }
          */
        }
        MessageBox({
          title: "支付确认",
          message:
            '1.请在微信内完成支付，如果您已经支付成功，请点击"已完成支付"按钮</br>2.请确保微信版本高于6.0.2',
          confirmButtonText: "已完成支付", //确认按钮的文本
          cancelButtonText: "取消", //取消按钮的文本
          confirmButtonHighlight: true, // 是否将确认按钮的文本加粗显示
          showCancelButton: true, //是否显示取消按钮
          showConfirmButton: true //是否显示确认按钮
        }).then(action => {
          if (action === "confirm") {
            if ((bid && cid) || (last_bid && last_cid)) {
              if (from_detail_catalog === "1") {
                this.$router.replace({
                  // 跳回书籍详情页
                  name: BookDetail.name,
                  query: {
                    id: bid,
                    yun
                  }
                });
              } else if (from_detail_catalog === "2") {
                this.$router.replace({
                  // 跳回目录
                  name: BookCatalog.name,
                  query: {
                    id: bid,
                    sequence,
                    yun
                  }
                });
              } else {
                this.$router.replace({
                  // 跳回上一章
                  name: Reader.name,
                  query: {
                    bid: last_bid,
                    cid: last_cid,
                    send_order_id,
                    yun,
                    token: urlToken,
                    hashuser: hashUser
                  }
                });
              }
            } else {
              this.$router.replace({
                // 跳回个人中心
                name: Person.name,
                yun
              });
            }
          }
        });
      }
      getUserInfo().then(r => {
        this.balance = r.balance;
      });
    },
    pay() {
      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,
        from_detail_catalog: this.$route.query.from_detail_catalog,
        last_bid: this.$route.query.last_bid,
        last_cid: this.$route.query.last_cid,
        sequence: this.$route.query.sequence,
        send_order_id: getKeyByWay("send_order_id"),
        yun: this.$route.query.yun,
        token: getKeyByWay("token"),
        hashuser: getKeyByWay("hashuser")
      });
    },
    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}`;
    },
    //获取当前金额的可用优惠券
    getAvaildCoupon(price) {
      this.currentCoupon = { id: "", price: 0 };
      this.isCouponChecked = false;
      this.availdCouponList = this.couponList.filter(
        item => item.use_condition < price
      );
    },
    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.xiyue_pay_template) {
            this.chooseXiYueEntry();
          }
        });
      });
    });

    //用户优惠券
  }
};
</script>

<style lang="scss" scoped>
.pay-product {
  // margin-bottom: 2.3rem;
}
.mint-msgbox-content {
  .mint-msgbox-message {
    text-align: left;
  }
}
.fixed-content {
  position: relative;
  height: 1.2rem;
  width: 100%;
}

.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: 2.1rem;
    border-radius: 4px;
    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: 10px;
    border: 1px solid #ef5952;
    height: 0.76rem;
    line-height: 0.76rem;
    font-size: 0.28rem;
    font-weight: bold;
    box-shadow: none;
  }
}
</style>
