<template>
	<view>
		<!-- 公共组件-每个页面必须引入 -->
		<public-module></public-module>
		<!-- <z-nav-bar title="我的订单"></z-nav-bar> -->
		<z-nav-bar backState="2000" title="我的订单"></z-nav-bar>

		<view class="orderTabs">
			<view v-for="(item,index) in orderTabs" @click="orderTabCLi(item.value)"
				:class="orderListTab==item.value?'ordStyle':''">{{item.name}}</view>
		</view>

		<view class="orderList">
			<view class="orderItem" v-for="(ifex,inten) in orderList">
				<view class="orderState" v-if="ifex.orderStatus==0">待支付</view>
				<view class="orderState" v-if="ifex.orderStatus==1">待发货</view>
				<view class="orderState" v-if="ifex.orderStatus==2">待收货</view>
				<view class="orderState" v-if="ifex.orderStatus==3">已完成</view>
				<view class="orderContent" :key="index" v-if="ifex.orderType=='order'"
					v-for="(item,index) in ifex.products" @click="goOrdiCont(ifex)">
					<image :src="item.image" mode=""></image>
					<view class="itemJian">
						<view class="orderTitle">
							<text>{{item.productName}}</text>
						</view>
						<view class="orderPrice">
							￥<text style="font-weight: bold;">{{item.productPrice}}</text><br>
							<text style="color: #bbbbbb;font-size: 20rpx;margin-right: 10rpx;">X</text>
							<text style="color: #bbbbbb;">{{item.quantity}}</text>
						</view>
						<br clear="both">
					</view>
					<br clear="both">
				</view>
				<view class="orderContent" v-if="ifex.orderType=='point'" @click="goOrdiCont(ifex)">
					<image src="../../static/icon/oder_chong.png" mode="" style="height: 150rpx;"></image>
					<view class="itemJian">
						<view class="orderTitle">
							<text>花生币充值</text>
						</view>
						<view class="orderPrice">
							￥<text style="font-weight: bold;">{{ifex.realMoney}}</text>
						</view>
						<br clear="both">
					</view>
					<br clear="both">
				</view>
				<view class="orderContent" v-if="ifex.orderType=='vip'" @click="goOrdiCont(ifex)">
					<image src="../../static/icon/oder_vip.png" mode="" style="height: 150rpx;"></image>
					<view class="itemJian">
						<view class="orderTitle">
							<text>会员充值</text>
						</view>
						<view class="orderPrice">
							￥<text style="font-weight: bold;">{{ifex.realMoney}}</text>
						</view>
						<br clear="both">
					</view>
					<br clear="both">
				</view>				
				<view class="orderReal">
					<span style="color: #666; float: left; font-size: 12px;">下单时间：{{ifex.createTime}}</span>
					<span style="color: #666;margin-right: 10rpx;">实付款 : </span>
					<span>￥</span>{{ifex.realMoney}}
				</view>
				<view class="orderOper" v-if="ifex.orderStatus==0">
					<view class="opFix" @click="canceOrder(ifex)">取消订单</view>
					<view class="opCan" @click="goPay(ifex)">去支付</view>
				</view>
			</view>
		</view>
<z-navigation></z-navigation>
<music-play :playData="playData"></music-play>
	</view>
</template>

<script>
	import musicPlay from '@/components/music.vue'
	import $http from '@/config/requestConfig.js';
	import {
		setPay,
		setPayAssign,setWXPay
	} from '@/config/utils';
