<template>

  <BaseContainer class="gold-coin">
    <NavBar title="充值" />
    <view class="header">
      <view class="cont">
        <view class="text">
          我的余额
          <view class="num">{{ userInfo.now_money }}</view>
        </view>
      </view>
    </view>
    <view class="main" v-if="updateOptions.length">
      <!-- 数量选择 -->
      <view class="wrap select">
        <view class="head">数量选择</view>
        <view class="cont">
          <view class="list">
            <view v-for="(item, index) in updateOptions" :class="{active :coinChecked===index}"
              @click="handleToggleOptions(index)" :key="index" class="item pos">
              <view class="item-cont" :class="{ active: coinChecked == item }">
                <view class="text">
                  {{ item.money }}元
                </view>
              </view>
              <view class="abs full" :data-idx="index"></view>
            </view>
          </view>
          <view :class="{ checked: coinChecked === options.length }" class="input">
            <view class="cell flex flex-center-x">
              <input v-model.number="moneyInput" :class="{ on: !moneyInput }" type="number" @focus="inputFocus"
                @blur="inputBlur" />
              元
            </view>
          </view>
        </view>
      </view>
      <view class="handle">
        <view class="btn flex flex-center" @click="callPay">立即充值</view>
      </view>
    </view>

    <!-- 支付弹窗 -->
    <PayDialog :open.sync="payDialogOpen" :money="moneyPay" :now_money="now_money" :special_id="moneyPay"
      :pay_type_num="payTypeNum" :is-Wechat="isWechat" :is-alipay="is_alipay" :is-balance="is_yue" :wxpay-h5="wxpayH5"
      @change="changeVal" />
  </BaseContainer>
</template>

<script>
  import { getRechargeInitData, aliPayApp, aliPayWap } from "@/api/special";
