<template>
<view id="recharge-index">

    <view class="contents">
		<!-- 这里不知道为什么，title的样式没有用，我先用行内样式解决 -->
        <view class="mx-1px-bottom title" style="font-size: 13px;background: #FFFFFF;font-weight: 600;">
            <!-- <i class="iconfont icon-recharge"></i> -->
            <span>
                <block v-if="initInfo && initInfo.vip_plan_status">
                    会员账号
                </block>
                <block v-else>
                    会员余额充值
                </block>
            </span>
        </view>
        <view class="item mx-1px-bottom">
            <view class="left">
                会员名：
            </view>
            <view class="right">
                {{user.nick_name}}
            </view>
        </view>
        <view class="item mx-1px-bottom">
            <view class="left">
                手机号：
            </view>
            <view class="right">
                {{user.mobile}}
            </view>
        </view>
        <view class="item mx-1px-bottom">
            <view class="left">
                当前余额：
            </view>
            <view class="right">
                {{num/100}}
            </view>
        </view>
        <view class="tips">
            <block v-if="initInfo && !initInfo.vip_plan_status">
                * 会员充值概不退款
            </block>
        </view>
        <view class="money-box">
            <view class="money-item" v-for="(item, index) in schemes" :key="index" :data-amount="item.amount" :data-id="item.id" :data-payment="item.payment_amount" @tap="submitPay">
                <view class="order">
                    <view class="old-Price" v-if="initInfo && initInfo.vip_plan_status">
                        {{item.title}}
                    </view>
                    <view class="old-Price" v-else>
                        {{item.amount/100}} 元
                    </view>
                    <view class="price">
                        售价：{{item.payment_amount/100}}元
                    </view>
                </view>
            </view>
        </view>
        <view class="tips" v-if="initInfo && initInfo.vip_plan_status">
            <view>
                * VIP享全场购物95折，299元享全场购物88折
            </view>
            <view>
                * 多次购买会员余额累积到账，VIP等级以最高等级权益为准
            </view>
            <view>
                * 会员账户余额可在平台购物时无限制使用
            </view>
            <view>
                * 会员账户余额不提现、不退款
            </view>
        </view>
    </view>

</view>


</template>
<script>
const app = getApp();
import {pageLogin, getUrl,config,is} from '@/common/js/utils.js';

