import store from '@/store/index.js'
import $http from '@/config/requestConfig.js';
// #ifdef APP-PLUS
const iapChannel = null;
const checking = false
const ComplateRequestArr = []
// #endif


var iap = {
	 getProvider() {
		return new Promise((resolve, reject) => {
			uni.getProvider({
				service: 'payment',
				success: (res) => {
					const iapChannel = res.providers.find((channel) => {
						return (channel.id === 'appleiap')
					})
					resolve(iapChannel);
					// 如果 iapChannel 为 null，说明当前包没有包含iap支付模块。注意：HBuilder基座不包含 iap 通道	  		
				}
			});
		})
	},
	// 检测支付通道
   async getChannels(){
		const that = this;
		console.log('检测支付通道')
		this.iapChannel = await this.getProvider()
		if(this.iapChannel){
			this.restoreComplateRequest()
		}else{		
			 console.log("不支持iap支付");
		}		
	},
	// 检测是否有未关闭订单	
	restoreComplateRequest() {
		let that = this
		console.log('检测未完成订单')			
		 this.iapChannel.restoreCompletedTransactions({
			manualFinishTransaction: true
		}, function(results) {
			if (!that.checking) {
				that.checking = true					
				// results 格式为数组存放恢复的IAP商品交易信息对象 IAPTransaction，通用需将返回的支付凭证传给后端进行二次认证  
				that.ComplateRequestArr = results
				console.log('未完成订单数组共有：=》',that.ComplateRequestArr.length ,that.ComplateRequestArr)
				
				if (that.ComplateRequestArr.length > 0) {			
					that.ComplateRequestArr.map((item, index) => {
						// "0"为正在支付；"1"为支付成功；"2"为支付失败；"3"为支付已恢复。
						if (item.transactionState == '1') {
							console.log('待验证订单，即将进入后台验证：=>', item)
							// return false
							// 已经支付，但是没有走逻辑的内购订单	   就发给后台做验证							
							 that.iapCheck(item, index)
						} else {
							// 其他状态的内购订单
							that.finishTransaction(item)			
						}
					})
				}
			}
		});
	},
	// 关闭订单
	finishTransaction(trans) {
		this.iapChannel.finishTransaction(
			trans,
			(success) => {
				console.log("关闭订单成功");	
				that.checking = false
			},
			(fail) => {
				console.log("关闭订单失败");
				that.checking = false
			}
		);
	},
	iapCheck(result) {
		let that = this;
		console.log("进入后台验证");		
		let data = {
			transactionId: result.transactionIdentifier, // 支付交易id
			customerOid: store.state.userInfo.id,
			productId: result.payment.productid.slice(1), // 产品id
			orderId: result.payment.username, // 系统订单号
			receiptData: result.transactionReceipt, // 苹果返回收据
			// isSandBox:true
			//	body: that.stepsCj.priceTypeId // 充值类型id
		};
		console.log("提交给后台的数据=>", data);
		// return false
		$http
			.request({
				url: "/Ipa/veri",
				method: "POST",
				data,
				header: {
					"Content-Type": "application/json",
				},
			})
			.then((res) => {
				if (res.code == 0) {
					// 服务器验证票据有效后在客户端关闭订单 (iapChannel.finishTransaction)
					that.finishTransaction(result);
				}
			})
			.catch((e) => {
				console.log('后台验证失败=>',e);	
				uni.showModal({
					title: "提示",	
					cancelColor:'#0081ff',
					content: `您的账户下存在验证异常的订单(订单编号为：${e.data.orderId})，可尝试稍后重启app，如不能解决您的问题，可联系官方客服`,
					cancelText:'已验证关闭订单',
					confirmText:'知道了',
					success: function(res) {
						if (res.confirm) {
							console.log("用户点击确定");
						}else{
							console.log('点了取消')
							that.finishTransaction(result);
						}
					},
				});
			});
	},
}
module.exports = {iap}