import { getUserInfo } from "@/api/auth";
  import PayDialog from "@/components/PayDialog/index.vue";

  export default {
    components: {
      PayDialog,
    },
    data() {
      return {
        // 换算率
        rate: 10,
        // 金币选项
        options: [],
        // 选中金额
        coinChecked: 0,
        // 输入金额
        moneyInput: 0,
        // 支付方式选中项
        payChecked: 0,
        // 是否显示支付弹窗
        payDialogOpen: false,
        // 登录弹窗隐藏
        loginShow: false,
        loginUrl: "",
        siteName: "",
        payTypeNum: 30, //金币充值
        is_alipay: false, //支付宝是否开启
        is_yue: false, //余额是否开启
        now_money: 0, //余额
        urlStr: "",
        from: "my",
        streamName: "",
        wxpayH5: false,
        site_name: "",
        isOpenWeixing: false,
				userInfo: {},
      };
    },
    computed: {
      updateOptions() {
        var that = this,
          Obj = {},
          Arr = [];
        that.options.map(function (value) {
          Obj.coin = value;
          Obj.money = (value / that.rate).toFixed(2);
          Arr.push(Obj);
          Obj = {};
        });
        return Arr;
      },
      // 支付金额
      moneyPay() {
        return this.coinChecked == -1
          ? this.moneyInput
          : this.options[this.coinChecked] / this.rate;
      },
      // 是否微信
      isWechat() {
        return false;
        // var agent = navigator.userAgent.toLowerCase();
        // return agent.match(/MicroMessenger/i) == "micromessenger";
      },
    },
    onShow() {
      if (this.isOpenWeixing && this.orderId) {
        this.$util.wxh5PayIsSuccess(this.orderId, 3, this)
        this.isOpenWeixing = false
      }
    },
    onLoad({ from }) {
      if (from) this.from = from;
      this.getData();
			this.getUserInfo();
    },
    methods: {
      handleToggleOptions(e) {
        this.coinChecked = e;
      },
			getUserInfo() {
				getUserInfo().then(({ data }) => {
					this.userInfo = data;
				});
			},
      getData() {
        getRechargeInitData().then(({ data }) => {
          const {
            recharge_price_list,
            gold_info,
            user_info,
            is_yue,
            wxpayH5,
            is_alipay,
            callback_url,
            site_name,
          } = data;
          Object.assign(this, {
            now_money: Number(user_info.now_money),
            is_alipay: is_alipay == 1,
            is_yue: false,
            wxpayH5: wxpayH5 == 1,
            site_name,
            callback_url,
            rate: gold_info.gold_rate ? gold_info.gold_rate : 10,
            options: recharge_price_list,
          });
        });
      },
      getUrlStr(name) {
        let pattern = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"),
          array = document.location.search.slice(1).match(pattern);
        if (array) {
          return decodeURI(array[2]);
        }
        return null;
      },
      inputFocus() {
        this.coinChecked = -1;
        if (this.moneyInput) {
          this.moneyInput = "";
        }
      },
      inputBlur() {
        if (!this.moneyInput) {
          this.moneyInput = 0;
          this.coinChecked = 0;
        }
      },
      // 支付弹窗调起
      callPay() {
        if (this.coinChecked == -1 && this.moneyInput <= 0)
          return this.$util.showMsg("请输入正确值");

        this.$util.checkLogin(() => {
          this.payDialogOpen = true;
        }, true);
      },
      closeLogin: function (params) {
        if (typeof params !== "object") {
          return;
        }
        switch (params.action) {
          case "loginClose":
            this.loginShow = false;
            break;
          case "logComplete":
            this.loginShow = false;
            this.payDialogOpen = true;
            break;
        }
      },
      logComplete: function (data) {
        var that = this;
        that.loginShow = false;
        if (!data) {
          return;
        }
        if (!data.isfollow && is_official_account_switch) {
          that.codeUrl = data.url;
          that.isfollow = true;
        } else {
          window.location.reload();
        }
      },
      //所有插件回调处理事件
      changeVal: function (opt) {
        if (typeof opt != "object") opt = {};
        var action = opt.action || "";
        var value = opt.value || "";
        this[action] && this[action](value);
      },
      pay_order: function (data) {
        this.orderId = data.data.result.order_id || "";
				console.log(JSON.stringify(data));
        switch (data.data.status) {
          case "PAY_ERROR":
          case "ORDER_EXIST":
          case "ORDER_ERROR":
            this.extendOrder(data.msg);
            break;
          case "WECHAT_PAY":
            this.wechatPay(data.data.result.jsConfig);
            // this.$util.weixinAppPay(data.data.result.jsConfig,this);
            break;
          case "WECHAT_H5_PAY":
            this.payDialogOpen = false;
            this.$util.wechatH5Pay(data.data.result.jsConfig, this);
            break;
          case "WECHAT_ROUTINE_PAY":
            this.$util.wechatRoutinePay(data.data.result.jsConfig, this);
            break;
          case "SUCCESS":
            this.successOrder(data.data);
            break;
          case "ZHIFUBAO_PAY":
            this.aliPay(data.data.result, "recharge")
            break;
          case 'TOUTIAO_PAY':
            this.$util.toutiaoPay(data.data.result.jsConfig, this);
            break;
          case 'KUAISHOU_PAY':
            this.$util.kuaishouPay(data.data.result.jsConfig, this);
            break
        }
      },
      aliPay(msn, type) {
        this.$util.aliPay(msn, type, this)
      },
      wechatPay: function (config) {
        this.$util.weixinpay(config, this)
      },
      successOrder: function (data) {
        var that = this,
          msg,
          result;
        if (data) {
          msg = data.msg;
          result = data.result;
          that.payDialogOpen = false;
          this.$util.showMsg("支付成功");
          uni.showToast({
            title: '支付成功',
            duration: 2000,
            success: function () {
              if (that.from == "live") {
                setTimeout(() => {
                  uni.navigateBack({
                    delta: 1
                  });
                }, 1500);
              } else {
                that.getUserInfo();
              }
            }
          });

        } else {
          this.$util.refreshPage(this.$mp.page.route + `?from=${this.from}`)

        }
      },
      extendOrder: function (msg) {
        if (typeof msg === "object") {
          if (msg.errMsg === "chooseWXPay:cancel") {
            msg = "微信支付取消";
          } else {
            msg = "支付失败";
          }
        } else {
          msg = "支付失败";
        }
        this.$util.showMsg(msg);
        this.$util.refreshPage(this.$mp.page.route)
      },
    },
  };
</script>

