<template>
	<view class="pay">

		<view class="pay-info">
			<view class="goods-info">
				<image class="goods-img" :src="info.goodsPath" mode=""></image>
				<view class="info">
					<view class="goods-name">
						{{ info.goodsName }}
					</view>
					<view class="num">
						{{ info.goodsDescribe }}
					</view>
					<view class="priceColumn">
						<view class="price">
							<text class="unit">￥</text>{{ info.realPrice }}
						</view>
						<view class="goodsNum">
							x{{ realPay.reservePersons.length }}
						</view>
					</view>
				</view>
			</view>

			<view class="setoff">
				<view class="text">
					出发时间
				</view>
				<view class="date">
					{{ reserveTimeFmt }}
				</view>
			</view>
		</view>

		<view class="appointment">
			<view class="title">
				预定人信息
			</view>
			<view class="name">
				<view class="label">
					姓名
				</view>
				<view class="value">
					{{ userInfo.name }}
				</view>
			</view>
			<view class="phone">
				<view class="label">
					手机号
				</view>
				<view class="value">
					<text class="zone">+86</text>{{ userInfo.phoneNum }}
				</view>
			</view>
			<view class="desc">
				预定人信息用于接受验证信息
			</view>
		</view>
		<view class="tour">
			<view class="title-top">
				<view class="title-text">
					出游人信息
				</view>
				<view @click="addNewTourPerson" class="add">
					+添加
				</view>
			</view>
			<view v-for="(item, index) in realPay.reservePersons" :key="index" class="info-card">
				<view class="user-name">
					{{ item.userName }}
					<view class="tag">
						出行人{{ index + 1 }}
					</view>
				</view>
				<view class="card-info">
					身份证：{{ item.idCard }}
				</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>
		<uni-calendar ref="calendar" :lunar="true" :showMonth="true" style="z-index: 999;" :insert="false"
			@confirm="confirm" />
	</view>
</template>

<script>

