<template>
	<!-- <page-meta :page-style="pageStyle"></page-meta> -->
	<view class="content">
		
		 <es-nav-bg-black title="御君方会员" right="管理订阅"></es-nav-bg-black>
		
		 <view class="es-fx es-pc es-h-168 es-ml-44 es-mr-44 es-mt-20">
		  	 <image class="topBg" src="../../static/image/course/vipBuy/topbg.png"></image>
			 <view class="topItem es es-fx x-f">
					<image class="es-w-104 es-h-56" style="position: absolute;left:-32rpx;top:0" src="../../static/image/course/xiangyun.png"></image>
					<view class="es-fs-40 es-h-156 es-fw-bold x-c" style="color: #FFDAA3;">
						<view class="es  x-bc " style="margin-left: 90rpx;">
							<image class="es-w-120 es-h-120 es-br-ban" :src="!$isEmpty(user.avatar)?user.avatar:avatar" ></image>
							<view class="y-b es-ml-20">
								<view class="es-fw-bold es-fs-32 es es-ac" :class="user.isVip==1?'vipC':'es-c-white'" >
								     {{ $isEmpty(user.nickName)?"暂无昵称":user.nickName }}
									 <image v-if="user.isVip==1" @tap="loginNavTo('../course/vipBuy')"  class="es-w-40 es-h-40 es-ml-10" src="../../static/image/mine/vip.png"></image>
								</view>
								<view  v-if="user.isVip==1" class="es-fs-22 es-mt-10 es-c-white" style="color: #929A9D">有效期至:{{ $formatDate(user.vipEndDate) }}</view>
								<view v-else class="es-fs-26 es-c-white">开通VIP享<span class="es-fw-bold es-fs-44" style="color: #929A9D;">6</span>大特权</view>
							</view>
						</view>
					</view>
					<image class="es-w-104 es-h-56" style="position: absolute;right:-32rpx;bottom:30rpx" src="../../static/image/course/xiangyun2.png"></image>
			</view>
		 </view>
		 
	    <!-- Vip选项 -->
	    <scroll-view class="payBox es x-f es-ml-44  es-mt-40" scroll-x="true"  >
			<view v-for="(item, index) in dataList" :key="index"  @tap="changePackage(index)" class="payItem es-ac es-pc" :class="pickIndex==index?'ac':''">
				 <image  v-if="pickIndex==index" class="san" src="../../static/image/course/vipBuy/item_san.png"></image>
				 <view class="es-fs-28 es-c-white es-fw-400  x-c" style="margin-top: 54rpx;">{{item.packageName}}</view>
				 <view class="es-c-white es-fs-44 es-fw-500 es-mt-2 x-c-28 price  x-c">￥{{item.sellPrice}}</view>
				 <view class="es-fs-24  es-fw-400  oriPriceBox x-c">
					 <view>原价</view>
					 <view class="oriPrice">￥{{item.price}}
						 <view class="zkline"></view>
					 </view>
				</view>
				 <view class="es es-h-44 es-bc-theme es-c-white es-br-9 es-fs-28 x-c es-fx es-ml-33 es-mr-33 es-mt-10" >限时优惠</view>
			</view>
		 </scroll-view>
	
	    <!-- 支付方式 -->
        <view class="es-mr-44 es-ml-44 es-mt-40">
			<view class="es-c-white es-fs-40 es-fw-700">支付方式</view>
			<view class="es-mt-30 x-bc">
				<view v-for="(item, index) in payTypes" :key="index"  @tap="changePayType(index)"  class="payTypeItem es x-bc " :class="payType==index+1?'pt_ac':''">
						<view class="x-bc es-ml-14">
							<image class="es-w-59 es-h-52" :src="index==0?'../../static/image/course/vipBuy/wx.png':'../../static/image/course/vipBuy/zfb.png'"></image>
							<view class="es-fs-33 es-c-white es-fw-500 es-ml-14">{{item}}</view>
						</view>
						<image v-if="payType==index+1" src="../../static/image/course/vipBuy/check.png" class="es-w-40 es-h-40 es-br-ban es-mr-14"></image>
						<view v-else class="es-w-40 es-h-40 es-br-ban es-mr-14 circle"></view>
				</view>
			</view>
		</view>
		
		<!-- 购买须知 -->
		<view class="es-mr-44 es-ml-44 es-mt-40">
			<view class="es-c-white es-fs-40 es-fw-700">购买须知</view>
			<view class="es-mt-24 es-c-white es-fs-28" style="line-height: 40rpx;">1.有效期内，会员内容都可使用 <br/> 2.御君方会员为虛拟服务，开通后不支持退款<br/> 3.支付成功会员权益自动生效<br/></view>
		     <view class="x-c es-mt-50 es-c es-fs-28 es-fw-500">
				 <view class="es-mr-40" @tap="openH5(0)">《会员服务协议》</view>     
				 <view>《自动续费协议》</view>     
			 </view>
		</view>
		
		<!-- 底部bottom -->
		<view class="es payBot x-bc">
			<view class="es-fs-56 es-fw-bold x-bc es-ml-44" style="color: #FDD8A1;">￥{{checkPrice}} <view class="tehui">（限时优惠）</view></view>
			<view class="es btnPay x-c" @tap="doBuy">立即开通</view>
		</view>
		
		<uni-popup ref="popTip" type="dialog">
			<uni-popup-dialog cancelText="支付失败" confirmText="支付成功" mode="base" content="是否已支付成功?" title="提示" :duration="2000" :before-close="true" @close="confirmTip" @confirm="confirmTip"></uni-popup-dialog>
		</uni-popup>
		
		
    </view>
