<template>
	<view class="offlinePayment">

		<view class="shop-info">
			<view class="shop-name">
				{{shopInfo.shopName}}
			</view>
			<view class="address">
				{{shopInfo.address}}
			</view>
		</view>

		<view class="pay-info">
			<view class="title">
				请输入付款金额
			</view>
			<view class="input-box">
				<view class="icon">
					¥
				</view>
				<input class="money-input" v-model.number="shopInfo.price" type="digit" />
			</view>
			<view class="coupon">
				<view class="label">
					优惠券
				</view>
				<view class="choose-coupon" @click="choose">
					{{payInfo.goodsCouponName}}-￥{{payInfo.offset}}
					<image class="icon" src="../static/jiantou-icon.png" mode=""></image>
				</view>
			</view>

			<view class="explain">
				<view class="label">
					优惠说明
				</view>

				<view class="right">
					已优惠： <view class="red">￥{{payInfo.offset}} </view> 合计: <view class="red fs28">￥{{payInfo.price}}
					</view>
				</view>
			</view>

		</view>


		<view class="btn-box">
			<view class="total-price">
				<view class="label">
					合计:
				</view>
				<view class="price">
					¥ {{payInfo.price}}
				</view>
			</view>

			<button class="btn" type="default" :loading="loading" @click="creat">提交订单</button>
		</view>

	</view>
</template>

<script>
	import {
		calculateByInput,
		creatScanOrder
	} from '@/api/order.js';
	import {
		creatPayOrder,
		queryPayOrder,
		close
	} from '@/api/payment.js'
	import {shopDetail} from '@/api/shop.js'
	import guid from '@/utils/guid.js'
	import {debounce} from '@/utils/tool.js'
	export default {
		data() {
			return {
				loading: false,
				shopInfo: {
					shopName:'',
					address:'',
					price:0,
				},
				info: {},
				realPay: {
					goodsCouponName: '', //优惠券名
					couponGoodsLogId: '', //优惠券id
					goodsId: '', //商品id
					price: '', //支付价格
					offset: '', //实际抵扣值
					discount: '', //优惠券值
					condition: '', //优惠条件
					originalPrice: '', //原价
				},
				query: {
					"msgType": "wx.unifiedOrder",
					"orderDesc": "线下扫码支付",
					"orderNo": "",
					"subOpenId": "",
					"userId": ""
				},
				// 支付信息
				payData: {

				}
			}
		},
		computed: {
			// 正式支付时的信息
			payInfo() {
				return {
					goodsCouponName: this.realPay.goodsCouponName || '', //优惠券名
					couponGoodsLogId: this.realPay.couponGoodsLogId || '', //优惠券id
					price: this.realPay.price, //支付价格
					offset: this.realPay.offset, //实际抵扣值
					discount: this.realPay.discount || 0, //优惠券值
					condition: this.realPay.condition || '', //优惠条件
					originalPrice: this.realPay.originalPrice, //原价
				}
			}
		},
		watch: {
			'shopInfo.price':debounce(function(val) {
				if(!val){
					this.shopInfo.price = 0
				}
				this.calculateByInput(this.shopInfo.shopId)
			})
		},
		methods: {
			calculateByInput(shopId) {
				return new Promise((resolve, reject) => {
					calculateByInput({
						couponId: this.info.couponId,
						"price": this.shopInfo.price,
						"shopId": shopId,
						"userId": JSON.parse(uni.getStorageSync('userInfo')).userId
					}).then(res => {
						if (res.state == 'Success') {
							this.realPay = res.content
						}
					})
				})
			},
			choose() {
				let that = this
				uni.navigateTo({
					url: `./coupon?couponId=${this.realPay.couponGoodsLogId}&type=offlinePayment`,
					success: function(res) {
						// 通过eventChannel向被打开页面传送数据
						res.eventChannel.emit('pay', that.shopInfo)
					}
				})
			},
			//创建订单
			creat() {
				if (this.loading) return
				this.loading = true
				if (!this.payInfo.price) { //价格为0
					uni.hideLoading()
					this.loading = false
					return uni.showToast({
						title:'请输入付款金额',
						icon:'none'
					})
				}
				uni.showLoading({
					title: '支付中'
				})
				let that = this
					creatScanOrder({
						discountId: this.payInfo.couponGoodsLogId ? [this.payInfo.couponGoodsLogId] : [],
						extend: "",
						price: this.shopInfo.price,
						shopId: this.shopInfo.shopId
					}).then(res => {
						this.loading = false
						if (res.state == 'Success') {
								this.query.orderNo = res.content.orderNo
								this.query.subOpenId = JSON.parse(uni.getStorageSync('userInfo')).openId
								creatPayOrder(this.query).then(data => {
									that.payData = JSON.parse(data.content.miniPayRequest)
									if(data.content.miniPayRequest == null) return uni.hideLoading()
									uni.requestPayment({
										"provider": "wxpay",
										"orderInfo": that.payData,
										"appid": that.payData.appId, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
										"paySign": that.payData.paySign,
										"nonceStr": that.payData.nonceStr, // 随机字符串
										"package": that.payData.package, // 固定值
										// "prepayid":  that.payData.package, // 统一下单订单号 
										"timeStamp": that.payData.timeStamp, // 时间戳（单位：秒）
										"signType": that.payData.signType, //签名算法
										success(msg) {
											console.log('msg', msg,res);
											queryPayOrder(that.query.orderNo).then(res1 => {
												if (res1.state == 'Success') {
													uni.hideLoading()
													uni.reLaunch({
														url: '/my/order/index'
													})
												}
											})
										},
										fail(e) {
											console.log('err', e);
											// 取消支付后，直接关闭订单
											close(that.query.orderNo).then(res=>{
												if (res.state == 'Success') {
													that.loading = false
													uni.hideLoading()
													uni.showToast({
														title: '取消支付',
														icon: 'fail'
													})
												}
											})
										}
									})
			
								})
			
						}
					})
			},
			shopDetail(shopId){
				shopDetail({shopId}).then(res=>{
					if (res.state == 'Success') {
						this.shopInfo.shopName = res.content.shopName
						this.shopInfo.address = res.content.address
					}
				})
			}

		},
		onLoad(options) {
			let that = this
			this.shopInfo.shopId = decodeURIComponent(options.scene)
			
			this.shopDetail(this.shopInfo.shopId)
			if(!uni.getStorageSync('token')){
				return uni.showModal({
					title:'请登录',
					confirmText:'去登录',
					success(res){
						console.log(res);
						if(res.confirm){
							uni.navigateTo({
								url:`/login/login/login?redirect=/pay/offlinePayment&scene=${that.shopInfo.shopId}`
							})
						}
					}
				})
			}
			let userInfo = JSON.parse(uni.getStorageSync('userInfo'))
			this.query.userId = userInfo.userId
			this.calculateByInput(this.shopInfo.shopId)
			const eventChannel = this.getOpenerEventChannel();
			if(JSON.stringify(eventChannel) !=='{}'){
				eventChannel.on('pay', function(data) {
					that.shopInfo = data
				})
			}
				
			
		}
	}