import {
	studyCalculate, saveReserve
} from '@/api/order.js';
import {
	creat
} from '@/api/goods.js'
import {
	creatPayOrder,
	queryPayOrder,
	payDetails
} from '@/api/payment.js'
import { studyOrderCreat } from '@/api/study.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: '', //原价
				reserveName: '',//预定人
				reservePhone: '',//预定人手机
				reserveTime: '',//预定时间
				reservePersons: [],//出游人
			},
			form: {
				account: ''
			},
			rules: {
				'account': {
					type: 'string',
					required: true,
					message: '请输入充值账号',
					trigger: ['blur', 'change']
				},
			},
			query: {
				"msgType": "wx.unifiedOrder",
				"orderDesc": "测试",
				"orderNo": "",
				"channel": 'ZhongShu',
				"subOpenId": "",
				"userId": ""
			},
			// 支付信息
			payData: {

			},
			userInfo: {}
		}
	},
	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, //原价
			}
		},
		reserveTimeFmt() {
			const date = new Date(this.info.reserveTime)
			// const year = date.getFullYear()
			const month = date.getMonth() + 1
			const day = date.getDate()
			return `${month}月${day}日`
		}
	},
	methods: {
		// 增加新的出游人
		addNewTourPerson() {
			uni.navigateTo({
				url: '/study/tourList/list'
			})
		},
		openCalendar() {
			this.$refs.calendar.open();
		},
		confirm(e) {
			console.log(e);
		},
		calculate(goodsId, shopId) {
			uni.showLoading({
				title: '计算中'
			})
			return new Promise((resolve, reject) => {
				studyCalculate({
					couponId: this.info.couponId,
					"goodsId": goodsId,
					"shopId": shopId,
					"userId": JSON.parse(uni.getStorageSync('userInfo')).userId,
					"number": this.realPay.reservePersons.length
				}).then(res => {
					uni.hideLoading()
					if (res.state == 'Success') {
						const reservePersons = this.realPay.reservePersons
						this.realPay = res.content
						this.realPay.reservePersons = reservePersons
						this.info.couponId = res.content.couponId
					}
				})
			})
		},
		choose() {
			let that = this
			uni.navigateTo({
				url: './coupon?couponId=' + this.realPay.couponLogId,
				success: function (res) {
					// 通过eventChannel向被打开页面传送数据
					res.eventChannel.emit('pay', that.info)
				}
			})
		},
		tempCreate() {
			uni.reLaunch({
				url: '/study/pay/orderPay'
			})
		},
		//创建订单
		creat() {
			if (this.loading) return

			if (this.realPay.reservePersons.length == 0) {
				uni.showToast({
					title: '请添加出游人',
					icon: 'none'
				})
				return
			}

			const user = JSON.parse(uni.getStorageSync('userInfo'))
			this.realPay.reserveName = user.name
			this.realPay.reservePhone = user.phoneNum
			this.realPay.reserveTime = this.info.reserveTime

			this.loading = true
			uni.showLoading({
				title: '支付中'
			})
			let that = this
			if (!this.payData.timeStamp) {
				// 处理扩展字段  暂时只有研学商品和视频会员  视频会员是字符串的JSON  研学是字符串
				let extend
				try {
					if (JSON.parse(this.info.extend)) {
						extend = this.info.extend
					}
				} catch (e) {
					extend = this.info.reservationTime || ''
				}

				studyOrderCreat({
					discountId: (this.payInfo.couponGoodsLogId || this.payInfo.couponGoodsLogId == -1) ? [this
						.payInfo.couponGoodsLogId
					] : [],
					extend,
					channel: 'ZhongShu',
					goodsList: this.info.goodsId ? [this.info.goodsId] : [],
					idempotent: guid(),
					reserveTime: this.info.reserveTime,
					shopId: this.info.shopId
				}).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.info.goodsName
							creatPayOrder(this.query).then(data => {
								that.payData = JSON.parse(data.content.miniPayRequest)
								if (data.content.miniPayRequest == null) return uni.hideLoading()
								saveReserve({
									...this.realPay,
									orderNo: this.query.orderNo,
									goodsId: this.info.goodsId,
								}).then(res => {
									if (res.state == 'Success') {
										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', that.query.orderNo);
												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'
												})
												// 取消支付后，获取支付信息以备再次支付
												payDetails(that.query.orderNo).then(r => {
													if (r.state == 'Success') {
														that.payData = JSON.parse(r.content.miniPayRequest)
													}
												})
											}
										})
									} else {
										uni.showToast({
											title: res.msg,
											icon: 'none'
										})
										that.loading = false
									}
								})
							})
						}

					}
				})
			} 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
		this.userInfo = userInfo
		let that = this
		const eventChannel = this.getOpenerEventChannel();
		eventChannel.on('pay', function (data) {
			that.info = data
			try {
				let extend = JSON.parse(that.info.extend)
				if (extend.account) {
					that.isVisual = true
					that.form.account = extend.account
				}
			} catch (e) {
				//TODO handle the exception
			}
			console.log('data', data);
			// that.calculate(that.info.goodsId, that.info.shopId)
		})
		uni.$on("updateData", (data) => {
			this.realPay.reservePersons = data
			that.calculate(that.info.goodsId, that.info.shopId)
			this.$forceUpdate()
		})
	},
	destoryed() {
		uni.$off("updateData")
	}
}
</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: 24rpx;

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

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

			.info {
				margin-left: 28rpx;
				flex: 1;

				.goods-name {
					font-weight: bold;
					color: #181818;
					font-size: 32rpx;
					width: 100%;
					word-break: break-all;
					text-overflow: ellipsis;
					overflow: hidden;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
					/* 这里是超出几行省略 */
				}

				.num {
					color: #999999;
					font-size: 24rpx;
					margin-top: 16rpx;
				}

				.priceColumn {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-top: 30rpx;

					.price {
						font-weight: bold;
						color: #FF4D3A;
						font-size: 32rpx;

						.unit {
							font-size: 20rpx;
						}
					}

					.goodsNum {
						font-size: 24rpx;
						color: #AAAAAA;
					}

				}

			}
		}

		.setoff {
			border-top: 1px solid #F0F0F0;
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 24rpx;
			padding-top: 24rpx;

			.text {
				color: #222222;
			}

			.date {
				color: #AAAAAA;
			}
		}
	}

	.appointment {
		padding: 24rpx;
		background: #FFFFFF;
		margin: 20rpx 30rpx;
		border-radius: 16rpx 16rpx 16rpx 16rpx;

		.title {
			font-size: 28rpx;
			color: #222222;
			font-weight: bold;
			margin-bottom: 24rpx;
		}

		.name {
			border-top: 1px solid #F0F0F0;
			padding: 24rpx 0;
			display: flex;

			.label {
				font: 24rpx;
				color: #222222;
				width: 152rpx;
			}

			.value {
				font-size: 28rpx;
				font-weight: bold;
			}
		}

		.phone {
			border-top: 1px solid #F0F0F0;
			padding: 24rpx 0;
			display: flex;

			.label {
				font: 24rpx;
				color: #222222;
				width: 152rpx;
			}

			.value {
				font-size: 28rpx;
				font-weight: bold;

				.zone {
					padding-right: 22rpx;
					margin-right: 20rpx;
					border-right: 1px solid #F0F0F0;
				}
			}
		}

		.desc {
			border-top: 1px solid #F0F0F0;
			padding-top: 24rpx;
			color: #AAAAAA;
			font-size: 24rpx;
		}
	}

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

		.title-top {
			display: flex;
			justify-content: space-between;
			align-items: center;

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

			.add {
				font-size: 24rpx;
				color: #3B83FF;
			}

			margin-bottom: 24rpx;
		}

		.info-card {
			border-top: 1px solid #F0F0F0;
			padding: 24rpx 0;

			.user-name {
				font-size: 28rpx;
				font-weight: bold;
				color: #222222;
				display: flex;
				align-items: center;

				.tag {
					margin-left: 20rpx;
					color: #222222;
					font-size: 20rpx;
					background-color: #F0F0F0;
					border-radius: 18rpx;
					line-height: 20rpx;
					padding: 2rpx 12rpx;
				}
			}

			.card-info {
				margin: 20rpx 0;
				font-size: 24rpx;
				color: #222222;
			}
		}

	}


	.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;
			}
		}

		.btn {
			width: 280rpx;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background: #3B83FF;
			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>