<template>
	<view>
		<!-- 公共组件-每个页面必须引入 -->
		<public-module></public-module>
		<z-nav-bar title="充值"></z-nav-bar>
		<view class="cha_jine">
			<view class="cj_title">充值金额</view>
			<view class="cj_xiang">
				<view v-for="(item, index) in cjList" @click="chosPric(item)"
					:class="stepsCj.priceTypeId == item.priceTypeId?'Tab_cj cj_price':'cj_price'">
					<view class="pr_jg">￥{{item.realMoney}}</view>
					<view class="pr_yl">{{item.money}} 疯币</view>
					<view class="pr_lj">限时特惠</view>
				</view>
				<br clear="both">
			</view>
		</view>
		<view class="cha_fangsh">
			<view class="cf_title">支付方式</view>

			<view class="cf_radio">
				<u-radio-group v-model="payType">
					<!-- #ifdef MP-WEIXIN -->
					<view style="width: 100%;" >
						<view v-for="(item, index) in paylist" @click="choseType(item.id)"
							:class="payType == item.id?'Tab_xf cf_xuanx':'cf_xuanx'">
							<image :src="item.img"></image>
							{{item.title}}
							<u-radio v-if="isAndroid" :key="index" activeColor="#fe6e09" :name='item.id'
								style="float: right;margin-top: 5rpx;"></u-radio>

						</view>
					</view>
					<!--  #endif -->
					<!-- #ifdef APP-IOS -->
					<view style="width: 100%;" >
						<view v-for="(item, index) in iosPaylist" @click="choseType(item.id)"
							:class="payType == item.id?'Tab_xf cf_xuanx':'cf_xuanx'">
							<image :src="item.img"></image>
							{{item.title}}
							<u-radio v-if="isAndroid" :key="index" activeColor="#fe6e09" :name='item.id'
								style="float: right;margin-top: 5rpx;"></u-radio>

						</view>
					</view>
					<!--  #endif -->
				</u-radio-group>
			</view>
		</view>
		<view class="agree_wo flexbox" style="float: left; display: flex;" >			
			<radio-group class="agree">
			     <view v-for="(item, index) in argee" :key="index" >
			         <radio  class="agreeRadio" :value="item.id" :checked="item.id==radioValue" @click="radioCheck(index)"></radio>
			       
			     </view>
			    </radio-group>			
			<view>* 我已阅读并同意<span class="highlight" @click="showXieyi">《增值服务协议》</span></view>
			</view>
		<view class="char_btn">
			<!-- #ifdef MP-WEIXIN -->
			<view @click="kaiChar">立即充值</view>
			<!--  #endif -->				
			<!-- #ifdef APP-IOS -->
			<view @click="iosPay" >立即充值</view>			
			<!--  #endif -->
		</view>
		<!-- 充值协议 -->
		<u-popup :show="xieyiShow" :round="10" @close="xieyiShow=false">
			<view class="tanchu">
				<view class="dp_title">增值服务协议</view>
				<view style="max-height: 1000rpx;overflow-y: scroll;">
					<view v-html="xieyi.content"></view>
				</view>				
			</view>
		</u-popup>
	</view>
</template>

