<template>
	<view class="makeOut">
		<view class="content signUp-info">
			<view class="title">
				{{activity.activityName}}
			</view>
			<view class="time">
				活动时间：{{activity.activityStartTime}} 至 {{activity.activityEndTime}}
			</view>
			<view class="signUp-box">
				<view class="label-box">
					<view class="label">
						报名人数
					</view>
					<view class="desc">
						{{activity.limited?`（最多${activity.limited}人）`:'（不限制）'}}
					</view>
				</view>
				<view class="num-box">
					<view class="btn" :class="[num == 1?'disabled':'']" @click="add(-1)">
						-
					</view>
					<view class="num">
						{{num}}
					</view>
					<view class="btn" :class="[num == activity.limited?'disabled':'']" @click="add(1)">
						+
					</view>
				</view>
			</view>
		</view>
		
		<view class="content" v-for="(test,d) in modelQuery">
			<u--form
				labelPosition="left"
				:model="modelQuery[d]"
				:rules="rules"
				:ref="'uForm'+d"
				labelWidth="150rpx"
			>
				<view v-for="(item,index) in setQuery.data" :key="index">
					<u-form-item
						:label="item.dataName"
						:prop="'data_'+index+'_value'"
						:borderBottom="index != (setQuery.data.length-1)"
						:required="item.requiredEnable == 1?true:false"
						ref="item1"
					>
					
						<u--input v-if="item.dataType == 1" :placeholder="'请输入'+item.dataName" :maxlength="getLength(item)" v-model="modelQuery[d][`data_${index}_value`]" border="none"></u--input>
						<u-textarea v-else-if="item.dataType == 2" v-model="modelQuery[d][`data_${index}_value`]" border="surround" :maxlength="400" count ></u-textarea>
						<u-radio-group  v-model="modelQuery[d][`data_${index}_value`]" v-else-if="item.dataType == 3">
							<u-radio labelSize="34rpx" v-for="i in item.content" :key="i" :name="i" :label="i"></u-radio>
						</u-radio-group>
						<!-- <template v-else-if="item.dataType == 3">
							<u--input @focus="handeChoose" :placeholder="'请选择'+item.dataName" v-model="modelQuery[d][`data_${index}_value`]" border="none"></u--input>
						 <u-picker :show="show" ref="uPicker" closeOnClickOverlay :columns="[item.content]" @cancel="cancel" @confirm="confirm($event,d,index)"></u-picker>
						</template> -->
						 <u-checkbox-group
							v-model="modelQuery[d][`data_${index}_value`]"
							 v-else-if="item.dataType == 4"
						>
							<u-checkbox
							 labelSize="34rpx"
							 iconSize="34rpx"
								v-for="i in item.content"
								:key="index"
								:label="i"
								:name="i"
							>
							</u-checkbox>
						</u-checkbox-group>
						<u-upload
							width="200rpx"
							height="200rpx"
							v-else-if="item.dataType == 5"
							:fileList="modelQuery[d][`data_${index}_value`]"
							@afterRead="afterRead($event,d,index)"
							@delete="deletePic($event,modelQuery[d][`data_${index}_value`])"
							@oversize="oversize($event,item)"
							name="1"
							:maxSize="item.size*1024*1024"
							multiple
							:maxCount="item.num"
						></u-upload>
					</u-form-item>
				</view>
			</u--form>
		</view>
		
		<view class="btn-box">
			<view class="left">
				<view class="num">
					共{{num}}人
				</view>
				<view class="total">
					合计 <view class="price-box">
						<view class="unit">
							￥
						</view>
						<view class="price">
							{{total}}
						</view>
					</view>
				</view>
			</view>
			<button class="btn" @click="handleSignUp" :loading="loading">
				立即报名
			</button>
		</view>
		
	</view>
</template>