</script>

<style lang="scss" scoped>
	.offlinePayment {
		background: #F9F9F9;
		min-height: 100vh;
		padding-top: 20rpx;

		.shop-info {
			margin: 0 30rpx 20rpx;
			width: 690rpx;
			padding: 24rpx;
			box-sizing: border-box;
			background: #FFFFFF;
			border-radius: 16rpx 16rpx 16rpx 16rpx;

			.shop-name {
				color: #181818;
				font-size: 32rpx;
			}

			.address {
				color: #999999;
				font-size: 24rpx;
				margin-top: 12rpx;
			}
		}

		.pay-info {
			margin: 0 30rpx;
			background: #FFFFFF;
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			padding: 28rpx 24rpx;

			.title {
				font-size: 28rpx;
				color: #222222;
			}

			.input-box {
				position: relative;
				line-height: 98rpx;
				font-size: 36rpx;
				border-bottom: 2rpx solid #f3f3f3;

				.icon {
					position: absolute;
					left: 0%;
					top: 50%;
					transform: translateY(-50%);
				}

				.money-input {
					padding-left: 30rpx;
					width: 100%;
					height: 100rpx;
					line-height: 100rpx;
					box-sizing: border-box;
				}
			}

			.coupon {
				display: flex;
				align-items: center;
				justify-content: space-between;
				border-bottom: 2rpx dashed #f3f3f3;
				padding: 28rpx 0;

				.label {
					color: #222222;
					font-size: 28rpx;
				}

				.choose-coupon {
					color: #FF4848;
					font-size: 28rpx;
					display: flex;
					align-items: center;

					.icon {
						width: 28rpx;
						height: 28rpx;
						display: block;
						margin-left: 10rpx;
					}
				}
			}

			.explain {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding-top: 28rpx;

				.label {
					color: #AAAAAA;
					font-size: 28rpx;
				}

				.right {
					display: flex;
					align-items: center;
					font-size: 24rpx;

					.red {
						font-weight: 500;
						color: #FF4848;
						margin: 0 10rpx;
					}

					.fs28 {
						font-size: 28rpx !important;
					}
				}
			}
		}

		.btn-box {
			position: fixed;
			bottom: 0%;
			left: 0%;
			width: 100%;
			height: 98rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			box-sizing: border-box;
			padding: 0 30rpx;
			border-top: 1rpx solid #EEEEEE;

			.total-price {
				display: flex;
				align-items: center;

				.label {
					color: #181818;
					font-size: 28rpx;
				}

				.price {
					font-size: 36rpx;
					font-weight: 800;
					color: #FF4848;
					margin-left: 10rpx;
				}
			}

			.btn {
				width: 240rpx;
				height: 80rpx;
				line-height: 80rpx;
				text-align: center;
				background: linear-gradient(265deg, #FF4A39 0%, #FC8B45 100%);
				box-shadow: inset 0rpx 6rpx 12rpx 2rpx rgba(255, 255, 255, 0.16);
				border-radius: 46rpx 46rpx 46rpx 46rpx;
				font-weight: 800;
				color: #FFFFFF;
				font-size: 28rpx;
				margin: 0;
			}
		}
	}
</style>