<script>
	import $http from '@/config/requestConfig.js';
	// import {  // 引入ios支付
	//     Iap,
	//     IapTransactionState
	//   } from "@/utils/iap.js"
	import {
		mapState
	} from 'vuex';
	import {
		setPay,
		setPayAssign
	} from '@/config/utils';
	export default {
		data() {
			return {
				xieyi:{
					title:'',
					content:''
				},
				xieyiShow:false,
				stepsCj: {},
				cjList: [],
				argee:[
				    {value:false,id:'1'}
				    
				] ,// 同意权限
				radioValue:'',
				orderSn:'',   // 订单sn
				productid: '',
				isAndroid: true, // 是否为安卓环境
				
				payType: 2,
				// #ifdef  APP-IOS
				payType: 3,
				// #endif
				paylist: [{
						title: '支付宝',
						id: 2,
						img: '../../static/icon/pay_1.png'
					},
					{
						title: '微信',
						id: 1,
						img: '../../static/icon/pay_2.png'
					}
				],
				iosPaylist: [{
					title: 'IOS支付',
					id: 3,
					img: '../../static/icon/pay_2.png'
				}],
			};
		},
		//第一次加载
		onLoad(e) {
			// 隐藏原生的tabbar
			uni.hideTabBar();
			this.getData();			
		},
		//页面显示
		onShow() {
			// 隐藏原生的tabbar
			uni.hideTabBar();
			// this.requestIapOrder()
		},
		computed: {
			...mapState(['userInfo']),
		},
		//方法
		methods: {
			showXieyi(){
				this.$http
					.get(`sys/agreement/list?key=pay`)
					.then(res => {						
						this.xieyi = res.page.list[0]
						this.xieyiShow = true
					})
				
			},
			radioCheck (index) {    // 勾选用户协议
			           this.argee.forEach((item =>{
			               item.isCheck = false
			           }))
			           if(this.radioValue==this.argee[index].id) {
			               this.radioValue =null
			           }else {
			              this.radioValue = this.argee[index].id
			           }
			          // console.log(this.radioValue)
			       },				
			iphonepay() {
				const that = this
				uni.showLoading({
					title: '检测支付环境...',
					mask: true
				})				
				plus.payment.getChannels((channels) => {
					for (var i in channels) {
						// 判断是否苹果支付
						if (channels[i].id === 'appleiap') {
							that.iapChannel = channels[i]
							that.requestOrder()
							consle.log(666666666)
						}
					}
				})
				
			},
			requestOrder() {
				uni.showLoading({
					title: '到这...',
					mask: true
				})
				const that = this
				// ['xxxxx'] 是平台申请拿到的内购商品的id 
				that.iapChannel.requestOrder(that.stepsCj.priceTypeId, function(event) {
					// uni.hideLoading()
					console.log(event)
					for (var index in event) {
						var OrderItem = event[index]
						console.log(OrderItem)
						that.topay(OrderItem.productid)
					}
				}, function(erroemsg) {
					//uni.hideLoading()	
					// uni.showToast({
						
					// })
					uni.showToast({
						title: "获取支付通道失败：",
						icon: 'none'
					})
				})
			},
			topay(id) {
				const that = this
				uni.showLoading({
					title: '充值中请勿离开',
					mask: true
				})
				uni.requestPayment({
					provider: 'appleiap',
					orderInfo: {
						productid: id,
						username: 'ordersn', // 用户标识
						optimize: true // 设置 optimize: true 解决丢单问题  
					},
					success: (res => {
						uni.hideLoading()
						let data= {
							receipt:res.transactionReceipt, // 校验体
							TransactionID: this.orderSn,
							transactionId: res.transactionIdentifier //交易id
						}
						const orderId = this.orderId //这个订单id 是由后端返回的
						const transactionId = res.transactionIdentifier //交易id
						const payload = res.transactionReceipt //校验体
						$http.request({
							url: "/apple/applePay",
							method: "POST", // POST、GET、PUT、DELETE，具体说明查看官方文档
							data,
							header: { //默认 无 说明：请求头
								'Content-Type': 'application/json'
							},
						}).then(res => {
							console.log(res)
							uni.showToast({
								title: '充值成功'
							})
							// 进行后续操作
							///that.getUserInfo()
						})
					}),
					fail: (e) => {
						uni.hideLoading()
						uni.showModal({
							content: "支付失败",
							showCancel: false
						})
					}
				})
				},


				getDevName() {
						// 获取使用环境
						if (uni.getSystemInfoSync().platform === 'android') {
							this.isAndroid = true
							// console.log('运行Android上')
						} else {
							this.isAndroid = false
							// console.log('运行iOS上')
				 	}
					},
					// 获取充值金额
					getData() {
						this.$http
							.post('book/bookbuyconfig/getVipOrPoint', {
								type: 'point',
								qudao: 'Android'
							})
							.then(res => {
								this.cjList = res.list
								this.stepsCj = res.list[0]
							});
					},

					// 点击充值金额
					chosPric(e) {
						this.stepsCj = e
						console.log(e)
					},

					// 选择支付方式
					choseType(e) {
						let that = this
						that.payType = e
					},
					//ios充值
					iosPay() {
						if(this.radioValue == '1'){							
						
						let that = this

						let data = {
							userId: that.userInfo.id, //下单人ID
							userPhone: that.userInfo.tel, //收货人手机号
							paymentMethod: that.payType,
							orderMoney: that.stepsCj.money * 1, //订单金额
							districtMoney: 0, //优惠金额
							realMoney: that.stepsCj.money * 1, //实收金额
							orderStatus: 0, //订单状态
							orderType: "point", //订单类型
						}

						$http.request({
							url: "book/buyorder/rechargeSave",
							method: "POST", // POST、GET、PUT、DELETE，具体说明查看官方文档
							data,
							header: { //默认 无 说明：请求头
								'Content-Type': 'application/json'
							},
						}).then(res => {
							console.log(res)
							this.orderSn = res.orderSn
							// this.topay(15)
							this.iphonepay()
						})
						}else{
							uni.showToast({
								title:'请勾选服务协议',
								icon:'error'
							})							
						}
					},
					// 充值
					kaiChar() {
						if(this.radioValue == '1'){							
						
						let that = this
						let data = {
							userId: that.userInfo.id, //下单人ID
							userPhone: that.userInfo.tel, //收货人手机号
							paymentMethod: that.payType, //1支付宝，2微信，3ios内购
							orderMoney: that.stepsCj.money * 1, //订单金额
							districtMoney: 0, //优惠金额
							realMoney: that.stepsCj.money * 1, //实收金额
							orderStatus: 0, //订单状态
							orderType: "point", //订单类型
						}

						$http.request({
							url: "book/buyorder/rechargeSave",
							method: "POST", // POST、GET、PUT、DELETE，具体说明查看官方文档
							data,
							header: { //默认 无 说明：请求头
								'Content-Type': 'application/json'
							},
						}).then(res => {							
							if (res.code == 0) {
								setPay({
									typePay: 'alipay',
									subject: 'point',
									totalAmount: that.stepsCj.money,
									type: that.payType,
									relevanceoid: res.orderSn,
									body: that.stepsCj.priceTypeId,
								}, res => {
									if (res.success) {
										uni.showToast({
											title: "支付成功"
										});
									} else {
										uni.showToast({
											title: "支付失败",
											icon: "none",
											image: '../../static/icon/ic_close.png'
										});
									}
								})
							}
						})
						}else{
							uni.showToast({
								title:'请勾选 已阅读会员服务协议',
								icon:'error'
							})
								return false
						}


					},

					// 跳转
					onPageJump(url) {
						uni.navigateTo({
							url: url
						});
					},

			},

		};