<script>
	import {getTemplateDetail,signUp,createOrder,calc} from '@/api/activity.js'
	import {upload} from '@/utils/upload.js'
	import {
		creatPayOrder,
		queryPayOrder,
		payDetails
	} from '@/api/payment.js'
	export default {
		data() {
			return {
				maxLength:40,
				num: 1,
				modelQuery:[{}],
				setQuery:{},
				activity:{},
				rules: {},
				loading:false,
				show:false,
				pickerObj:{
					
				},
				price:0,
				query: {
					"msgType": "wx.unifiedOrder",
					"orderDesc": "",
					"orderNo": "",
					"subOpenId": "",
					"userId": ""
				},
				// 支付信息
				payData: {}
			}
		},
		computed: {
			total() {
				return this.price || this.activity.price
			}
		},
		methods: {
			handeChoose(){
				this.show = true
			},
			cancel(){
				this.show = false
			},
			confirm(val,d,index){
				this.modelQuery[d][`data_${index}_value`] = val.value[0] 
				this.show = false
				console.log(val,d,index);
			},
			oversize(val,item){
				console.log(val,item);
				uni.showToast({
					title:`请上传${item.size}MB以内的图片`,
					icon:'none'
				})
			},
			getLength(item){
				if(item.validType == 1){
					return 11 
				}else if(item.validType == 2){
					return 18
				}else{
					return 40
				}
			},
			add(val){
				if((val==-1&&this.num == 1)||(val==1&&this.num == this.activity.limited)) return
				this.num += val
				if(val == 1){
					
					let obj = {}
					this.setQuery.data.map((item,index)=>{
						if(item.dataType == 1){
							// this.$set(this.modelQuery[this.modelQuery.length], `data_${index}_value`,'')
							obj[`data_${index}_value`] = ''
							
						}else if(item.dataType == 2 ){
							// this.$set(this.modelQuery[this.modelQuery.length], `data_${index}_value`,'')
							obj[`data_${index}_value`] = ''
						}
						else if(item.dataType == 3 ){
							// this.$set(this.modelQuery[this.modelQuery.length], `data_${index}_value`,'')
							obj[`data_${index}_value`] = ''
						}
						else if(item.dataType == 4 ){
							// this.$set(this.modelQuery[this.modelQuery.length], `data_${index}_value`,[])
							obj[`data_${index}_value`] = []
							
						}else if( item.dataType == 5){
							// this.$set(this.modelQuery[this.modelQuery.length], `data_${index}_value`,[])
							obj[`data_${index}_value`] = []
						}
						
					})
					this.modelQuery.push(obj)
					this.$nextTick(() => {
					  this.$refs['uForm'+(this.modelQuery.length-1)][0].setRules(this.rules);
					})
				}else{
					this.modelQuery.pop()
				}
				// 计算价格
				calc({activityId:this.activity.id,num:this.num}).then(res=>{
					if (res.state == 'Success') {
						this.price = res.content.price
					}
				})
				
			},
			getTemplateDetail(activityId){
				getTemplateDetail({activityId}).then(res=>{
					if (res.state == 'Success') {
						this.setQuery = res.content.content
						this.setQuery.data.map((item,index)=>{
							if(item.dataType == 1){
								// this.$set(item,'value','')
								this.$set(this.modelQuery[0], `data_${index}_value`,'')
								if(item.requiredEnable == 1){
									let obj; //校验规则
									if(item.validType == 0){
										console.log(11111);
										obj = {
										  required: true,
										  message: `请输入${item.dataName}`,
										  trigger: ['blur']
										}
									}else if(item.validType == 1){
										console.log(22222);
										obj ={
											pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/,
											message: '请输入正确的手机号'
										}
									}else if(item.validType == 2){
										obj ={
											len:18,
											message: '请输入正确的身份证号'
										}
									}else if(item.validType == 3){
										obj ={
											pattern: /^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]/,
											// 正则检验前先将值转为字符串
											transform(value) {
												return String(value);
											},
											message: '请输入正确的邮箱'
										}
									}else if(item.validType == 4){
										obj ={
											pattern: /^(\-|\+)?\d+(\.\d+)?$/,
											message: '只能输入数字'
										}
									}
									
									this.$set(this.rules, `data_${index}_value`, [{
									  required: true,
									  message: `请输入${item.dataName}`,
									  trigger: ['blur']
									},obj])
								}
							}else if(item.dataType == 2 ){
								// this.$set(item,'value','')
								this.$set(this.modelQuery[0], `data_${index}_value`,'')
								if(item.requiredEnable == 1){
									this.$set(this.rules, `data_${index}_value`, [{
									  required: true,
									  message: `请输入${item.dataName}`,
									  trigger: ['blur']
									}])
								}
							
							}
							else if(item.dataType == 3 ){
								// this.$set(item,'value','')
								this.$set(this.modelQuery[0], `data_${index}_value`,'')
								if(item.requiredEnable == 1){
									this.$set(this.rules, `data_${index}_value`, [{
									  required: true,
									  message: `请选择${item.dataName}`,
									  trigger: ['blur','change']
									}])
								}
								
							}
							else if(item.dataType == 4 ){
								// this.$set(item,'value',[])
								this.$set(this.modelQuery[0], `data_${index}_value`,[])
								if(item.requiredEnable == 1){
									this.$set(this.rules, `data_${index}_value`, [{
									  type: 'array',
									  required: true,
									  message: `请选择${item.dataName}`,
									  trigger: ['change']
									}])
								}
								
							}else if( item.dataType == 5){
								// this.$set(item,'value',[])
								this.$set(this.modelQuery[0], `data_${index}_value`,[])
								if(item.requiredEnable == 1){
									this.$set(this.rules, `data_${index}_value`, [{
									  type: 'array',
									  required: true,
									  message: `请上传${item.dataName}`,
									  trigger: ['change']
									}])
								}
							}
							
						})
							this.$nextTick(() => {
								console.log( this.$refs.uForm0);
							  this.$refs.uForm0[0].setRules(this.rules);
							})
						
					}
				})
			},
			// 删除图片
			deletePic(event,data) {
				data.splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event,d,index) {
				console.log(event);
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file)
			let fileListLen = this.modelQuery[d][`data_${index}_value`].length
			lists.map((item) => {
				console.log(this.setQuery.data[index],this.setQuery.data[index].dataName);
				this.modelQuery[d][`data_${index}_value`].push({
					...item,
					status: 'uploading',
					message: '上传中'
				})
			
			})
			for (let i = 0; i < lists.length; i++) {
				const result = await this.uploadFilePromise(lists[i])
				let item = this.modelQuery[d][`data_${index}_value`][fileListLen]
				
				this.modelQuery[d][`data_${index}_value`].splice(fileListLen, 1, Object.assign(item, {
					status: 'success',
					message: '',
					url: result
				}))
				
				fileListLen++
			}
			},
			uploadFilePromise(file) {
				return new Promise((resolve, reject) => {
					upload(file,'SHOP_INFO').then(res=>{
						// this.form[key] = [{url:res}]
						resolve(res)
					})
				})
			},
			formatData(){
				console.log(this.modelQuery);
			},
			// 点击提交报名
			handleSignUp(){
				let obj = {
				  "activitySignupId": this.activity.id,
				  "dataInfos": [],
				  "num": this.num,
				  "userId": JSON.parse(uni.getStorageSync('userInfo')).userId
				}
				let arr = []
				console.log( 11111111,this.modelQuery);
				new Promise((resolve,reject)=>{
					this.modelQuery.map((item,index)=>{
						let personData = {data:[]}//每个人的填写数据
						// 循环校验表单
						this['a'+index] =  new Promise((resolve1,reject1)=>{
							console.log( this.$refs['uForm' + index][0]);
							if( Object.keys(this.rules).length){//有必填项
							  this.$refs['uForm' + index][0].validate().then(res => {
								  // 把每个人的资料全部放在personData的data属性里面  依次排列
								  let dataItem
									for(let key in item){
										let i = key.split('_')[1]
										console.log(item,i,this.setQuery.data[i]);
										dataItem = JSON.parse(JSON.stringify(this.setQuery.data[i])) 
										
										// 值是数组直接赋值
										if(Array.isArray(item[key])){
											if(dataItem.dataType == 5){//取出图片里面的地址
												dataItem.content = item[key].map(item1=>{ return item1.url})
											}else{
												dataItem.content = item[key]
											}
										}else{
											dataItem.content = [item[key]]
										}
										personData.data.push(dataItem)
									}
									resolve1(1)
									
								}).catch(errors => {
									console.log(errors);
								})
							}else{
								// 把每个人的资料全部放在personData的data属性里面  依次排列
								let dataItem
								for(let key in item){
									let i = key.split('_')[1]
									console.log(item,i,this.setQuery.data[i]);
									dataItem = JSON.parse(JSON.stringify(this.setQuery.data[i])) 
									
									// 值是数组直接赋值
									if(Array.isArray(item[key])){
										if(dataItem.dataType == 5){//取出图片里面的地址
											dataItem.content = [item[key][0].url]
										}else{
											dataItem.content = item[key]
										}
									}else{
										dataItem.content = [item[key]]
									}
									personData.data.push(dataItem)
								}
								resolve1(1)
							}
						})
						obj.dataInfos.push(personData)
						// 校验的promise数组 用于获取全部校验成功
						arr.push(this['a'+index])
						
					})
					// 全部校验成功
					Promise.all(arr).then(res=>{
						console.log('结果',res);
						resolve()
					}).catch(e=>{
						console.log('报错',e);
					})
				}).then(()=>{
					console.log(this.modelQuery,this.setQuery,obj)
					this.signUp(obj).then(id=>{
						this.creat(id)
					})
				})
			},
			signUp(obj){
				return new Promise((resolve,reject)=>{
					this.loading = true
					signUp(obj).then(res=>{
						this.loading = false
						if (res.state == 'Success') {
							resolve(res.content.serviceId)
							// uni.hideLoading()
							// uni.showToast({
							// 	title:'报名成功',
							// 	icon:'success'
							// })
							// uni.reLaunch({
							// 	url: '/my/order/index'
							// })
						}
					})
				})
			},
			//创建订单
			creat(serviceId) {
				if (this.loading) return
					this.loading = true
					uni.showLoading({
						title: '支付中'
					})
					let that = this
					if (!this.payData.timeStamp) {
						createOrder({
							activityId: this.activity.id,
							serviceId,
							channel:'ZhongShu',
							num:this.num,
							userId: JSON.parse(uni.getStorageSync('userInfo')).userId
						}).then(res => {
							this.loading = false
							if (res.state == 'Success') {
								if (!this.activity.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.activity.activityName
									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/signUp/signUpDetail?id='+that.query.orderNo
												})
												// payDetails(that.query.orderNo).then(r => {
												// 	if (r.state == 'Success') {
												// 	that.payData = JSON.parse(r.content.miniPayRequest)
												// 	}
												// })
											}
										})
			
									})
								}
			
							}
						})
					} 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);
							}
						})
					}
			}
		},
		onLoad(options) {
			let userInfo = JSON.parse(uni.getStorageSync('userInfo'))
			this.query.userId = userInfo.userId
			this.activity = JSON.parse(uni.getStorageSync('activity'))
			this.getTemplateDetail(this.activity.id)
		}
	}