</template>

<script>
	import {getUserInfo} from '@/api/user'
	import { getPackageList,createVipOrder,vipZfbPayment,getVipOrderById } from '@/api/course'
	export default {
		data() {
			return {
				dataList:[],
				pickIndex:0,
				packageItem:{sellPrice:0,price:0},
				checkPrice:0.0,
				payTypes:["微信支付","支付宝支付"],
				payType:1,//微信支付:1  支付宝支付:2
				user:{
					avatar:"/static/images/detault_head.png",
					userName:"",
					phone:"",
					nickName:"",
				},
				order:null,
				showPayTips:false,
			}
		},
	  //  onBackPress() {
			// // 手动调用返回方法
			// uni.navigateBack({ delta: 1});
			// // 阻止默认的返回行为
			// return true;
	  //  },
		onLoad(options) {
			this.initData();
		},
		onShow() {
			if(this.showPayTips){
				this.$refs.popTip.open();
				this.showPayTips=false;
			}
		},
		onUnload() {
		    const subNVue = uni.getSubNVueById('privilege');
			if(subNVue){
				setTimeout(e => {
					 subNVue.show();	
				}, 200);
			}
		},
		methods: {
			initData(){
				this.getPackageList();
				this.getUserInfo();
			},
			getPackageList(){
				getPackageList().then(res => {
						if(res.code==200){
							this.dataList=res.data;
							this.packageItem=this.dataList[0];
							this.checkPrice=this.packageItem.sellPrice;
						}
					},
					rej => {}
				);
			},
			doBuy(){
				this.createVipOrder();
			},
			createVipOrder(){
			   	if(!this.$isLogin()){
			   		this.$showLoginPage();
			   		return;
			   	}
			   	uni.showLoading({title:""});
				let params={"packageId":this.packageItem.packageId,"payType":this.payType};
			   	createVipOrder(params).then(res => {
					    console.log("qxj createVipOrder res:"+JSON.stringify(res));
			   			uni.hideLoading();
			   			if(res.code==200){
							this.order=res.order;
			   				if(this.payType==1){  //微信支付
			   					this.doWxPay();
			   				}else{   //支付宝
			   					this.doAlipay();
			   				}
			   			}else{
			   				uni.showToast({title: res.msg,icon: 'none'});
			   			}
			   		},
			   		rej => {}
			   	);
			},
			changePackage(index){
				this.pickIndex=index;
				this.packageItem=this.dataList[index];
				this.checkPrice=this.packageItem.sellPrice;
			},
			changePayType(index){
				this.payType=index+1;
			},
			getUserInfo(){
				let that=this;
				getUserInfo().then(res => {
						if(res.code==200){
							if(res.user!=null){
								uni.setStorageSync('userInfo',JSON.stringify(res.user));
								this.user=res.user;
							}
							else{
								uni.showToast({
									icon:'none',
									title: res.msg,
								});
							}
						}
					},
					rej => {}
				);
			},		
			doAlipay(){
				var data = {orderId:this.order.orderId};
			    let that=this;
				// #ifdef APP-PLUS
				const tzCashier=uni.requireNativePlugin("TZBank-Cashier");
				uni.showLoading();
				vipZfbPayment(data).then(res => {
						uni.hideLoading();
						if(res.code==200){
							if(res.type=="tz"){
								//console.log("qxj res:"+JSON.stringify(res));
								//console.log("qxj orderFlowNo:"+res.data.body.orderFlowNo+" businessCstNo:"+res.data.body.orderNo+" platMerCstNo:"+res.data.body.platMerCstNo);
								const match = res.data.body.url.match(/[\?&]businessCstNo=([^&]+)/);
								const businessCstNo = match ? match[1] : null;
						        console.log("qxj tzCashier:"+tzCashier+" businessCstNo:"+businessCstNo);
								tzCashier.pay({
									env:0,
									wxMiniProgramType:0,
									wxAppId:'wx703c4bd07bbd1695',
									wxUniversalLink:"https://yjf.runtzh.com/",
									orderFlowNo:res.data.body.orderFlowNo,
									businessCstNo:businessCstNo,
									platMerCstNo:res.data.body.platMerCstNo
								},(res)=>{
									    // uni.showToast({
									    // 	title:'收银台回调:'+JSON.stringify(res),
									    // 	icon:'none'
									    // })
										uni.$emit('closePrivilege', {});
										that.showPayTips=true;
								  });
							}
							else if(res.type=='hf'){
								if (uni.getSystemInfoSync().platform == 'android') {
									var alipayScheme ='alipays://platformapi/startApp?&saId=10000007&qrcode=' + res.data.qr_code;
								}else{
								    var alipayScheme ='alipay://platformapi/startApp?&saId=10000007&qrcode=' + res.data.qr_code;
								}
								// 在uni-app中使用plus.runtime.openURL打开URL
								plus.runtime.openURL(alipayScheme, function(error) {
								  
								});
								uni.$emit('closePrivilege', {});
								that.showPayTips=true;
							}
						}
						else{
							uni.showToast({title:res.msg,icon:'none'})
						}
						
					},
					rej => {}
				);
				// #endif	
			},
			doWxPay(){
				var that=this;
				plus.share.getServices(function(res){
				    var sweixin = null;  
				    for(var i=0;i<res.length;i++){  
				        var t = res[i];  
				        if(t.id == 'weixin'){  
				            sweixin = t;  
				        }  
				    }  
					if(sweixin){
						let path='/pages_order/userVipOrderPayment?orderId='+that.order.orderId+"&payMethod=app";
						console.log('调起小程序 path:'+path);
						//唤起微信跳转小程序
						sweixin.launchMiniProgram({
							id:"gh_7a6a32e5ef61",
							path:'/pages_order/userVipOrderPayment?orderId='+that.order.orderId+"&payMethod=app",
							type:0  // 微信小程序版本类型，可取值： 0-正式版； 1-测试版； 2-体验版。 默认值为0。
						},function(){
							console.log("微信唤起成功");
							return true;
						},function(e){
							console.log("微信唤起失败",e);
							uni.showToast({
								title:'微信唤起失败，请检查是否有微信应用',
								icon:'none'
							});
							return false;
						});
						that.showPayTips=true;
						uni.$emit('closePrivilege', {});
					}else{
						uni.showToast({
							title:'微信唤起失败，请检查是否有微信应用',
							icon:'none',
							duration:3000
						});
						return false;
					}
				      
				},function(res){  
				    console.log(JSON.stringify(res));  
				});
			},		
			getVipOrderById(){
				getVipOrderById(this.order.orderId).then(res => {
					    this.$refs.popTip.close();
						if(res.code==200){
							if(res.data.status==1 || res.data.payTime!=null){
								// #ifdef APP-PLUS
								if(plus.runtime.channel=="baidu"){  //获取渠道标识
								     let bdCmdType=uni.getStorageSync("bdCmdType");
								     if(bdCmdType!=null && parseInt(bdCmdType)<=2){
								         //this.$registerIdCode("orders",2,res.data.payMoney.toString()); //已下单
								     }
							    }
								//  #endif
								this.getUserInfo();
								uni.showToast({title:"支付成功",icon:'success'});
							}else{
								uni.showToast({title:"支付失败",icon:'error'});
							}
						}
						setTimeout(()=>{
							this.navBack();
						},2000);
					
					},
					rej => {}
				);
			},
			navBack() {
				uni.navigateBack({
					animationType: 'pop-out',
					animationDuration: 200
				});
			},
			openH5(index){
				uni.setStorageSync('url',index==0?"https://userapp.his.cdwjyyh.com/web/userAgreement":"https://userapp.his.cdwjyyh.com/web/privacyPolicy");
				uni.navigateTo({
					url:"/pages/index/h5"
				})
			},
			closeTip(){
				this.$refs.popTip.close();
				this.getVipOrderById();
			},
			confirmTip() {
				uni.showLoading({title:"请稍侯...",mask:true});
				setTimeout(()=>{
					uni.hideLoading();
					this.getVipOrderById();
					uni.$emit('refreshUser', {});
				},2000);
				// setTimeout(()=>{
				// 	this.navBack();
				// },2000);
			},
		}
	}