export default {
  data() {
    return {
      num: '',
      schemes: [],
      user: "",
      token: "",
      channel: 'wx_lite',
      initInfo: '',
	  order_no:''
    };
  },

  onLoad(e) {
    pageLogin(getUrl(), token => {
     this.token =  token;
      this.querySchemes();
      this.queryUserInfo(token);
      this.queryUserSum(token);
    });
  },
  methods: { 
    queryUserSum(token) {
      // 获取用户余额
      this.$http.get({
        api: 'api/users/balance/sum',
        header: {
          Authorization: token
        }
      }).then(res => {
        if (res.statusCode == 200) {
          this.setData({
            num: res.data.data.sum
          });
        } else {
          wx.showModal({
            title: '提示',
            content: '数据请求失败',
            success: res => {}
          });
        }
      });
    },

    getOpenid() {
      return new Promise((resolve, reject) => {
        wx.login({
          success: res => {
            this.$http.get({
              api: `api/oauth/miniprogram/openid`,
              data: {
                code: res.code
              }
            }).then(res => {
              res = res.data;
              resolve(res.data.openid);
            }).catch(() => {
              reject('获取openid失败');
            });
          },
          fail: () => {
            wx.showModal({
              content: "接口请求失败"
            });
          }
        });
      });
    },

    querySchemes() {
      this.$http.get({
        api: 'api/users/balance/schemes'
      }).then(res => {
        if (res.statusCode == 200) {
          this.setData({
            schemes: res.data.data
          }); // this.schemes=res.data.data;
        } else {
          wx.showModal({
            title: '提示',
            content: '数据请求失败',
            success: res => {}
          });
        }
      });
    },

    queryUserInfo(token) {
      this.$http.get({
        api: 'api/me',
        header: {
          Authorization: token
        }
      }).then(res => {
        if (res.statusCode == 200) {
          this.setData({
            user: res.data.data
          });
        } else {
          wx.showModal({
            title: '提示',
            content: '数据请求失败',
            success: res => {}
          });
        }
      });
    },

    urlPath(url) {
      // console.log()
      let data = {};
      let query = url.slice(url.indexOf("?") + 1);
      query = query.split("&");
      query.forEach(val => {
        data[val.slice(0, val.indexOf("="))] = val.slice(val.indexOf("=") + 1);
      }); // console.log(query);

      return data;
    },

	// #ifdef MP-WEIXIN
	submitPay(e) {
	  wx.showLoading();
	  this.getOpenid().then(res => {
	    var oauth = this.$cookieStorage.get('user_token');
	    var data = {
	      amount: e.currentTarget.dataset.amount,
	      pay_amount: e.currentTarget.dataset.payment,
	      channel: this.channel,
	      recharge_rule_id: e.currentTarget.dataset.id,
		  extra:{
			  openid: res,
		  }
	    };
	    this.$http.post({
	      api: `api/users/balance/charge`,
	      data: data,
	      header: {
	        Authorization: oauth
	      }
	    }).then(res => {
	      res = res.data;
	
	      if (res.status) {
	        if (res.data.name == 'pingxx') {
	          wx.showModal({
	            content: '不支持pxx支付',
	            showCancel: false
	          });
	        } else {
	          this.newcharge(true, res.data.charge);
	        }
	      } else {
	        this.newcharge(false, res.message);
	      }
	    }).catch(rej => {
	      this.newcharge(false);
	    });
		 wx.hideLoading();
	  }).catch(() => {
	     wx.hideLoading();
	    wx.showModal({
	      content: '支付失败',
	      showCancel: false
	    });
	  });
	},
	// #endif

    
	// #ifdef H5
	submitPay(e){
		var oauth = this.$cookieStorage.get('user_token');
		 var openid = this.$cookieStorage.get('openid');
		  var origin = window.location.origin;
		 var url = origin+'/pages/recharge/success/success?order_no='+this.order_no;
		 var fail_url = origin+'/pages/user/personal/personal';
		var data = {
		  amount: e.currentTarget.dataset.amount,
		  pay_amount: e.currentTarget.dataset.payment,
		  channel: 'wx_pub',
		  recharge_rule_id: e.currentTarget.dataset.id,
		  extra:{
			  openid:openid,
			  successUrl:url,
			  failUrl:fail_url
		  }
		};
		this.$http.post({
		  api: `api/users/balance/charge`,
		  data: data,
		  header: {
		    Authorization: oauth
		  }
		}).then(res => {
				res = res.data;
				if (res.status) {
				 if(res.data.redirect_url){
				 	window.location.href = res.data.redirect_url;
				 }
				} else {
				 wx.showModal({
				   content: res.message || '支付失败',
				   showCancel: false
				 });
				}

		   
		}).catch(() => {
			this.loading = false;
			wx.showModal({
			  content: '支付失败',
			  showCancel: false
			});
		});
		
	},
	// #endif
	 // #ifdef APP-PLUS
	 submitPay(e) {
	   wx.showLoading();
	     var oauth = this.$cookieStorage.get('user_token');
	     var data = {
	       amount: e.currentTarget.dataset.amount,
	       pay_amount: e.currentTarget.dataset.payment,
	       channel:'wx_app',
	       recharge_rule_id: e.currentTarget.dataset.id,
	     };
	     this.$http.post({
	       api: `api/users/balance/charge`,
	       data: data,
	       header: {
	         Authorization: oauth
	       }
	     }).then(res => {
	       res = res.data;
	       if (res.status) {
			   this.order_no = res.data.order_no;
	           this.appPayment(true,JSON.stringify(res.data.credential));
	       } else {
	         this.appPayment(false, res.message);
	       }
	     }).catch(rej => {
	       this.appPayment(false);
	     });
	 	 wx.hideLoading();
	 },
	 // #endif
	// app支付
	appPayment(success,orderInfo) {
		var that = this;
	  if (success) {
		  // 获取服务供应商
		  uni.getProvider({
		  	service:'payment',
		  	success:ret=>{
				uni.requestPayment({
				   provider:'wxpay',
				   orderInfo:orderInfo,
				   success: res => {
				     if (res.errMsg == 'requestPayment:ok') {
				       this.loading =  false;
				      wx.redirectTo({
				         url: `/pages/recharge/success/success?order_no=${this.order_no}`
				       });
				     } else {
				       wx.showModal({
				         content: '调用支付失败！',
				         showCancel: false
				       });
				     }
				   },
				   fail: err => {
				     this.setData({
				       loading: false
				     });
					console.log('fail:' + JSON.stringify(err));
				     if (err.errMsg == 'requestPayment:fail:[payment微信:-2]User canceled') {
				      wx.switchTab({
				        url: `/pages/user/personal/personal`
				      });
				     } else {
				       wx.showModal({
				         content: '调用支付失败！',
				         showCancel: false
				       });
				     }
				   }
				 });
		  		
		  	}
		  	
		  })
	   
	  } else {
	    this.setData({
	      loading: false
	    });
	    wx.showModal({
	      content: charge || '请求支付失败，请重试！',
	      showCancel: false
	    });
	  }
	},

    // 新版支付
    newcharge(success, charge) {
      if (success) {
        var that = this;

        if (charge.pay_scene == 'test') {
          wx.showModal({
            content: '不支持模拟支付',
            showCancel: false
          });
          this.setData({
            loading: false
          });
        } else {
          wx.requestPayment({
            "timeStamp": charge.credential.wechat.timeStamp,
            "nonceStr": charge.credential.wechat.nonceStr,
            "package": charge.credential.wechat.package,
            "signType": charge.credential.wechat.signType,
            "paySign": charge.credential.wechat.paySign,
            success: res => {
              if (res.errMsg == 'requestPayment:ok') {
                this.loading =  false
                wx.redirectTo({
                  url: `/pages/recharge/success/success?order_no=${charge.order_no}`
                });
              } else {
                wx.showModal({
                  content: '调用支付失败！',
                  showCancel: false
                });
              }
            },
            fail: err => {
              wx.hideLoading();

              if (err.errMsg == 'requestPayment:fail cancel') {
                wx.switchTab({
                  url: `/pages/user/personal/personal`
                });
              } else {
                wx.showModal({
                  content: '调用支付失败！',
                  showCancel: false
                });
              }
            }
          });
        }
      } else {
        wx.hideLoading();
        wx.showModal({
          content: charge || '请求支付失败，请重试！',
          showCancel: false
        });
      }
    },

    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  },
  computed: {},
  watch: {}
};
</script>
<style>
#recharge-index .contents{height:100%;overflow:auto;box-sizing:border-box}#recharge-index .contents .title{display:flex;align-items:center;font-size:14px;padding:10px 15px}#recharge-index .contents .title i{font-size:20px;color:#000;margin-right:10px}#recharge-index .contents .item{color:#666;background:#FFF;padding:10px 15px;display:flex;align-items:center;font-size:12px}#recharge-index .contents .item .left{flex:1;font-size:14px}#recharge-index .contents .tips{padding:15px 10px;font-size:14px;color:#b2b2b2}#recharge-index .contents .money-box{font-size:0;padding:0 7px}#recharge-index .contents .money-box .money-item{display:inline-block;text-align:center;font-size:14px;width:33%;box-sizing:border-box;margin-bottom:15px;padding:0 7px}#recharge-index .contents .money-box .money-item .order{border:1px solid #1AAD19;border-radius:6px;padding:5px 6px;color:#1AAD19}#recharge-index .contents .money-box .money-item .order .price{min-height:20px;font-size:10px;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1;overflow:hidden;text-overflow:ellipsis}
</style>