</script>
<style lang="scss" scoped>
	
	@import '@/style/mixin.scss';
	.tanchu {
		padding: 40rpx 30rpx 40rpx 30rpx;
		position: relative;


		.dp_title {
			font-size: 32rpx;
			margin-bottom: 50rpx;
			color: #555;
			text-align: center;
			font-weight: bold;
		}

		.dp_add {
			position: absolute;
			top: 40rpx;
			right: 30rpx;
			font-size: 22rpx;
			background-color: #fd6004;
			color: #fff;
			border-radius: 10rpx;
			padding: 5rpx 10rpx;

			.u-icon {
				display: inline-block;
				margin-right: 5rpx;
			}
		}

		.addressItem {
			border: 2px dashed #d9d9d9;
			border-radius: 10rpx;
			width: 100%;
			display: flex;
			padding: 20rpx 10rpx;
			margin: 25rpx 0 0 0;
			align-items: center;
			background-color: #fff;

			.addrContent {
				margin-left: 40rpx;
				flex: 1;

				.addrContentTop {
					display: flex;
					align-items: flex-end;
					margin: 0 0 15rpx 0;
					position: relative;

					.userName {
						font-size: 35rpx;
						font-weight: bold;
						margin-right: 30rpx;
					}

					.userTel {
						font-size: 25rpx;
						color: #888;
					}

					.userMoren {
						border: 1px solid #fd6004;
						color: #fd6004;
						padding: 3rpx 10rpx;
						font-size: 22rpx;
						border-radius: 10rpx;
						margin: 0 0 0 20rpx;
					}


					.chooseCheck {
						position: absolute;
						top: 3rpx;
						right: 6rpx;
					}
				}

				.addrContentBottom {
					font-size: 32rpx;
				}
			}
		}


		.addressItem.addItem_style {
			border-color: #fd6004;
		}

		.youhuiItem {
			border: 1px solid #d9d9d9;
			border-radius: 10rpx;
			width: 100%;
			display: flex;
			padding: 20rpx 10rpx;
			margin: 25rpx 0 0 0;
			align-items: center;
			background-color: #fff;
			font-size: 30rpx;
		}

		.youhuiItem>view {
			float: left;
		}

		.youhuiItem.youItem_style {
			border-color: #fd6004;
		}
	}