</script>

<style scoped>
	
	page {
		background-color: #1B1F22;
		
	}
   .topBg{
	   position: absolute;
	   width:calc(100% - 88rpx) ;
	   height:168rpx;
	   z-index: 5;
   }
   
   .topItem{
	   width: 100%;
	   height: 100%;
	   z-index: 10;
   }
   
   .payBox{
	   display:flex;
	   white-space:nowrap;
	   overflow-x: scroll;
   }
   
   .payItem{
	   position: relative;
	   display: inline-block;
	   width: 209rpx;
	   height: 286rpx;
	   background-image: url(../../static/image/course/vipBuy/item.png);
	   background-repeat: no-repeat;
	   background-size: cover;
	   background-position: center;
	   /* background-attachment: fixed; */
	   margin-right: 12rpx;
   }
  
   .ac{
	    background-image: url(../../static/image/course/vipBuy/item_ac.png);
	   .price{
		   color: #C4AA83;
	   }
   }
   
   .san{
	   position: absolute;
	   left: calc(50% - 25rpx);
	   top:-10rpx;
	   width: 50rpx;
	   height: 42rpx;
   }
   
   .price{
   	   color: #fff;
   }
   
   .oriPriceBox{
	   color: #797A7D;
	   .oriPrice{
	   	   position: relative;
	   }
	   .zkline{
		   position: absolute;
		   left: 0;
		   top:18rpx;
		   height: 1px;
		   width: 100%;
		   background-color:#797A7D ;
	   }
   }
   
   .payTypeItem{
	   background-color:#1B1F22;
	   border:1px solid #fff;
	   border-radius: 10rpx;
	   width: calc(50% - 15rpx);
	   height: 94rpx;
   }
   
   .circle{
	   border:1px solid #fff;
   }
   
   .pt_ac{
	    border:1px solid #FDD8A1;
   }
   
   .payBot{
	   position: fixed;
	   bottom: 0;
	   left: 0;
	   right: 0;
	   width: 100%;
	   height: 170rpx;
   }
   
   .tehui{
	   color: #8B8F92;
	   font-size: 26rpx;
	   font-weight: 400;
   }
   
   .btnPay{
	   width: 246rpx;
	   height: 84rpx;
	   background: linear-gradient(90deg, #FFE0B2, #F8BA8B);
	   border-radius: 41rpx;
	   margin-right: 44rpx;
	   font-weight: 700;
	   font-size: 40rpx;
	   color: #1B1F22;
	   line-height: 61rpx;
   }
   
   .vipC{
	   color: #FDD8A1;
   }
   
   
   
   
</style>
