<template>
	<view class="pay">

		<view class="pay-info">
			<view class="goods-info">
				<image class="goods-img" :src="createQuery.postImageUrl" mode=""></image>

				<view class="info">
					<view class="goods-name">
						{{createQuery.movieName}}
					</view>
					<view class="time">
						{{$u.timeFormat(createQuery.sessionBeginTime,'yyyy-mm-dd hh:MM')}}
					</view>
					<view class="desc">
						{{createQuery.seatNames}}
						
					</view>
					<view class="price">
						￥{{totalPrice}} <view class="include">
							（{{createQuery.seatNames.split(',').length}}张电影票）
						</view>
					</view>
				</view>
			</view>

			

			<view class="coupon">
				<view class="label">
					优惠券
				</view>
				<view class="choose-coupon" :class="[payInfo.offset?'':'none']" @click="choose">
					<!-- {{payInfo.goodsCouponName}}-￥{{payInfo.offset}} -->
					{{payInfo.offset?('-￥' + 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">
					¥ {{totalPrice}}
				</view>
				<view class="originPrice">
					原价¥ {{totalOriginPrice}}
				</view>
			</view>

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

	</view>
</template>

<script>
	import {
		calculate
	} from '@/api/order.js';

	import {create_order} from '@/api/movie.js'
	import {
		creatPayOrder,
		queryPayOrder,
		payDetails
	} from '@/api/payment.js'
	import guid from '@/utils/guid.js'
	export default {
		data() {
			return {
				isVisual:false,//是否是虚拟商品
				loading: false,
				info: {},
				realPay: {
					goodsCouponName: '', //优惠券名
					couponGoodsLogId: '', //优惠券id
					goodsId: '', //商品id
					price: '', //支付价格
					offset: '', //实际抵扣值
					discount: '', //优惠券值
					condition: '', //优惠条件
					originalPrice: '', //原价
				},
				price:0,//显示价格
				form:{
					account:''
				},
				rules: {
					'account': {
						type: 'string',
						required: true,
						message: '请输入充值账号',
						trigger: ['blur', 'change']
					},
				},
				query: {
					"msgType": "wx.unifiedOrder",
					"orderDesc": "测试",
					"orderNo": "",
					"subOpenId": "",
					"userId": ""
				},
				createQuery:{
					"channel":"ZhongShu",
					"sessionId": "",//场次ID
					"cityId": "",//城市ID
					"cinemaId": "",//影院ID
					"movieId": "",//电影ID
					"cinemaCode": "",
					"movieCode": "",
					"cityName": "",//城市名称
					"cinemaName": "",//影院名称
					"hallName": "",//影厅名称
					"movieName": "",//电影名称
					"seatNames": "",//座位名称（多个用逗号分隔）
					"postImageUrl": "",
					"cinemaAddress": "",//影院地址
					"sessionBeginTime": "",//开场时间
					"sessionEndTime": "",
					"movieVersion": "",
					"userMobile": "",
					// "cinemaLat": 0,
					// "cinemaLng": 0,
					// "audience": "",
					// "entPara": "",
					originPrice:[],
					"buyModel": 0,
					"originalSeatIds": "",//座位id，多个座位用逗号分隔
					"sourceId": ""
				},
				// 支付信息
				payData: {

				}
			}
		},
		computed: {
			// 正式支付时的信息
			payInfo() {
				return {
					goodsCouponName: this.realPay.goodsCouponName || '', //优惠券名
					couponGoodsLogId: this.info.couponId, //优惠券id
					goodsId: this.realPay.goodsId || this.info.goodsId, //商品id
					price: this.realPay.price, //支付价格
					offset: this.realPay.offset, //实际抵扣值
					discount: this.realPay.discount || 0, //优惠券值
					condition: this.realPay.condition || '', //优惠条件
					originalPrice: this.realPay.originalPrice, //原价
				}
			},
			totalPrice(){
				let total = 0
				if(this.price.length){
					this.price.map(item=>{
						total+=item*10000
					})
				}
				return total/10000
			},
			totalOriginPrice(){
				let total = 0
				if(this.createQuery.originPrice.length){
					this.createQuery.originPrice.map(item=>{
						total+=item*10000
					})
				}
				return total/10000
			},
		},
		methods: {
			calculate(goodsId, shopId) {
				return new Promise((resolve, reject) => {
					calculate({
						couponId: this.info.couponId,
						"goodsId": goodsId,
						"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,
					success: function(res) {
						// 通过eventChannel向被打开页面传送数据
						res.eventChannel.emit('pay', that.info)
					}
				})
			},
			//创建订单
			creat() {
				if (this.loading) return
					
					this.loading = true
					uni.showLoading({
						title: '支付中'
					})
					let that = this
					if (!this.payData.timeStamp) {
						let createQuery = JSON.parse(JSON.stringify(this.createQuery))
						createQuery.originPrice = Math.max.apply(null,createQuery.originPrice)
						create_order(createQuery).then(res => {
							this.loading = false
							if (res.state == 'Success') {
								// if (!this.payInfo.price) { //价格为0
								// 	uni.hideLoading()
								// 	uni.reLaunch({
								// 		url: '/my/order/index'
								// 	})
								// } else {
									this.query.orderNo = res.content.orderNo
									this.query.subOpenId = JSON.parse(uni.getStorageSync('userInfo')).openId
									this.query.orderDesc = this.createQuery.movieName +'电影票'
									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);
												that.loading = false
												uni.hideLoading()
												uni.showToast({
													title: '取消支付',
													icon: 'fail'
												})
												// 取消支付后
												uni.reLaunch({
													url:'/my/order/movie/detail?id='+that.query.orderNo
												})
												// // 取消支付后，获取支付信息以备再次支付
												// payDetails(that.query.orderNo).then(r => {
												// 	if (r.state == 'Success') {

												// 	}
												// })
											}
										})

									})
								// }

							}
						})
					} else { // 取消支付后再次支付
						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);
								queryPayOrder(that.query.orderNo).then(res1 => {
									if (res1.state == 'Success') {
										uni.hideLoading()
										uni.reLaunch({
											url: '/my/order/index'
										})
									}
								})
							},
							fail(e) {
								that.loading = false
								uni.hideLoading()
								uni.showToast({
									title: '取消支付',
									icon: 'fail'
								})
								// 取消支付后，获取支付信息以备再次支付
								payDetails(that.query.orderNo).then(r => {
									if (r.state == 'Success') {
										that.payData = JSON.parse(r.content.miniPayRequest)
									}
								})
								console.log('err', e);
							}
						})
					}
			}

		},
		onReady() {
			
		},
		onLoad() {
			let userInfo = JSON.parse(uni.getStorageSync('userInfo'))
			this.query.userId = userInfo.userId
			let that = this
			const eventChannel = this.getOpenerEventChannel();
			eventChannel.on('pay', function(data) {
				that.createQuery.sessionId = data.sessionId
				that.createQuery.cityId = data.cityId
				that.createQuery.cinemaId = data.cinemaId
				that.createQuery.movieId = data.movieId
				that.createQuery.movieCode = data.movieCode
				that.createQuery.cityName = data.cityName
				that.createQuery.cinemaName = data.cinemaName
				that.createQuery.hallName = data.hallName
				that.createQuery.movieName = data.movieName
				that.createQuery.seatNames = data.seatNames
				that.createQuery.cinemaAddress = data.cinemaAddress
				that.createQuery.sessionBeginTime = data.sessionBeginTime
				that.createQuery.sessionEndTime = data.sessionEndTime
				that.createQuery.originalSeatIds = data.originalSeatIds
				that.createQuery.cinemaCode = data.cinemaCode
				
				that.createQuery.postImageUrl = data.postImageUrl
				that.createQuery.originPrice = data.originPrice 
				that.price = data.price 

				console.log('data', data);
				// that.calculate(that.info.goodsId, that.info.shopId)
			})
		}
	}
