<template>
	<view class="scenic-makeOut">
		<u--form
			labelPosition="left"
			:model="form"
			ref="uForm"
			labelWidth="150rpx"
			>
			<view class="content info">
				<view class="title">
					{{ticketInfo.productName}}
				</view>
				<view class="notice" @click="showNotice = true">
					<view class="text">
						预定须知 
					</view>
					<image class="jiantou" src="../static/right.png" mode=""></image>
				</view>
				<u-form-item
						label="出游日期"
						borderBottom
						ref="startTime"
						required
						prop="startTime"
				>
					<view class="time-box" @click="chooseTime">
						{{form.startTime}}
						<image class="right-icon" src="../static/right.png" mode=""></image>
					</view>
				</u-form-item>
				<view class="signUp-box">
					<view class="label-box">
						<view class="label">
							预订数量
						</view>
						<view class="desc">
							（最多10张）
						</view>
					</view>
					<view class="num-box">
						<view class="btn" :class="[form.bookNumber == 1?'disabled':'']" @click="add(-1)">
							-
						</view>
						<view class="num">
							{{form.bookNumber}}
						</view>
						<view class="btn" :class="[form.bookNumber == 10?'disabled':'']" @click="add(1)">
							+
						</view>
					</view>
				</view>
			</view>
			
			<view class="content ">
				<view class="sub-title">
					取票人信息
				</view>
				<u-form-item
						label="姓名"
						borderBottom
						ref="item1"
						prop="contact.contactName"
						required
				>
					<u--input
							v-model="form.contact.contactName"
							border="none"
							placeholder="请输入姓名"
					></u--input>
				</u-form-item>
				<u-form-item
						label="手机号"
						borderBottom
						ref="item1"
						prop="contact.contactTel"
						required
				>
					<u--input
							v-model="form.contact.contactTel"
							border="none"
							:maxlength="11"
							placeholder="请输入手机号"
					></u--input>
				</u-form-item>
				<u-form-item
						label="邮箱"
						borderBottom
						ref="item1"
						prop="contact.contactEmail"
						required
						v-if="ticketInfo.admissionVoucher.admissionVoucherCode == 205 || ticketInfo.admissionVoucher.admissionVoucherCode == 302"
				>
					<u--input
							v-model="form.contact.contactEmail"
							border="none"
							placeholder="请输入邮箱号"
					></u--input>
				</u-form-item>
				<u-form-item
						label="证件类型"
						borderBottom
						ref="item1"
						:required="showContact"
						v-if="showContact"
				>
					<view class="time-box" @click="chooseType('取票')">
						{{form.contact.psptType | filterType(that)}}
						<image class="right-icon" src="../static/right.png" mode=""></image>
					</view>
				</u-form-item>
				<u-form-item
						label="证件号"
						ref="item1"
						prop="contact.psptId"
						:required="showContact"
						v-if="showContact"
				>
					<u--input
							v-model="form.contact.psptId"
							border="none"
							placeholder="请输入证件号"
							:maxlength="18"
					></u--input>
				</u-form-item>
			</view>
			
			<template v-if="required">
				
				<view class="content" v-for="(item,index) in form.touristList" :key="item">
					<view class="sub-title">
						出游人信息
					</view>
					<view class="no">
						第{{index+1}}位
					</view>
					<u-form-item
							label="姓名"
							borderBottom
							:ref="'touristList'+index+'name'"
							:prop="`touristList.${index}.name`"
							:required="required"
					>
						<u--input
								v-model="item.name"
								border="none"
								placeholder="请输入姓名"
						></u--input>
					</u-form-item>
					<u-form-item
							label="手机号"
							borderBottom
							:ref="'touristList'+index+'tel'"
							:prop="'touristList.'+index+'.tel'"
							:required="required"
					>
						<u--input
								v-model="item.tel"
								border="none"
								:maxlength="11"
								placeholder="请输入手机号"
						></u--input>
					</u-form-item>
					<u-form-item
							label="证件类型"
							borderBottom
							ref="item13"
							prop="name"
							:required="idRequired"
							v-if="idRequired"
					>
						<view class="time-box" @click="chooseType(index)">
							{{item.psptType | filterType(that)}}
							<image class="right-icon" src="../static/right.png" mode=""></image>
						</view>
					</u-form-item>
					<u-form-item
							label="证件号"
							ref="item14"
							:ref="'touristList'+index+'psptId'"
							:prop="'touristList.'+index+'.psptId'"
							:required="idRequired"
							v-if="idRequired"
					>
						<u--input
								v-model="item.psptId"
								border="none"
								placeholder="请输入证件号"
								:maxlength="18"
						></u--input>
					</u-form-item>
				</view>
			</template>
			
		</u--form>
		
		<view class="btn-box">
			<view class="left">
				<view class="num">
					共{{form.bookNumber}}件
				</view>
				<view class="total">
					合计 <view class="price-box">
						<view class="unit">
							￥
						</view>
						<view class="price">
							{{total}}
						</view>
					</view>
				</view>
			</view>
			<button class="btn" @click="handleBuy" :loading="loading">
				提交订单
			</button>
		</view>
		
		<u-calendar
			confirmDisabledText="请选择日期"
			:show="show" 
			@confirm="confirmTime"
			@close="show = false"
			ref="calendar"
			:rowHeight="120"
			closeOnClickOverlay
			color="#EE4320"
			:customList="ticketInfo.priceCalendar"
			:monthNum="12"
		>
		</u-calendar>
		
		 <u-picker :show="show1" :columns="columns" closeOnClickOverlay keyName="label" @cancel="close" @close="close" @confirm="confirm"></u-picker>
		 
		 <!-- 预定须知 -->
		 <u-popup :show="showNotice" round="16rpx" mode="bottom" @close="showNotice = false">
		 	<view class="popup-title">
		 		{{ticketInfo.shopName}}
		 	</view>
		 	<view class="box">
		 		<template v-if="ticketInfo.drawAddress">
		 			<view class="sub-title">
		 				取票地点
		 			</view>
		 			<view class="intro">
		 				{{ticketInfo.drawAddress}}
		 			</view>
		 		</template>
		 		<view class="sub-title">
		 			入园方式
		 		</view>
		 		<view class="intro">
		 			{{ticketInfo.admissionVoucher.admissionVoucherCode | filterVoucherType}}
		 		</view>
		 		<view class="sub-title">
		 			有效期
		 		</view>
		 		<view class="intro">
		 			{{ticketInfo.indate || '-'}}
		 		</view>
		 		<view class="sub-title">
		 			预定截止
		 		</view>
		 		<view class="intro">
		 			{{ticketInfo.advanceDay}}天 {{ticketInfo.advanceHour}}小时
		 		</view>
		 		<view class="sub-title">
		 			退改规则
		 		</view>
		 		<rich-text class="intro" :nodes="ticketInfo.mpLossInfo"></rich-text>
		 		<view class="sub-title">
		 			预定须知
		 		</view>
		 		<rich-text class="intro" :nodes="ticketInfo.bookNotice"></rich-text>
		 		<view class="sub-title">
		 			其他说明
		 		</view>
		 		<rich-text class="intro" :nodes="ticketInfo.info"></rich-text>
		 		
		 	</view>
		 </u-popup>
		
	</view>
