<!-- 收银台 -->
<template>
	<custom-navbar-page class="cashier-page" title="收银台" leftIcon="back" color="#333333">
		<view class="header">
			<image src="https://box-mall.oss-cn-hangzhou.aliyuncs.com/static/shopcar/clover.png" mode="" class="clover-img" v-if="paidWith == 1"></image>
			<view class="header-title" v-if="paidWith == 1">实付繁豆</view>
			<view class="header-title" v-if="paidWith == 2">实付金额</view>
			<view class="header-price">
				<text class="header-sym" v-if="paidWith == 2">¥ </text>
				<text class="price" v-if="paidWith == 2"> {{mathAdd}}</text>
				<text class="price" v-if="paidWith == 1"> {{points}}</text>
			</view>
		</view>
		<view class="pay-type">支付方式</view>
		<!-- <view class="pay-item" v-if="paidWith == 1">
			<view class="item-info">
				<view class="pay-label">繁豆-线路1</view>
			</view>
			<image src="@/static/shop/select.png" mode="" class="pay-select"></image>
		</view> -->
		<template v-if="paidWith == 1">
			<view v-for="(item,index) in payList" :key="index" class="pay-item" style="margin-bottom: 0;" @click="payChange(index)">
				<view class="item-info">
					<image class="pay-img" :src="item.img" mode="" :style="{width:item.width,height:item.height}"></image>
					<view class="pay-label">{{item.label}}</view>
				</view>
				<image src="https://box-mall.oss-cn-hangzhou.aliyuncs.com/static/shop/select-no.png" mode="" v-if="!item.visible" class="pay-select"></image>
				<image src="https://box-mall.oss-cn-hangzhou.aliyuncs.com/static/shop/select.png" mode="" v-if="item.visible" class="pay-select"></image>
			</view>
		</template>
		<template v-if="paidWith == 2">
			<view v-for="(item,index) in payList" :key="index" class="pay-item" @click="payChange(index)">
				<view class="item-info">
					<image class="pay-img" :src="item.img" mode="" :style="{width:item.width,height:item.height}"></image>
					<view class="pay-label">{{item.label}}</view>
				</view>
				<image src="https://box-mall.oss-cn-hangzhou.aliyuncs.com/static/shop/select-no.png" mode="" v-if="!item.visible" class="pay-select"></image>
				<image src="https://box-mall.oss-cn-hangzhou.aliyuncs.com/static/shop/select.png" mode="" v-if="item.visible" class="pay-select"></image>
			</view>
		</template>
		<view class="confirm-pay" @click="paySuccess">确认支付</view>
		<popup-view :show="popupShow" mode="center" :value="popupShow" @close="popupClose" :closeable="true" :z-index="99999">
			<view class="popup-content">
				<view class="popup-cancel" >
					<view class="f36 col000">
						温馨提示
					</view>
					<view class="f28 col26 cancel-sub">
						请复制链接使用微信浏览，进行支付
					</view>
					<view class="cancel-op">
						<view class="popup-btn popup-btn-cancel" @click="copy">
							<view class="f24">
								复制链接
							</view>
						</view>
					</view>
				</view>
			</view>
		</popup-view>
	</custom-navbar-page>
</template>