<style scoped lang="scss">
  .gold-coin .header {
    height: 350rpx;
    background: #2c8eff url(@/static/images/coin-bg.png) center/cover no-repeat;
  }

  .gold-coin .header .cont {
    position: relative;
    height: 263rpx;
    line-height: 263rpx;
    text-align: center;
  }

  .gold-coin .header .text {
    display: inline-block;
    max-width: 100%;
    vertical-align: middle;
    overflow: hidden;
    font-size: 26rpx;
    line-height: 1.5;
    color: #ffffff;
  }

  .gold-coin .header .num {
    margin-top: 30rpx;
    font-weight: bold;
    font-size: 78rpx;
  }

  .gold-coin .header .link {
    position: absolute;
    top: 74rpx;
    right: 0;
    height: 54rpx;
    padding-right: 32rpx;
    padding-left: 47rpx;
    border-top-left-radius: 27rpx;
    border-bottom-left-radius: 27rpx;
    background-color: #feb720;
    font-size: 30rpx;
    line-height: 54rpx;
    color: #ffffff;
  }

  .gold-coin .main {
    min-height: 87rpx;
    border-top-left-radius: 24rpx;
    border-top-right-radius: 24rpx;
    margin-top: -87rpx;
    background-color: #ffffff;
  }

  .gold-coin .main .wrap {
    padding-right: 30rpx;
    padding-left: 30rpx;
  }

  .gold-coin .main .wrap .wrap {
    margin-top: 10rpx;
  }

  .gold-coin .wrap .head {
    height: 108rpx;
    font-size: 30rpx;
    line-height: 108rpx;
    color: #282828;
  }

  .gold-coin .select .list::after {
    content: " ";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
  }

  .gold-coin .select .list .item {
    float: left;
    display: block;
    margin-top: 21rpx;
    margin-right: 21rpx;
  }

  .gold-coin .select .list .item:nth-child(-n + 3) {
    margin-top: 0;
  }

  .gold-coin .select .list .item:nth-child(3n + 3) {
    margin-right: 0;
  }

  .gold-coin .select .list .item-cont {
    width: 216rpx;
    height: 120rpx;
    border: 1px solid #eee;
    border-radius: 12rpx;
    line-height: 120rpx;
    text-align: center;
  }

  .gold-coin .select .list .active .item-cont {
    border-color: #539dfd;
  }

  .gold-coin .select .list .text {
    display: inline-block;
    vertical-align: middle;
    font-size: 28rpx;
    line-height: 1;
    color: #999999;
  }

  .gold-coin .select .list .num {
    padding-right: 46rpx;
    margin-bottom: 16rpx;
    background: url(@/static/icon/coin.png) right center/36rpx 36rpx no-repeat;
    font-weight: bold;
    font-size: 36rpx;
    color: #282828;
  }

  .gold-coin .input {
    display: block;
    height: 86rpx;
    border: 1px solid #eee;
    border-radius: 12rpx;
    margin-top: 21rpx;
    line-height: 86rpx;
  }

  .gold-coin .checked {
    border-color: #539dfd;
  }

  .gold-coin .input::after {
    content: " ";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
  }

  .gold-coin .input .cell {
    float: left;
    width: 50%;
  }

  .gold-coin .input .cell:first-child {
    padding-right: 61rpx;
    padding-left: 28rpx;
    margin-right: -16rpx;
    // background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB8AAAAfCAYAAAAfrhY5AAAAz0lEQVRYR+2TMQ6CIQxGC5zBwSt4Ci+hqy6kk4MH0cHEQK+gqyfxQjWaPyQ6aIslLDCX7315UAcdj+vIhgHvYn9o/1s7Ec2997MY410aZqY953xyzu0A4IqIa0kBMzgRHQFgP0FFBczgTygRXQBgJS1gCtcWMIdrCjSBSws0g0sKNIX/KlDgOeez934h2c+aGWZefm5BgRMR14TW3EHEF7fAU0rbEMKmJkxzh5lviHh4g2sCrGabf7hvRQfc6hlVOUO7SpfV8NBuZVKV01X7A0aXQCDv/YToAAAAAElFTkSuQmCC") right center/.31rem no-repeat;
    font-size: 30rpx;
    color: #999999;
  }

  .gold-coin .input input {
    flex: 1;
    min-width: 0;
    color: #282828;
  }

  .gold-coin .input input.on {
    color: #999999;
  }

  .gold-coin .input input::placeholder {
    color: #999999;
  }

  .gold-coin .method .item {
    display: block;
  }

  .gold-coin .method .item .item {
    margin-top: 19rpx;
  }

  .gold-coin .method input {
    display: none;
  }

  .gold-coin .method .item-cont {
    border: 1px solid #eee;
    border-radius: 6rpx;
    font-size: 28rpx;
    color: #282828;
  }

  .gold-coin .method input:checked+.item-cont {
    border-color: #539dfd;
    color: #539dfd;
  }

  .gold-coin .method .item-cont::after {
    content: " ";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
  }

  .gold-coin .method .cell {
    float: left;
    width: 50%;
    height: 86rpx;
    line-height: 86rpx;
  }

  .gold-coin .method .cell:first-child {
    padding-left: 150rpx;
    background: url(@/static/icon/wxpay.png) 86rpx center/44rpx no-repeat;
  }

  .gold-coin .method .item:last-child .cell:first-child {
    background-image: url(@/static/icon/alipay.png);
  }

  .gold-coin .method .cell:last-child {
    position: relative;
    font-size: 26rpx;
    text-align: center;
    color: #aaa;
  }

  .gold-coin .method .cell:last-child::before {
    content: " ";
    position: absolute;
    top: 50%;
    left: 0;
    width: 1px;
    height: 30rpx;
    background-color: #eee;
    margin-top: -15rpx;
  }

  .gold-coin .handle {
    padding-right: 41rpx;
    padding-left: 41rpx;
    margin-top: 74rpx;
  }

  .gold-coin .handle .btn {
    width: 100%;
    height: 86rpx;
    border-radius: 43rpx;
    background-color: #539dfd;
    font-size: 30rpx;
    color: #ffffff;
  }
</style>