</template>

<script>
	import {createOrderNew} from '@/api/scenic.js'
	import {
		creatPayOrder,
		queryPayOrder,
	} from '@/api/payment.js'
	export default {
		data() {
			return {
				that:this,
				show:false,
				show1:false,
				showNotice:false,
				loading:false,
				form:{
				  "scenicId":0,
				  "epId":0,
				  "channel":'ZhongShu',
				  "bookNumber": 1,
				  "contact": {
					"contactEmail": "",
					"contactName": "",
					"contactTel": "",
					"psptId": "",
					"psptType": 1
				  },
				  "couponValue": 0,
				  "delivery": {
					"deliveryEndAddress": "",
					"deliveryType": 0,
					"receiverName": "",
					"telNum": "",
					"zipCode": ""
				  },
				  "productId": 0,
				  "startTime": "",
				  "touristList": [
					{
					  "email": "",
					  "name": "",
					  "psptId": "",
					  "psptType": 1,
					  "tel": ""
					}
				  ]
				},
				required:false,//游客信息是否必填
				idRequired:false,//游客身份证信息是否必填
				showContact:false,//取票人信息是否必填
				rules: {
					'startTime':[
						{
							required: true,
							message: '请选择出游日期',
							trigger: ['blur', 'change']
						},
					],
					contact:{
						contactName:[
							{
								required: true,
								message: '请输入姓名',
								trigger: ['blur', 'change']
							},
							
						],
						contactTel:[
							{
								required: true,
								message: '请输入手机号',
								trigger: ['blur', 'change']
							},
							{
								// 自定义验证函数，见上说明
								validator: (rule, value, callback) => {
									// 上面有说，返回true表示校验通过，返回false表示不通过
									// uni.$u.test.mobile()就是返回true或者false的
									return uni.$u.test.mobile(value);
								},
								message: '手机号码不正确',
								// 触发器可以同时用blur和change
								trigger: ['change','blur'],
							}
						],
						contactEmail:[
							{
								required: true,
								message: '请输入取票人邮箱',
								trigger: ['blur', 'change']
							},
							{
								// 自定义验证函数，见上说明
								validator: (rule, value, callback) => {
									// 上面有说，返回true表示校验通过，返回false表示不通过
									// uni.$u.test.mobile()就是返回true或者false的
									return uni.$u.test.email(value);
								},
								message: '邮箱号不正确',
								// 触发器可以同时用blur和change
								trigger: ['change','blur'],
							}
						],
						psptId:[
							{
								required: true,
								message: '请输入证件号码',
								trigger: ['blur', 'change']
							}
						],
					},
					touristList:[]
				},
				ticketInfo:{salePrice:0},
				columns: [
					[
						{
							label: '身份证',
							id: 1
						}, 
						{
							label: '护照',
							id: 2
						},
						{
							label: '军官证',
							id: 3
						},
						{
							label: '港澳通行证',
							id: 4
						},
						{
							label: '台胞证',
							id: 7
						},
						{
							label: '回乡证',
							id: 8
						},
						{
							label: '户口簿',
							id: 9
						},
						{
							label: '出生证明',
							id: 10
						},
						{
							label: '台湾通行证',
							id: 11
						},
					]
				],
				active:0,
				query: {
					"msgType": "wx.unifiedOrder",
					"orderDesc": "",
					"orderNo": "",
					"channel":'ZhongShu',
					"subOpenId": "",
					"userId": ""
				},
				payData:null,
				price:0
			}
		},
		filters: {
			filterType: function(value,that) {
				let msg
				that.columns[0].map(item=>{
					if(value == item.id){
						msg = item.label
					}
				})
				return msg;
			},
			filterVoucherType: function(val) {
				if(val == 1){
					return '实体票入园'
				}else if(val == 201){
					return '换票入园短信'
				}else if(val == 202){
					return '换票入园二维码'
				}else if(val == 203){
					return '换票入园数字码'
				}else if(val == 204){
					return '换票入园换票证'
				}else if(val == 205){
					return '换票入园邮件'
				}else if(val == 206){
					return '换票入园身份证'
				}else if(val == 207){
					return '换票入园护照'
				}else if(val == 208){
					return '换票入园港澳通行证'
				}else if(val == 209){
					return '换票入园军官证'
				}else if(val == 210){
					return '换票入园台胞证'
				}else if(val == 301){
					return '直接验证入园二维码'
				}else if(val == 302){
					return '直接验证入园邮件'
				}else if(val == 303){
					return '直接验证入园身份证'
				}else if(val == 304){
					return '直接验证入园护照'
				}else if(val == 305){
					return '直接验证入园港澳通行证'
				}else if(val == 306){
					return '直接验证入园军官证'
				}else if(val == 307){
					return '直接验证入园台胞证'
				}
			}
		},
		computed: {
			total() {
				if(this.price){
					return this.price*this.form.bookNumber
				}else{
					return this.ticketInfo.salePrice*this.form.bookNumber
				}
			}
		},
		methods: {
			confirmTime(val){
				if(!val.length) return uni.showToast({
					title:'请选择日期',
					icon:'none'
				})
				this.show = false
				this.form.startTime = val[0]
				this.ticketInfo.priceCalendar.forEach(item=>{
					if(item.departDate == val[0]){
						this.price = item.salePrice
					}
				})
				this.$refs.uForm.validateField('startTime')
			},
			confirm(val){
				console.log(val);
				this.show1 = false
				if(this.active == '取票'){
					this.form.contact.psptType = val.value[0].id
				}else{
					this.form.touristList[this.active].psptType = val.value[0].id
				}
			},
			close(){
				console.log(9999);
				this.show1 = false
			},
			chooseTime() {
				this.show = true
			},
			chooseType(index){
				this.show1 = true
				this.active = index
			},
			add(val){
				if((val==-1&&this.form.bookNumber == 1)||(val==1&&this.form.bookNumber == 10)) return
				if(val == 1){
					if(this.required){
						this.form.touristList.push({
						  "email": "",
						  "name": "",
						  "psptId": "",
						  "psptType": 1,
						  "tel": ""
						})
					}
				}else{
					this.form.touristList.pop()
				}
				this.form.bookNumber+=val
				this.setRules()
			},
			handleBuy(){
				this.$refs.uForm.validate().then(res => {
					this.createOrderNew(this.form)
				})
			},
			createOrderNew(query){
				if (this.loading) return
					this.loading = true
					uni.showLoading({
						title: '支付中'
					})
					let that = this
				createOrderNew(query).then(res=>{
					if(res.state == 'Success'){
						this.query.orderNo = res.content.orderNo
						this.query.subOpenId = JSON.parse(uni.getStorageSync('userInfo')).openId
						this.query.orderDesc = this.ticketInfo.productName
						creatPayOrder(this.query).then(data => {
							that.payData = JSON.parse(data.content.miniPayRequest)
							if (data.content.miniPayRequest == null) return uni.hideLoading()
							console.log(666,that.payData);
							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 => {
											uni.hideLoading()
											that.loading = false
										if (res1.state == 'Success') {
											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/scenic/detail?id='+that.query.orderNo
									})
								}
							})
						
						})
						
					}else{
						that.loading = false
						uni.hideLoading()
						uni.hideToast()
						if(res.content.indexOf('不符合资源') != -1){
							uni.showToast({
								title: res.content.split('不符合资源')[0]+'不合法',
								icon: 'none'
							})
						}else{
							uni.showToast({
								title: res.content,
								icon: 'none'
							})
						}
					}
				})
			},
			 setRules() {
				 //custInfoLimit=2,3,6,7这几种类型  游客信息必填  否则直接不填
				 if(this.required){
					  this.form.touristList.forEach((ele, index) => {
						this.$set(this.rules, `touristList.${index}.name`, [
						  {
							required: true,
							message: '请填写姓名',
							trigger: ['blur', 'change']
						  }
						])
						this.$set(this.rules, `touristList.${index}.tel`, [
						  {
							required: true,
							message: '请填写手机号',
							trigger: ['blur', 'change']
						  },
						  {
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								return uni.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change
							trigger: ['change','blur'],
						  }
						])
						if(this.idRequired){
							this.$set(this.rules, `touristList.${index}.psptId`, [
							  {
								required: true,
								message: '请填写证件号码',
								trigger: ['blur', 'change']
							  }
							])
						}
					  })
				 }
				 console.log('rule',this.rules);
					  this.$nextTick(() => {
						this.$refs.uForm.setRules(this.rules)
					  })
			},
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			// this.$refs.uForm.setRules(this.rules)
			this.setRules()
		},
		mounted() {
			// this.setRules()
		},
		onLoad(options) {
			let userInfo = JSON.parse(uni.getStorageSync('userInfo'))
			this.query.userId = userInfo.userId
			this.form.scenicId = options.id
			let that = this
			const eventChannel = this.getOpenerEventChannel();
			eventChannel.on('pay', function(data) {
				that.form.epId = data.epId
				that.ticketInfo = data
				that.ticketInfo.priceCalendar.map(i=>{i.bottomInfo = i.salePrice})
				that.form.productId = data.productId
				// 这几种类型 才需要填写游客信息
				if([2,3,6,7].includes(that.ticketInfo.custInfoLimit)){
					that.required = true
					// 必填游客身份证
					if([3,6].includes(that.ticketInfo.custInfoLimit)){
						that.idRequired = true
					}else{
						that.idRequired = false
					}
				}else{
					that.required = false
					that.form.touristList = []
				}
				
				// 这几种类型 才需要填写取票人证件信息
				if([4,6,7].includes(that.ticketInfo.custInfoLimit)){
					that.showContact = true
				}else{
					that.showContact = false
					delete that.form.contact.psptType
					delete that.form.contact.psptId
				}
				
			})
		}
	}