<script>
	import { mathAdd,mathMul } from '@/utils/mathUtils.js'
	import { createOrder,boxPickup } from '@/API/order.js'
	// import { delCart } from '@/API/cart.js'
	
	import {
		wechatAppid,
	} from '@/API/login.js'
	import {
		orderShopPaid,createOrderPay
		
	} from '@/API/pay.js'
	export default{
		data(){
			return {
				popupShow:false,
				deliveryFee:0,
				points:"",
				productId:"",
				amount:0,
				skuId:"",
				quantity:"",
				userAddressId:"",
				paidWith:"",//1 繁豆支付  2 现金支付
				totalAmount:"",
				payList:[
					// {label:"支付宝-线路1",type:"ALIPAY",img:require('@/static/shop/zfb.png'),width:'36rpx',height:'36rpx',visible:true},
					{label:"繁豆支付-线路1",type:"POINTS",img:'https://box-mall.oss-cn-hangzhou.aliyuncs.com/static/shopcar/clover.png',width:'40rpx',height:'40rpx',visible:true},
					{label:"微信-线路2",type:"WECHAT",img:'https://box-mall.oss-cn-hangzhou.aliyuncs.com/static/shop/wx.png',width:'36rpx',height:'32rpx',visible:true},
				],
				payIndex:0,
				type:"",
				cartId:"",
				orderDetail:{},
				no:'',
				totalAmount:0
			}
		},
		onLoad(opation) {
			this.recordId = opation.recordId ? opation.recordId : ''
			if(opation.no){
				this.no = opation.no
				this.orderDetail.no = opation.no
				this.orderDetail.id = opation.orderId
				this.totalAmount = Number(opation.totalAmount)
			}
			this.type = opation.type ? opation.type : ''
			this.deliveryFee = opation.deliveryFee
			this.productId = opation.productId
			this.amount = opation.amount ? opation.amount : undefined
			this.cartId = opation.cartId ? opation.cartId : ''
			// this.amount = opation.amount
			this.skuId = opation.skuId
			this.quantity = opation.quantity
			this.userAddressId = opation.userAddressId
			this.points = opation.points
			this.paidWith = opation.paidWith
			// {label:"繁豆支付",type:1,visible:true},{label:"现金支付",type:2,visible:false}
			if(this.paidWith == 1){
				// 繁豆支付
				this.payList = [
					// {label:"支付宝-线路1",type:"ALIPAY",img:require('@/static/shop/zfb.png'),width:'36rpx',height:'36rpx',visible:true},
					{label:"繁豆支付-线路1",type:"POINTS",img:'https://box-mall.oss-cn-hangzhou.aliyuncs.com/static/shopcar/clover.png',width:'40rpx',height:'40rpx',visible:true},
					// {label:"微信-线路2",type:"WECHAT",img:'https://box-mall.oss-cn-hangzhou.aliyuncs.com/static/shop/wx.png',width:'36rpx',height:'32rpx',visible:true},
				]
			}else{
				// 现金支付
				if(this.amount){
					this.mathAdd = mathAdd(this.amount,this.deliveryFee)
				}else{
					this.mathAdd = this.deliveryFee
				}
				
			}
		},
		methods:{
			// 复制
			copy(){
				let val = window.location.href
				uni.setClipboardData({
					data: val
				})
				this.popupClose()
				this.$api.msg('复制成功！')
			},
			popupClose(){
				this.popupShow = false
			},
			// 切换支付方式
			payChange(index){
				this.payList.forEach((v, i) => {
					v.visible = false;
				})
				this.payIndex = index
				this.payList[this.payIndex].visible = !this.payList[this.payIndex].visible
			},
			//方法：用来判断是否是微信内置的浏览器
			isWechat() {
				return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
			},
			// 确认支付
			paySuccess(){
				// if(this.paidWith != 1){
				// 	if(!this.isWechat()){//非微信浏览器
				// 		console.log('请复制链接使用微信浏览，进行支付')
				// 		this.popupShow = true
				// 		return false
				// 	}
				// }
				
				// POINTS, ALIPAY, WECHAT 
				let obj = {}
				if(this.paidWith == 1){
					obj.paidWith = 'POINTS'
					obj.points = this.points
				}else{
					obj.paidWith = this.payList[this.payIndex].type
					obj.amount = this.mathAdd
				}
				obj.productId = this.productId
				obj.skuId = this.skuId
				obj.quantity = this.quantity
				obj.userAddressId = this.userAddressId
				obj.openid = JSON.parse(uni.getStorageSync('userInfo')).openid
				console.log("obj:",obj)
				uni.showLoading()
				if(this.type === 'warehouse'){
					obj.recordId = this.recordId
					boxPickup(obj).then(res => {
						uni.hideLoading()
						if(res.code === 200){
							console.log("res.data:",res.data)
							this.orderDetail = res.data
							if(this.cartId){
								// delCart(`?ids=${this.cartId}`).then(res => {
								// 	uni.hideLoading()
								// 	console.log(res)
								// 	this.$api.msg(res.message)
									
								// }).catch(err => {
								// 	uni.hideLoading()
								// })
							}
								this.pay(this.orderDetail.deliveryFee)
						}else{
							this.$api.msg(res.message)
						}
					}).catch(err => {
						uni.hideLoading()
					})
				}else{
					if(this.no){
						this.pay(this.totalAmount)
					}else{
						createOrder(obj).then(res => {
							uni.hideLoading()
							if(res.code === 200){
								this.orderDetail = res.data
								if(this.cartId){
									// delCart(`?ids=${this.cartId}`).then(res => {
									// 	uni.hideLoading()
									// 	console.log(res)
									// 	this.$api.msg(res.message)
										
									// }).catch(err => {
									// 	uni.hideLoading()
									// })
								}
								if(res.data.status === 'WAIT_FOR_PAYMENT'){
									this.pay(this.orderDetail.totalAmount)
								}else{
									console.log("aaa")
									uni.redirectTo({
																	 // url:`/pages/shop/paySuccess?id=${this.orderDetail.id}&no=${this.orderDetail.no||this.orderDetail.orderNo}`
																	url:`/pages/shop/paySuccess?id=${this.orderDetail.id}&no=${this.orderDetail.no}`
									})
								}
									// this.pay(this.orderDetail.totalAmount)
							}else{
								this.$api.msg(res.message)
							}
						}).catch(err => {
							uni.hideLoading()
						})
					}
				}
			},
			
			pay(totalAmount) {
				let that = this;
				uni.showLoading()
				wechatAppid({type:'jsapi'}).then(result => {
					console.log("result")
					uni.hideLoading()
					if(totalAmount === 0){
						if(this.type){
							 uni.redirectTo({
								url:`/pages/shop/paySuccess?id=${this.orderDetail.id}&no=${this.no}&type=${this.type}`
								// url:`/pages/shop/paySuccess?id=${this.orderDetail.id}&no=${this.orderDetail.no||this.orderDetail.orderNo}&type=${this.type}`
							 })
						}else{
							 uni.redirectTo({
								 // url:`/pages/shop/paySuccess?id=${this.orderDetail.id}&no=${this.orderDetail.no||this.orderDetail.orderNo}`
								url:`/pages/shop/paySuccess?id=${this.orderDetail.id}&no=${this.no}`
							 })
						}
					}else{
						let data = {
							payType:"wechat_v3_jsapi",
							wechatPayTradeType:"JSAPI",
							openid:JSON.parse(uni.getStorageSync('userInfo')).openid,
							userId:JSON.parse(uni.getStorageSync('userInfo')).id,
							// 需乘100
							totalFee:mathMul(totalAmount,100),
							// totalFee:1,
							// totalFee:that.formData.paidAmount,
							orderNo:that.orderDetail.no || that.orderDetail.orderNo,
							description:"蜜丫妈妈-商品购买"
						}
						createOrderPay(data).then(res => {
							uni.hideLoading()
							if (res.code === 200) {
								console.log(res)
								let payObj = {
									appId:res.data.appid,
									timeStamp:res.data.timestamp,
									nonceStr:res.data.nonceStr,
									package:res.data.packages,
									signType:res.data.signType,
									paySign:res.data.paySign
								}
								// #ifdef H5
								if (typeof WeixinJSBridge === 'undefined') {
									// that._paying = false;
								} else {
									WeixinJSBridge.invoke(
										'getBrandWCPayRequest', payObj,
										(payres) => {
											if (payres.err_msg === "get_brand_wcpay_request:ok") {
												uni.showLoading()
												 that.timer = setInterval(() => {
													 console.log("success:", payres)
													 console.log("that.orderDetail:",that.orderDetail)
													 orderShopPaid({no:that.orderDetail.no || that.orderDetail.orderNo}).then(payResult => {
														 if(payResult.data){
															 clearInterval(that.timer);　　// 清除定时器
															 that.timer = null;
															 that.$api.msg("支付成功")
															 uni.hideLoading()
															 let nono = that.orderDetail.orderNo ? that.orderDetail.orderNo : that.orderDetail.no
															 if(that.type){
																 uni.redirectTo({
																	 // url:`/pages/shop/paySuccess?id=${that.orderDetail.id}&no=${that.orderDetail.orderNo || that.orderDetail.no}&type=${that.type}`
																 	url:`/pages/shop/paySuccess?id=${that.orderDetail.id}&no=${nono}&type=${that.type}`
																 })
															 }else{
																 uni.redirectTo({
																 	// url:`/pages/shop/paySuccess?id=${that.orderDetail.id}&no=${that.orderDetail.orderNo || that.orderDetail.no}`
																	url:`/pages/shop/paySuccess?id=${that.orderDetail.id}&no=${nono}`
																 })
															 }
															 
														 }
													 }).catch(err => {
														 clearInterval(that.timer);　　// 清除定时器
														 that.timer = null;
														 uni.hideLoading()
													 })
												 },3000); 
												// if(JSON.stringify(_that.payPage) != "{}"){
												// 	//循环执行，每隔2秒钟执行一次 1000
												// 	 // _that.timer = setInterval(() => {
												// 		//  _that.getSystemcreatePaymentOrder()
												// 	 // },2000);  
												// }else{
												// 	// _that._paying = false;
												// 	// _that.emitOk();
												// }
											} else {
												clearInterval(that.timer);　　// 清除定时器
												that.timer = null;
												console.log("err:",payres)
											}
										});
								}
								// #endif
							}
						}).catch(err => {
							uni.hideLoading()
						})
					}
					
				}).catch(err => {
					uni.hideLoading()
				})
				
				
					
				
			}
		}
	}