</script>

<style lang="scss" >
.makeOut{
	background: #F9F9F9;
	min-height: 100vh;
	padding-top: 20rpx;
	padding-bottom: 150rpx;
	.content{
		margin: 0 24rpx 20rpx;
		padding: 28rpx 24rpx;
		background: #fff;
		box-sizing: border-box;
		border-radius: 16rpx;
	}
	.signUp-info{
		.title{
			font-weight: 600;
			font-size: 32rpx;
			color: #181818;
			overflow: hidden;
			text-overflow: ellipsis;
			/* 弹性伸缩盒子模型显示 */
			display: -webkit-box;
			/* 限制在一个块元素显示的文本的行数 */
			-webkit-line-clamp: 2;
			/* 设置或检索伸缩盒对象的子元素的排列方式 */
			-webkit-box-orient: vertical;
		}
		.time{
			font-weight: 300;
			font-size: 24rpx;
			color: #AAAAAA;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #F0F0F0;
		}
		.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: #FFEDEB;
					color: $uni-color-primary;
					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;
					}
				}
			}
		}
	
		.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-form-item{
		display: flex;
		justify-content: flex-start;
		.u-form-item__body__left{
			align-self: flex-start !important;
		}
		.u-radio-group{
			flex-wrap: wrap;
		}
		.u-radio,.u-checkbox{
			margin-right: 20rpx;
			margin-bottom: 20rpx;
		}
		.u-radio__icon-wrap--circle,.u-checkbox__icon-wrap--square{
			width: 28rpx!important;
			height: 28rpx!important;
		}
		.u-checkbox-group{
			flex-wrap: wrap;
			.u-radio,.u-checkbox-label--left{
				margin-bottom: 20rpx;
			}
		}
	}
}
</style>