</script>

<style lang="scss">
	.pay {
		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;

			.goods-info {
				display: flex;
				margin-bottom: 30rpx;

				.goods-img {
					width: 160rpx;
					height: 200rpx;
					border-radius: 16rpx;
				}

				.info {
					margin-left: 20rpx;
					flex: 1;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					.goods-name {
						font-weight: 600;
						font-size: 28rpx;
						color: #222222;
						width: 400rpx;
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
					}
					.time{
						font-weight: 300;
						font-size: 24rpx;
						color: #AAAAAA;
					}
					.desc{
						font-weight: 300;
						font-size: 24rpx;
						color: #AAAAAA;
					}
					.price{
						display: flex;
						font-size: 24rpx;
						color: rgba(255, 77, 58, 1);
						.include{
							color: #AAAAAA;
							margin-left: 10rpx;
						}
					}
				}
			}
			
			

			.coupon {
				display: flex;
				align-items: center;
				justify-content: space-between;
				border-top: 1rpx solid #F0F0F0;
				padding: 28rpx 0 0;

				.label {
					color: #222222;
					font-size: 28rpx;
				}
				
				.choose-coupon.none{
					color: #AAAAAA;
				}
				.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;
					}
				}
			}
		}
		
		.input-box{
			margin: 20rpx 30rpx;
			padding: 28rpx 24rpx;
			background: #FFFFFF;
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			.label {
				color: #222;
				font-size: 28rpx;
			}
			
			.value {
				font-size: 28rpx;	
				color: #AAAAAA;
			}
		}

		.btn-box {
			position: fixed;
			bottom: 0%;
			left: 0%;
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			box-sizing: border-box;
			padding: 10rpx 30rpx env(safe-area-inset-bottom);
			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;
				}
				.originPrice{
					font-size: 20rpx;
					color: #AAAAAA;
					margin-left: 10rpx;
					text-decoration: line-through;
				}
			}

			.btn {
				width: 280rpx;
				height: 80rpx;
				line-height: 80rpx;
				text-align: center;
				background: $uni-color-primary;
				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>