</script>

<style lang="scss" >
.scenic-makeOut{
	background: #F9F9F9;
	border-radius: 0rpx 0rpx 0rpx 0rpx;
	padding: 20rpx 24rpx 120rpx;
	min-height: 100vh;
	.content{
		background: #FFFFFF;
		border-radius: 16rpx 16rpx 16rpx 16rpx;
		margin-bottom: 20rpx;
		padding: 24rpx;
	}
	.sub-title{
		font-weight: 600;
		font-size: 28rpx;
		color: #222222;
		padding-bottom: 24rpx;
		border-bottom: 1rpx solid #F0F0F0;
	}
	.no{
		padding: 24rpx 0;
		font-size: 28rpx;
		color: #222222;
		font-weight: bold;
	}
	.time-box{
		display: flex;
		justify-content: flex-end;
		text-align: center;
		.right-icon{
			width: 48rpx;
			height: 48rpx;
		}
	}
	.info{
		.title{
			font-weight: 600;
			font-size: 36rpx;
			color: #222222;
			width: 100%;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			margin-top: 10rpx;
		}
		.notice{
			display: flex;
			align-items: center;
			font-size: 24rpx;
			color: #AAAAAA;
			margin-top: 20rpx;
			.jiantou{
				width: 48rpx;
				height: 48rpx;
			}
		}
		
		.signUp-box{
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding-top: 20rpx;
			.label-box{
				display: flex;
				align-items: center;
				.label{
					font-weight: 300;
					font-size: 24rpx;
					color: #181818;
				}
				.desc{
					font-weight: 300;
					font-size: 24rpx;
					color: #AAAAAA;
				}
			}
			.num-box{
				display: flex;
				align-items: center;
				.btn.disabled{
					background: #F0F0F0;
					color: #AAAAAA;
				}
				.btn{
					width: 36rpx;
					height: 36rpx;
					line-height: 36rpx;
					border-radius: 50%;
					background: #E2ECFF;
					color: #3879F9;
					font-size: 30rpx;
					text-align: center;
					vertical-align: top;
				}
				.num{
					font-weight: 400;
					font-size: 24rpx;
					color: #222222;
					width: 50rpx;
					text-align: center;
					
				}
			}
		}
		
	}
	.btn-box {
		position: fixed;
		bottom: 0%;
		left: 0%;
		z-index: 2;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		box-sizing: border-box;
		padding: 10rpx 24rpx env(safe-area-inset-bottom);
		background: #fff;
		border-top: 1rpx solid #EEEEEE;
		.left{
			display: flex;
			align-items: flex-end;
			.num{
				font-weight: 300;
				font-size: 24rpx;
				color: #AAAAAA;
			}
			.total{
				font-weight: 300;
				font-size: 24rpx;
				color: #222222;
				display: flex;
				align-items: flex-end;
				margin-left: 6rpx;
				.price-box{
					display: flex;
					align-items: flex-end;
					font-weight: 400;
					font-size: 32rpx;
					color: #222222;
					.unit{
						font-size: 20rpx;
					}
					.price{
						font-weight: bold;
					}
				}
			}
		}
	
		.btn {
			width: 280rpx;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background: $uni-color-primary;
			border-radius: 40rpx;
			font-weight: 600;
			font-size: 28rpx;
			color: #FFFFFF;
			margin: 0;
		}
	}
	
	
	.u-popup__content{
		padding: 0 24rpx 28rpx;
		position: relative;
		.popup-title{
			font-weight: 600;
			font-size: 32rpx;
			color: #222222;
			padding: 28rpx 0;
			border-bottom: 1rpx solid #F0F0F0;
		}
		.box{
			max-height: 70vh;
			overflow: auto;
			.sub-title{
				font-weight: 600;
				font-size: 28rpx;
				color: #222222;
				margin: 20rpx 0;
				border: none;
			}
			.intro{
				font-weight: 300;
				font-size: 24rpx;
				color: #AAAAAA;
				line-height: 40rpx;
				padding-bottom: 24rpx;
			}
			.border-bottom{
				border-bottom: 1rpx solid #F0F0F0!important;
			}
		}
	}
	
	
}
</style>