import {
		mapState,mapMutations
	} from 'vuex';
	export default {
		data() {
			return {
				playData:{},
				orderTabs: [{
					name: '全部',
					value: 9
				}, {
					name: '待支付',
					value: 0
				}, {
					name: '待发货',
					value: 1
				}, {
					name: '待收货',
					value: 2
				}, {
					name: '已完成',
					value: 3
				}],
				orderListTab: 9,
				orderList: [],
				iapChannel:{},
				checking:false,  // 正在检测
				ComplateRequestArr:null,
				isAndorid:true
			}
		},
		onShow() {
			this.getOrderList()
			this.checkIapOrders()    //检查未完成的苹果支付订单
			this.getOS()
		},
		computed: {
			...mapState(['userInfo']),
		},
		// 下拉刷新
		onPullDownRefresh() {
			this.getOrderList()
			uni.stopPullDownRefresh()
		},
		components:{
			musicPlay			
		},
		methods: {
			...mapMutations(['setUserInfo']),
			// 获得操作系统
			getOS(){
				let oprateOs = ''
				oprateOs = uni.getSystemInfoSync().platform
				console.log(oprateOs)
				if(oprateOs == 'android'){
					this.isAndorid = true
				}else{
					this.isAndorid = false
				}
			},
			checkIapOrders() {
				const that = this				
				// 如果ios已经绑定支付信息，就直接支付，如果没有绑定，就需要先绑定
				console.log('检测支付环境...')
				plus.payment.getChannels((channels) => {
					console.log(channels, 'channels')
					for (var i in channels) {
						// 判断是否苹果支付1
						if (channels[i].id === 'appleiap') {
							that.iapChannel = channels[i]
							that.restoreComplateRequest() //  检查未关闭订单
							// that.requestOrder(productId)							
						}
					}
				})
			
			},
			// 切换订单状态
			orderTabCLi(e) {
				this.orderListTab = e
				this.getOrderList()
			},

			// 获取订单列表
			getOrderList() {
				this.$http
					.post(`book/buyorder/appUserGetlist?userId=${this.userInfo.id}&orderStatus=${this.orderListTab}`)
					.then(res => {	
						this.orderList = res.page.list
					})
			},

			// 订单详情
			goOrdiCont(e) {
				uni.navigateTo({
					url: './orderLCont?orderId=' + e.orderId + '&orderType=' + e.orderStatus + '&orderSn=' + e.orderSn
				});
			},
			
			// 跳转到支付页面
			goPay1(e){	
				console.log(e,'goPay1')
				uni.navigateTo({
					url: '../peanut/reCharge?orderSn=' + e.orderSn
				});
			},
			
			// 取消订单
			canceOrder(e) {
				uni.showModal({
					title: '提示',
					content: '确定要取消订单吗？',
					confirmText: "取消订单",
					cancelText: "考虑一下",
					confirmColor: '#c96713',
					cancelColor: '#555',
					success: res => {
						if (res.confirm) {
							this.$http
								.post(`book/buyorder/appDelete?orderId=${e.orderId}`)
								.then(res => {
									uni.showToast({
										icon: 'none',
										title: '取消订单成功'
									})
									this.getOrderList()
								})
						}
					}
				});
			},

			// 支付
			goPay(payItem) {
				console.log(payItem,'payItem')				
				if(payItem.paymentMethod == 2){
					console.log('阿里支付')
				setPay({
					typePay: 'alipay',
					subject: 'order',
					totalAmount: payItem.realMoney,
					type: 2,
					relevanceoid: payItem.orderSn,
					customerId: this.userInfo.id,
				}, res => {
					if (res.success) {
						uni.showToast({
							title: "支付成功"
						});
					} else {
						uni.showToast({
							title: "支付失败",
							icon: "none",
							image: '../../static/icon/ic_close.png'
						});
					}
					this.getOrderList()
				})
			} else if(payItem.paymentMethod == 1){
				console.log('微信支付')
				// console.log(this.isAndorid)				
				 if(this.isAndorid == false){
					 uni.showModal({
						 title: '提示',
						 content: '很抱歉，苹果系统暂不支持微信支付',
						 showCancel:false
					 })
					return false
				 }else{
					let data1={
						orderSn:payItem.orderSn,
						buyOrderId: null,	
						totalAmount: payItem.realMoney					
					}
					console.log(data1,'data1')
					setWXPay(data1,res => {
						if (res.success) {
							uni.showToast({
								title: "支付成功"
							});
						} else {	
							console.log(res)
							if(res.data.errMsg.indexOf('User canceled') != -1){
								uni.showToast({
									title: "用户取消支付",
									icon: "none",
									image: '../../static/icon/ic_close.png'
								});
							}else{
							uni.showToast({
								title: "支付失败",
								icon: "none",
								image: '../../static/icon/ic_close.png'
							});
							}
						}
					})
				}
			}else if(payItem.paymentMethod == 3){
				// 苹果充值
				console.log('苹果二次支付')
				if(this.isAndorid){
					uni.showModal({
						title:'提示',
						showCancel:false,
						content:'很抱歉，当前订单属于苹果系统内购订单，安卓系统无法完成支付操作，您可切换到苹果系统进行支付，也可以取消该订单，并重新下单'
					})
				}else{
					this.iphonepay(payItem)
				}
			}
			},
			iphonepay(payItem) {	
				console.log(this.userInfo.restoreFlag,'this.userInfo.restoreFlag')
				if(this.ComplateRequestArr == null || this.ComplateRequestArr == [] ){	
					this.requestOrder(payItem)						
				}else{
					uni.showModal({
						title:'提示',
						showCancel: false,
						content: '您的账户存在未完成的支付订单，请稍后重启app留意账户变动。',
					})
				}
			},
			requestOrder(payItem) {
				uni.showLoading({
					title: '获取商品信息',
					mask: true
				})
				const that = this
				// console.log(productId, 88888888)
				// ['xxxxx'] 是平台申请拿到的内购商品的id 
				let IAPOrders = []
				 IAPOrders.push(payItem.productId+'')
				console.log(IAPOrders, 'IAPOrders')
				 // 新建订单
				that.iapChannel.requestOrder(IAPOrders, function(event) {
					// uni.hideLoading()
					console.log(event, 'event')
					for (var index in event) {
						var OrderItem = event[index]
						// console.log(OrderItem, 'OrderItem')
						console.log(OrderItem.productid,'OrderItem.productid')
						that.topay(payItem)
					}
				}, function(erroemsg) {
					uni.showToast({
						title: "商品获取失败",
						icon: 'none'
					})
				})
			},
			topay(payItem) {				
				const that = this
				uni.hideLoading()	
				// var restoreFlag = true; // 调用支付接口时标记 restoreFlag = true , 实际应用请将标记存储在 storage 中  
				this.setUserInfo({restoreFlag:true});
				console.log(this.userInfo,'更新后的用户信息')				
				plus.payment.request(that.iapChannel, {
					productid: payItem.productId,
					username: payItem.orderSn, // 用户标识/订单标识 					
					manualFinishTransaction: true // 3.5.1+ 支持，设置此参数后需要开发者主动关闭订单，参见下面的关闭订单方法 finishTransaction()
					
				}, function(result) {
					// restoreFlag = false; // 支付成功清除标记 restoreFlag = false 					
					that.transaction = result
					// 支付成功，result 为 IAP商品交易信息对象 IAPTransaction 需将返回的支付凭证传给后端进行二次认证  
					that.iapCheck(result)
				}, function(e) {
					if(e.errCode == 2){
						// 用户未绑定支付方式，app内支付流程结束，系统弹出框引导用户绑定支付方式，此过程将跳转到系统应用 AppStore 进行绑定支付方式，绑定成功同步支付成功，用户成功付款
						plus.runtime.openURL("https://apps.apple.com/account/billing");
					}else{
						// restoreFlag = false; // 支付失败清楚标记					
						that.finishTransaction(result);
						//console.log('订单关闭后的用户信息', that.userInfo);
						 // console.log(e)	
						//console.log(e.message)
					}
				});						
			},			
			// 查询未关闭订单
			restoreComplateRequest(){				
				let that = this
				console.log('检测未完成订单')
				// console.log(that.iapChannel,'this.iapChannel')				
				that.iapChannel.restoreComplateRequest({
					manualFinishTransaction: true
				}, function(results) { 
					console.log('进入restoreComplateRequest')
						// if(!that.checking){
							// that.checking = true
							// console.log(that.checking)
				        // results 格式为数组存放恢复的IAP商品交易信息对象 IAPTransaction，通用需将返回的支付凭证传给后端进行二次认证  
						that.ComplateRequestArr = results
						console.log(that.ComplateRequestArr,'未完成订单数组')							
						if(results && results.length>0){							
						results.map((item,index)=>{
							// "0"为正在支付；"1"为支付成功；"2"为支付失败；"3"为支付已恢复。
							if(item.transactionState == '1'){ 
								// 已经支付，但是没有走逻辑的内购订单								
							    that.iapCheck(item,index)															
							}else{
								// 其他状态的内购订单
								that.finishTransaction(item)	
								
							}	
						})
						}else{
							this.setUserInfo({restoreFlag:false});
							console.log('无未处理订单，可以拉起新的支付')
						}
						// }
					});	
					
				
			},
			// 关闭交易订单
			finishTransaction(trans,index){				
				this.iapChannel.finishTransaction(trans, (success) => {
				      console.log('关闭订单成功',index);
					  
					 if(index == this.ComplateRequestArr.length-1){  // 最后一个支付订单
						this.setUserInfo({restoreFlag:false});	
						console.log(this.userInfo.restoreFlag, 'this.userInfo.restoreFlag')
					}
					 
				    }, (fail) => {
				      console.log('关闭订单失败');
				    });
			},
			iapCheck(result,index) {
				  const that = this
				console.log('进入后台验证')
				let data = {
					transactionId: result.transactionIdentifier, // 支付交易id
					customerOid: that.userInfo.id, 
					productId: result.payment.productid, // 产品id
					orderId: result.payment.username, // 系统订单号
					receiptData: result.transactionReceipt ,// 苹果返回收据
					loadAnimate:'none', // 请求加载动画
				}	
				console.log(data,'data')
				$http.request({
					url: "/Ipa/veri",
					method: "POST", // POST、GET、PUT、DELETE，具体说明查看官方文档		
					data,
					header: { //默认 无 说明：请求头
						'Content-Type': 'application/json'
					},
				}).then(res => {
					console.log(JSON.stringify(res))					
					console.log(res.code)
					if(res.code == 0){
						// uni.hideLoading()
						console.log('充值订单已处理，请留意账户金额变动....')						
					// 服务器验证票据有效后在客户端关闭订单
						that.finishTransaction(result,index)									
					}else if(res.code == 200){ // 重复验证订单
						console.log('重复验证....')
						that.finishTransaction(result,index)
					}
				}).catch(e => {					
					console.log('支付验证失败，进入轮询程序...')
					that.getIapPayResult(result,index)
				  })
				console.log('--------------')
			},
			
			// 轮询验证支付结果			
			getIapPayResult(result,index){
				// let interval = null
			this.ComplateRequestInterval = setTimeout(() => {
					if(this.maxTimes <= 3){
				    this.iapCheck(result,index)
					console.log('执行1', this.maxTimes,this.ComplateRequestInterval)
					this.maxTimes += 1
					}else{
						this.maxTimes = 0
						console.log('停止轮询', this.maxTimes,this.ComplateRequestInterval, this.maxTimes)
						this.checking = false
						this.saveErrorIapOrder(result,index)
						clearTimeout(this.ComplateRequestInterval)
						
					}
				},10000)
				
			},
			// 轮询失败接口
			saveErrorIapOrder(result,index){
				console.log('提交到充值问题单里面...')
				let data = {
					transactionId : result.transactionIdentifier,
					failureflag: 1,
					orderId:result.payment.username,
					receiptData:result.transactionReceipt,
					productId:result.payment.productid,
					customerOid:this.userInfo.id					
				}				
				$http.request({
					url: "Ipa/failure",
					method: "POST", // POST、GET、PUT、DELETE，具体说明查看官方文档		
					data,
					header: { //默认 无 说明：请求头
						'Content-Type': 'application/json'
					},
				}).then(res => {
					console.log(JSON.stringify(res))					
					if(res.code == 200){
						console.log('提交成功，关闭订单')
						this.finishTransaction(result,index)
					}
				}).catch(e => {					
					console.log(e)	
					if(e.statusCode == 0){ // 重复提交，直接关闭订单
						this.finishTransaction(result,index)
					}
				  })
			},

		}
	}
