<template>
	<view class="app">
		<view class="price-box">
			<text>支付金额</text>
			<text class="price">{{ money }}</text>
		</view>
		<view class="pay-type-list">
			<view class="type-item b-b" @click="changePayType(1)">
				<text class="icon iconfont iconweixin"></text>
				<view class="con">
					<text class="tit">微信支付</text>
					<text>推荐使用微信支付</text>
				</view>
				<label class="radio">
					<radio value="" color="#5dbc7c" :checked="payType == 1"></radio>
				</label>
			</view>
			<!-- #ifdef APP-PLUS -->
			<view class="type-item b-b" @click="changePayType(2)">
				<text class="icon iconfont iconzhifubao"></text>
				<view class="con"><text class="tit">支付宝支付</text></view>
				<label class="radio">
					<radio value="" color="#5dbc7c" :checked="payType == 2"></radio>
				</label>
			</view>
			<!-- #endif -->
			<view class="type-item" @click="changePayType(3)">
				<text class="icon iconfont iconyue"></text>
				<view class="con">
					<text class="tit">余额支付</text>
					<text>可用余额{{ now_money }}</text>
				</view>
				<label class="radio">
					<radio value="" color="#5dbc7c" :checked="payType == 3"></radio>
				</label>
			</view>
			<!-- <view class="type-item" @click="changePayType(4)">
				<image src="../../static/icon/i8.png" mode=""
					style="width: 32rpx; height: 32rpx;margin-right: 70rpx;margin-left: 10rpx;"></image>
				<view class="con">
					<text class="tit">代付</text>
				</view>
				<label class="radio">
					<radio value="" color="#5dbc7c" :checked="payType == 4"></radio>
				</label>
			</view> -->
			<!-- <view class="type-item" @click="changePayType(5)">
				<image src="../../static/icon/i9.png" mode=""
					style="width: 32rpx; height: 32rpx;margin-right: 58rpx;margin-left: 10rpx;"></image>
				<view class="con">
					<text class="tit">第三方支付</text>
				</view>
				<label class="radio">
					<radio value="" color="#5dbc7c" :checked="payType == 5"></radio>
				</label>
			</view> -->
		</view>
		<text class="mix-btn" :class="{ clickbg: payLoding }" @click="!payLoding ? confirm() : ''">确认支付</text>
		<uni-popup ref="popupdf" type="center" :maskClick="false">
			<view class="df-wrap">
					<view class="ewm">
					<!-- <image :src="erweimasrc" mode=""></image> -->
						<tki-qrcode cid="tki-qrcode-canvass" ref="qrcodes" :val="val" :size="size" :unit="unit" :background="background"
							:foreground="foreground" :pdground="pdground" :icon="icon" :iconSize="iconSize" :lv="lv" :onval="onval"
							:showLoading="showLoading" :loadMake="loadMake" :usingComponents="usingComponents" @result="qrRs"/>
					</view>
					<view class="dftit" @click="comfirm(val)">
						代付码：{{val}}
					</view>
					<view class="dftip">
						扫一扫为他代付
					</view>
					<view class="btn" @click="closeDf">
						代付完成，返回首页
					</view>
			</view>
		</uni-popup>
		<view class="qrimg">
			<tki-qrcode :cid="cid" ref="qrcode" :val="val" :size="size" :unit="unit" :background="background"
				:foreground="foreground" :pdground="pdground" :icon="icon" :iconSize="iconSize" :lv="lv" :onval="onval"
				:showLoading="showLoading" :loadMake="loadMake" :usingComponents="usingComponents" @result="qrR" />
		</view>
	</view>

</template>