.agreeRadio{ zoom: .8;}
	
	.cha_jine {
		margin: 40rpx 50rpx 0 50rpx;

		.cj_title {
			font-size: 36rpx;
			font-weight: bold;
		}

		.cj_xiang {
			margin-top: 50rpx;

			.cj_price {
				box-shadow: 0 0 20rpx 0 #0000001a;
				float: left;
				width: 47%;
				margin: 0 30rpx 30rpx 0;
				text-align: center;
				padding: 25rpx 0 30rpx 0;
				border-radius: 20rpx;
				position: relative;
				color: #2d2d2d;

				.pr_jg {
					font-size: 45rpx;
					margin: 20rpx 0 10rpx 0;
					font-weight: bold;
				}

				.pr_yl {
					font-size: 30rpx;
					// text-decoration: line-through;
					color: #b1b1b1;
				}

				.pr_lj {
					background-image: linear-gradient(90deg, #fe6e09 0%, #efa574 100%);
					color: #fff;
					position: absolute;
					top: -10rpx;
					right: 0;
					font-size: 24rpx;
					padding: 5rpx 10rpx;
					border-top-left-radius: 20rpx;
					border-bottom-right-radius: 20rpx;
				}
			}

			.cj_price:nth-child(2n) {
				margin-right: 0;
			}

			.Tab_cj {
				box-shadow: 0 0 20rpx 0 #fe700bcc;
				color: #7b4c0a;
				background: #fff9f5cc;
			}
		}
	}
.highlight{color: $uni-color-primary;}
	.cha_fangsh {
		margin: 40rpx 50rpx 0 50rpx;

		.cf_title {
			font-size: 36rpx;
			font-weight: bold;
		}

		.cf_radio {
			margin-top: 20rpx;

			.cf_xuanx {
				font-size: 32rpx;
				padding: 20rpx;
				margin-bottom: 20rpx;
				border-bottom: 1px solid #ededed;

				image {
					width: 40rpx;
					height: 40rpx;
					display: inline-block;
					margin-right: 20rpx;
					vertical-align: bottom;
				}
			}

			.Tab_xf {
				background-color: #fdf1e9cc;
			}

		}



	}

	.agree_wo {
		color: #aaa;
		font-size: 25rpx;
		margin-top: 30rpx;
		margin: 40rpx 50rpx 0 50rpx;
		padding-bottom: 180rpx;
	}

	.char_btn {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 30rpx;

		view {
			background-image: linear-gradient(90deg, #ed7161 0%, #efa574 100%);
			color: #fff;
			width: 90%;
			margin: 0 auto;
			text-align: center;
			font-size: 35rpx;
			font-weight: bold;
			padding: 25rpx 0;
			border-radius: 50rpx;
		}
	}
</style>