</script>

<style lang="scss" scoped>
	@import '@/style/mixin.scss';

	.orderTabs {
		margin: 70rpx 0 0 0;
		width: 100%;
		padding: 0 3% 3% 3%;
		position: fixed;
		top: 80rpx;
		background-color: #f7faf9;
		z-index: 100;

		view {
			display: inline-block;
			padding: 0 0 20rpx 0;
			margin: 40rpx 0 15rpx 0;
			width: 20%;
			text-align: center;
			font-size: 30rpx;
		}

		.ordStyle {
			border-bottom: 5rpx solid #54a966;
			color: #54a966;
			font-weight: bold;
		}
	}

	.orderList {
		padding: 20rpx;
		margin-top: 130rpx;

		.orderItem {
			padding: 30rpx 10rpx 30rpx 30rpx;
			background-color: #fff;
			border-radius: 30rpx;
			margin-bottom: 30rpx;

			.orderState {
				
				text-align: right;
				font-size: 30rpx;
				margin: 0 20rpx 30rpx 0;
				font-weight: bold;				
				color: #d70808;
			}

			.orderContent {
				margin-bottom: 20rpx;

				image {
					width: 150rpx;
					height: 180rpx;
					margin-right: 20rpx;
					float: left;
				}

				.itemJian {
					float: left;
					width: 470rpx;

					.orderTitle {
						font-weight: bold;
						font-size: 30rpx;
						margin: 0 0 20rpx 0;
						float: left;
						width: 410rpx;
					}

					.orderPrice {
						font-size: 28rpx;
						float: right;
						width: 60rpx;
						text-align: right;
						line-height: 40rpx;
					}
				}


			}

			.orderReal {
				border-top: 1px solid #eee;
				text-align: right;
				font-size: 30rpx;
				margin: 30rpx 20rpx 0 0;
				padding: 30rpx 0 0 0;
			}

			.orderOper {
				text-align: right;
				margin: 30rpx 20rpx 0 0;

				view {
					margin-left: 20rpx;
					padding: 10rpx 0;
					display: inline-block;
					width: 150rpx;
					font-size: 25rpx;
					text-align: center;
				}

				.opFix {
					color: #555;
					border: 1px solid #ddd;
					border-radius: 30rpx;
				}

				.opCan {
					color: #c96713;
					border: 1px solid #eba00b;
					border-radius: 30rpx;
				}
			}
		}
	}
</style>