<script>
	import {
		balance
	} from '@/api/wallet.js';
	import {
		createOrderkey,
		computedOrderkey,
		orderPay
	} from '@/api/order.js';
	import {
		mapState
	} from 'vuex';
	// #ifdef H5
	import weichatObj from '@/plugin/jweixin-module/index.js';
	// #endif
	export default {
		data() {
			return {
				cid: 'tki-qrcode-canvas', //canvasId，页面存在多个二维码组件时需设置不同的ID
				size: 300, //生成的二维码大小
				unit: 'upx', //大小单位尺寸
				val: '', //要生成的内容
				background: '#ffffff', //二维码背景色
				foreground: '#333333', //二维码前景色
				pdground: '#333333', //二维码角标色
				icon: '', //二维码图标URL（必须是本地图片，网络图需要先下载至本地）
				iconSize: 40, //二维码图标大小
				lv: 3, //容错级别
				onval: true, //监听val值变化自动重新生成二维码
				loadMake: true, //组件初始化完成后自动生成二维码，val需要有值
				usingComponents: false, //是否使用了自定义组件模式（主要是为了修复非自定义组件模式时 v-if 无法生成二维码的问题）
				showLoading: false, //是否显示loading

				payType: 3, //支付类型
				// #ifdef H5
				payName: 'yue',
				// #endif
				// #ifdef APP-PLUS
				payName: 'yue',
				// #endif
				// #ifdef MP-WEIXIN
				payName: 'yue',
				// #endif
				orderInfo: {},
				money: 0.0, //订单金额
				now_money: 0.0, //余额
				orderKey: '',
				orderId: '', //保存订单id
				payLoding: false, //判断是否支付中
				type: '', //判断是否从订单中进入
				// #ifdef H5
				froms: '', //保存h5中数据来源对象
				// #endif
				pinkid: '', //保存拼团商品id
				is_mark: 0,
				erweimasrc:'',
			};
		},
		computed: {
			// #ifdef H5
			...mapState(['weichatObj']),
			// #endif
			...mapState('user', ['userInfo'])
		},
		onLoad(options) {
			if (options.is_mark) {
				this.is_mark = options.is_mark
			}
			if (options.type == 1) {
				this.type = 1;
				this.orderId = options.ordid;
				this.money = options.money;
			} else {
				this.orderKey = options.key;
				let prepage = this.$api.prePage();
				computedOrderkey({
					orderkey: this.orderKey,
					couponId: prepage.couponChecked.id, //优惠券编号
					addressId: prepage.addressData.id, //地址编号
					useIntegral: prepage.checkedPoints ? 1 : 0
				}).then(({
					data
				}) => {
					// 获取支付金额
					this.money = data.result.pay_price;
				});
			}
			// 保存pinkid
			if (options.pinkid) {
				this.pinkid = options.pinkid;
			}
			// 载入余额
			balance({}).then(({
				data
			}) => {
				// 获取余额
				this.now_money = data.now_money;
			});
		},
		methods: {
			comfirm(text) {
				console.log(text);
				const result = this.uniCopy(text);
				if (result === false) {
					uni.showToast({
						title: '不支持'
					});
				} else {
					uni.showToast({
						title: '复制成功',
						icon: 'none'
					});
				}
				// this.$refs.popupkf.close();
			},
			uniCopy(content) {
				/**
				 * 小程序端 和 app端的复制逻辑
				 */
				//#ifndef H5
				uni.setClipboardData({
					data: content,
					success: function() {
						console.log('success');
						return true;
					}
				});
				//#endif
			
				/**
				 * H5端的复制逻辑
				 */
				// #ifdef H5
				if (!document.queryCommandSupported('copy')) {
					//为了兼容有些浏览器 queryCommandSupported 的判断
					// 不支持
					return false;
				}
				let textarea = document.createElement('textarea');
				textarea.value = content;
				textarea.readOnly = 'readOnly';
				document.body.appendChild(textarea);
				textarea.select(); // 选择对象
				textarea.setSelectionRange(0, content.length); //核心
				let result = document.execCommand('copy'); // 执行浏览器复制命令
				textarea.remove();
				return result;
				// #endif
			},
			qrRs() {
				
			},
			closeDf() {
				this.$refs.popupdf.close()
				uni.switchTab({
					url:'/pages/index/index'
				})
			},
			qrR(res) {
				console.log('zheli');
				// this.erweimasrc = res
				try{
					uni.hideLoading()
					this.$refs.popupdf.open()
				}catch(e){
					//TODO handle the exception
					console.log(e);
				}
				
			},
			//选择支付方式
			changePayType(type) {
				this.payType = type;
				if (this.payType == 1) {
					this.payName = 'weixin';
				}
				if (this.payType == 2) {
					this.payName = 'ali';
				}
				if (this.payType == 3) {
					this.payName = 'yue';
				}
				if (this.payType == 4) {
					this.payName = 'paying';
				}
				if (this.payType == 5) {
					this.payName = 'lakala';
				}
			},
			// 支付金额
			orderMoneyPay() {
				let obj = this;
				console.log('支付金额')
				orderPay({
						uni: obj.orderId,
						// #ifdef H5
						from: obj.froms ? 'weixin' : 'H5', //来源
						// #endif
						// #ifdef MP-WEIXIN
						from: 'routine', //来源
						// #endif
						// #ifdef APP-PLUS
						from: 'app', //来源
						// #endif
						paytype: obj.payName //支付类型  weixin-微信 yue-余额
					})
					.then(e => {
						console.log(obj.payName, '支付类型')
						console.log(e, '支付金额')
						// 判断是否为余额支付
						if (obj.payName == 'yue' && e.data.status == 'SUCCESS') {
							if (e.status == 200) {
								obj.paySuccessTo();
							} else {
								obj.$api.msg(msg);
							}
						}
						if (obj.payName == 'paying' && e.data.status == 'SUCCESS') {
							if (e.status == 200) {
								console.log(e.data.result.order_id);
								// obj.paySuccessTo();
								obj.val = e.data.result.order_id
								// console.log(obj.val,'obj.val');
								uni.showLoading({
									title: '代付码生成中...'
								})
							} else {
								obj.$api.msg(msg);
							}
						}
						if (obj.payName == 'lakala' && e.data.status == 'LAKALA_PAY') {
							if (e.status == 200) {
								// console.log(e.data.result.order_id);
								// obj.paySuccessTo();
								let url = e.data.result.jsConfig.counter_url
								// console.log(obj.val,'obj.val');
								// uni.showLoading({
								// 	title: '代付码生成中...'
								// })
								// #ifdef APP
								plus.runtime.openURL(url);
								// #endif
								// #ifdef H5
								window.open(url)
								// #endif
								setTimeout(()=>{
									uni.switchTab({
										url:'/pages/index/index'
									})
								},1500)
							} else {
								obj.$api.msg(msg);
							}
						}
						if (obj.payName == 'weixin' || obj.payName == 'routine') {
							let da = e.data.result.jsConfig;
							let data = {
								// #ifdef H5
								timestamp: da.timestamp,
								// #endif
								// #ifdef MP
								timeStamp: da.timestamp,
								// #endif
								nonceStr: da.nonceStr,
								package: da.package,
								signType: da.signType,
								paySign: da.paySign,
								success: function(res) {
									obj.paySuccessTo();
								},
								fail: () => {

									uni.navigateTo({
										url: '/pages/order/order?state=0'
									});
								}
							};
							// #ifdef H5
							if (obj.payName == 'weixin') {
								weichatObj.chooseWXPay(data);
							}
							// #endif
							// #ifdef MP-WEIXIN
							if (obj.payName == 'weixin' || obj.payName == 'routine') {
								console.log('开始支付')
								wx.requestPayment(data);
							}
							// #endif
						}
						uni.hideLoading();
						obj.payLoding = false;
					})
					.catch(e => {
						// 支付完成
						uni.hideLoading();
						obj.payLoding = false;
						console.log(e);
					});
			},
			// 支付成功跳转
			paySuccessTo() {
				let obj = this
				uni.hideLoading();
				uni.redirectTo({
					url: '/pages/money/paySuccess?orderid=' + this.orderId
				});

			},
			//确认支付
			confirm: async function() {
				let obj = this;
				// 判断是否余额不足
				if (obj.payName == 'yue' && +obj.now_money < obj.money) {
					uni.showModal({
						title: '提示',
						content: '账户余额不足！',
						showCancel: false,
						success: res => {},
						fail: () => {},
						complete: () => {}
					});
					return;
				}
				if (obj.payName == 'againjifen' && +obj.userInfo.again_integral < obj.money) {
					uni.showModal({
						title: '提示',
						content: '账户复购积分不足！',
						showCancel: false,
						success: res => {},
						fail: () => {},
						complete: () => {}
					});
					return;
				}
				uni.showLoading({
					title: '支付中',
					mask: true
				})

				// 支付中
				obj.payLoding = true;
				// #ifdef H5
				// 获取当前是否为微信浏览器
				obj.froms = uni.getStorageSync('weichatBrowser') || '';
				// #endif
				// 判断是否为未支付订单中跳转进入
				if (obj.type != 1) {
					// 初次生成订单
					obj.firstCreateOrder();
				} else {
					// 已经生成订单未支付
					obj.orderMoneyPay();
				}
			},
			// 初次订单创建
			firstCreateOrder() {
				let obj = this;
				// 获取下单页面数据
				let prepage = obj.$api.prePage();

				let data = {
					is_agent:prepage.is_agent,
					is_level: prepage.is_level,
					is_pack: prepage.is_pack,
					real_name: prepage.addressData.real_name, //联系人名称
					phone: prepage.addressData.phone, //联系人号码
					couponId: prepage.couponChecked.id, //优惠券编号
					addressId: prepage.addressData.id, //支付地址id
					useIntegral: prepage.checkedPoints ? 1 : 0, //是否积分抵扣1为是0为否
					payType: obj.payName, //支付类型  weixin-微信 yue-余额
					mark: prepage.desc, //备注
					// #ifdef H5
					from: obj.froms ? 'weixin' : 'H5', //来源
					// #endif
					// #ifdef MP-WEIXIN
					from: 'routine', //来源
					// #endif
					// #ifdef APP-PLUS
					from: 'app', //来源
					// #endif
					shipping_type: prepage.tabCurrentIndex == 0?1:2,//提货方式 1 快递 2自提
					store_id: prepage.tabCurrentIndex == 0?'':prepage.checkedPoint.id
				};
				// 判断是否拼团商品
				if (obj.pinkid) {
					data.pinkId = obj.pinkid;
				}
				// 生成订单
				createOrderkey(data, obj.orderKey)
					.then(({
						data,
						status,
						msg
					}) => {
						console.log('生成订单')
						// 判断是否支付失败
						if (data.status == 'ORDER_EXIST') {
							uni.showModal({
								title: '提示',
								content: msg,
								showCancel: false
							});
							uni.hideLoading();
							obj.payLoding = false;
							return;
						}
						// 保存订单号
						obj.orderId = data.result.orderId;
						// 判断是否为余额支付
						if (obj.payName == 'yue') {
							if (status == 200 && data.status == 'SUCCESS') {
								obj.paySuccessTo();
							} else {
								obj.$api.msg(msg);
							}
						} else if (obj.payName == 'paying') {
							if (status == 200 && data.status == 'SUCCESS') {
								// obj.paySuccessTo();
								// console.log(data.result.orderId);
								obj.val = data.result.orderId
								console.log(obj.val,'obj.val');
								uni.showLoading({
									title: '代付码生成中...'
								})
							} else {
								obj.$api.msg(msg);
							}
						} else if(obj.payName == 'lakala'){
							if (status == 200 && data.status == 'LAKALA_PAY') {
								// obj.paySuccessTo();
								// console.log(data.result.orderId);
								let url = data.result.jsConfig.counter_url
								// window.open()
								// console.log(obj.val,'obj.val');
								// uni.showLoading({
								// 	title: '代付码生成中...'
								// })
								// #ifdef APP
								plus.runtime.openURL(url);
								// #endif
								// #ifdef H5
								window.open(url)
								// #endif
								setTimeout(()=>{
									uni.switchTab({
										url:'/pages/index/index'
									})
								},1500)
							} else {
								obj.$api.msg(msg);
							}
						} else {
							// 立即支付
							obj.orderMoneyPay();
						}
					})
					.catch(e => {
						uni.hideLoading();
						obj.payLoding = false;
						console.log(e);
					});
			}
		}
	};