</script>

<style lang="scss">
	.cashier-page{
		height: 100vh;
		background-color: #F0F1F5;
		padding-bottom: 140rpx;
		.header{
			background-color: #fff;
			padding: 79rpx 0 68rpx 0;
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;
			.clover-img{
				width: 124rpx;
				height: 124rpx;
				margin-bottom: 24rpx;
			}
			.header-title{
				font-size: 28rpx;
				color: #000000;
			}
			.header-price{
				display: flex;
				align-items: center;
				color: #000000;
				font-weight: 800;
				.header-sym{
					font-size: 44rpx;
				}
				.price{
					font-size: 64rpx;
				}
			}
		}
		.pay-type{
			padding: 48rpx 32rpx 32rpx 32rpx;
			font-size: 28rpx;
			color: #000000;
			font-weight: bold;
		}
		.pay-item{
			width: 100%;
			height: 100rpx;
			background-color: #fff;
			margin-bottom: 20rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 32rpx;
			.item-info{
				display: flex;
				align-items: center;
				justify-content: center;
				.pay-img{
					
				}
				.pay-label{
					font-size: 28rpx;
					color: #333333;
					font-weight: bold;
					margin-left: 20rpx;
				}
			}
			.pay-select{
				width: 28rpx;
				height: 28rpx;
			}
		}
		.confirm-pay{
			position: fixed;
			bottom: 24rpx;
			width: 686rpx;
			left: 32rpx;
			height: 100rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #000000;
			font-size: 32rpx;
			font-weight: 800;
			background-color: #70E3DE;
			border-radius: 50rpx;
		}
		.popup-content{
			width: 620rpx;
			height: 344rpx;
			background-color: #fff;
			border-radius: 16rpx;
			.popup-cancel{
				padding-top: 60rpx;
				text-align: center;
				.cancel-sub{
					margin-top: 30rpx;
				}
			}
			
			.cancel-op{
				margin-top: 40rpx;
				display: flex;
				align-items: center;
				justify-content: space-around;
				.popup-btn{
					width: 400rpx;
					height: 80rpx;
					border-radius: 40rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					border: 1rpx solid #979797 !important;
					margin: 0 !important;
					padding: 0 !important;
					background-color: transparent !important;
				}
				.popup-btn-cofirm{
					color: #979797;
				}
				.popup-btn-cancel{
					color: #70E3DE !important;
				}
			}
			.popup-refund{
				padding-top: 80rpx;
				text-align: center;
			}
		}
	}
</style>