</script>

<style lang="scss">
	.app {
		width: 100%;
	}

	.price-box {
		background-color: #fff;
		height: 265upx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: 28upx;
		color: #909399;

		.price {
			font-size: 50upx;
			color: #303133;
			margin-top: 12upx;

			&:before {
				content: '￥';
				font-size: 40upx;
			}
		}
	}

	.pay-type-list {
		margin-top: 20upx;
		background-color: #fff;
		padding-left: 60upx;

		.type-item {
			height: 120upx;
			padding: 20upx 0;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding-right: 60upx;
			font-size: 30upx;
			position: relative;
		}

		.icon {
			width: 100upx;
			font-size: 52upx;
		}

		.iconyue {
			color: #fe8e2e;
		}

		.iconweixin {
			color: #36cb59;
		}

		.iconzhifubao {
			color: #01aaef;
		}

		.tit {
			font-size: $font-lg;
			color: $font-color-dark;
			margin-bottom: 4upx;
		}

		.con {
			flex: 1;
			display: flex;
			flex-direction: column;
			font-size: $font-sm;
			color: $font-color-light;
		}
	}

	.mix-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 630upx;
		height: 80upx;
		margin: 80upx auto 30upx;
		font-size: $font-lg;
		color: #fff;
		background-color: $base-color;
		border-radius: 10upx;
		/* box-shadow: 1px 2px 5px rgba(219, 63, 96, 0.4); */
	}

	.clickbg {
		background-color: $color-gray !important;
	}
	.df-wrap {
		text-align: center;
		padding:60rpx 40rpx;
		background-color: #fff;
		border-radius: 20rpx;
		position: relative;
		.ewm {
			// width: 377rpx;
			// height: 377rpx;
			// border: 3px solid #FF6F0F;
			margin: auto;
			padding: 23rpx;
			border-radius: 15rpx;
			image {
				width: 100%;
				height: 100%;
				margin: auto;
			}
		}
		.dftit {
			padding: 30rpx 0 15rpx;
			font-size: 36rpx;
			color: #333333;
		}
		.dftip {
			font-size: 30rpx;
			color: #333333;
		}
		.btn {
			
			width: 600rpx;
			line-height: 87rpx;
			background: $base-color;
			color: #fff;
			border-radius: 20rpx;
			font-weight: 500;
			font-size: 35rpx;
			position: absolute;
			bottom: -120rpx;
			left: 0;
			right: 0;
			margin: auto;
		}
	}
	.qrimg {
		position: absolute;
		left: -9999rpx;
		top: -9999rpx;
	}
</style>