<template>
	<view class="pageBg">
		<!-- <topNavbar title="报名信息确认"></topNavbar> -->
		<view class="pad">
			<view class="card">
				<view class="row">
					<view class="lab">扫描教练二维码</view>
					<view class="rightCon">
						<view class="scan" @click="scanCodeFn">
							<image src="@/static/images/carIcon/sanIcon.png"></image>
						</view>
					</view>
				</view>
			</view>
			
			<view class="card">
				<view class="row" >
					<view class="lab">选择驾校</view>
					<view class="rightCon">
						<view class="row" @click="showSchool=true">
							<view class="val">
								<mySelect :value="form.school"/>
							</view>
							<view class="arrow">
								<u-icon name="arrow-right" size="14" color="#686B73" style="margin-left: 12rpx;" ></u-icon>
							</view>
						</view>
					</view>
				</view>
				<view class="row">
					<view class="lab">选择车型</view>
					<view class="rightCon">
						<view class="row" @click="showCarClick">
							<view class="val">
								<mySelect :value="form.trainType"/>
							</view>
							<view class="arrow">
								<u-icon name="arrow-right" size="14" color="#686B73" style="margin-left: 12rpx;" ></u-icon>
							</view>
						</view>
					</view>
				</view>
				<view class="row">
					<view class="lab">选择班型</view>
					<view class="rightCon">
						<view class="row"  @click="showClassModel=true">
							<view class="val">
								<mySelect :value="form.classModel"/>
							</view>
							<view class="arrow">
								<u-icon name="arrow-right" size="14" color="#686B73" style="margin-left: 12rpx;" ></u-icon>
							</view>
						</view>
					</view>
				</view>
				<view class="row">
					<view class="lab">选择教练</view>
					<view class="rightCon" @click="goCoach">
						<view class="row" >
							<view class="val">
								<mySelect :value="form.coach"/>
							</view>
							<view class="arrow">
								<u-icon name="arrow-right" size="14" color="#686B73" style="margin-left: 12rpx;" ></u-icon>
							</view>
						</view>
					</view>
				</view>
			</view>
			
			<view class="card">
				<view class="row">
					<view class="lab">业务类型</view>
					<view class="rightCon">
						<u-radio-group
						    v-model="form.businessType"
						  >
						    <u-radio
						      :customStyle="{marginRight: '24rpx'}"
						      v-for="(item, index) in radiolist1"
						      :key="index"
						      :label="item.name"
						      :name="item.id"
						    >
						    </u-radio>
						  </u-radio-group>
					</view>
				</view>
			</view>
			
			<view class="card" v-if="form.businessType==1">
				<view class="row">
					<view class="lab long">原驾驶证号</view>
					<view class="rightCon">
						<view class="row">
							<view class="val">
								<u-input placeholder="请输入原驾驶证号" v-model="form.certificateCodeShow" border font-size="26rpx" placeholderStyle="color: #ADADAD" style="padding: 0;"></u-input>
							</view>
						</view>
					</view>
				</view>
				<view class="row">
					<view class="lab long">驾驶证初领日期</view>
					<view class="rightCon">
						<view class="row" @click="showFirstLicenceTime=true" >
							<view class="val">
								<mySelect :value="form.firstDriveDate"/>
							</view>
							<view class="arrow">
								<u-icon name="arrow-right" size="14" color="#686B73" style="margin-left: 12rpx;" ></u-icon>
							</view>
						</view>
					</view>
				</view>
				<view class="row">
					<view class="lab long">原准驾车型</view>
					<view class="rightCon">
						<view class="row" @click="showOldDriveModel=true" >
							<view class="val">
								<mySelect :value="form.oldTrainType"/>
							</view>
							<view class="arrow">
								<u-icon name="arrow-right" size="14" color="#686B73" style="margin-left: 12rpx;" ></u-icon>
							</view>
						</view>
					</view>
				</view>
			</view>
			
			<view class="card">
				<view class="row">
					<view class="lab">是否异地转入</view>
					<view class="rightCon" style="margin-left: 40rpx;">
						<u-radio-group
						    v-model="form.transfer"
							@change="changeVal"
						  >
						    <u-radio
						      :customStyle="{marginRight: '24rpx'}"
						      v-for="(item, index) in radiolist2"
						      :key="item.id"
						      :label="item.name"
						      :name="item.id"
						    >
						    </u-radio>
						  </u-radio-group>
					</view>
				</view>
			</view>
			
			<view class="card" v-if="form.transfer==1">
				<view class="row" @click="cityShowFn">
					<view class="lab">来源城市</view>
					<view class="rightCon">
						<view class="row">
							<view class="val">
								<mySelect :value="form.fromArea"/>
							</view>
							<view class="arrow">
								<u-icon name="arrow-right" size="14" color="#686B73" style="margin-left: 12rpx;" ></u-icon>
							</view>
						</view>
					</view>
				</view>
				<view class="row">
					<view class="lab ">已过科目</view>
					<view class="rightCon">
						<view class="row" @click="subjectClick">
							<view class="val">
								<mySelect :value="form.finishSubjectName"/>
							</view>
							<view class="arrow">
								<u-icon name="arrow-right" size="14" color="#686B73" style="margin-left: 12rpx;" ></u-icon>
							</view>
						</view>
					</view>
				</view>
				<view class="row">
					<view class="lab">待学科目</view>
					<view class="rightCon">
						<view class="row" @click="showSubjectTreat=true">
							<view class="val">
								<mySelect :value="form.waitSubjectName"/>
							</view>
							<view class="arrow">
								<u-icon name="arrow-right" size="14" color="#686B73" style="margin-left: 12rpx;" ></u-icon>
							</view>
						</view>
					</view>
				</view>
			</view>
			
			<view class="card" v-if="form.totalAmount">
				<view class="row">
					<view class="lab">学费</view>
					<view class="rightCon">
						<view class="row">
							<view class="val blue" >￥{{ $u.utils.priceTo(form.totalAmount) }}</view>
						</view>
					</view>
				</view>
			</view>
			
			<view class="btnBg" @click="confirmClick">确认</view>
		</view>
		<u-popup :show="showPopup" mode="center" :round="8" >
			<comfigPopup @comfigClick="comfigClick" :info="form"/>
		</u-popup>
		
		<u-popup :show="showSchool" mode="bottom" :round="8"  @close="showSchool=false">
			<searchSchool @chooseSchool="chooseSchool"/>
		</u-popup>
		
		<!-- 选择班型 -->
		<u-picker :show="showClassModel" :columns="columnsClassModel" keyName="name" @confirm="confirmClassModel" @cancel="showClassModel=false"></u-picker>
		<!-- 选择车型 -->
		<u-picker :show="showCar" :columns="columnsCar" keyName="label" @confirm="confirmCar" :closeOnClickOverlay="true" @cancel="showCar=false"></u-picker>
		<!-- 原驾驶证初领日期 -->
		<u-datetime-picker :show="showFirstLicenceTime"  mode="date"  @confirm="confirmFirstLicenceTime"></u-datetime-picker>
		<!-- 原驾驶证学驾车型 -->
		<u-popup :show="showOldDriveModel" mode="bottom" :round="8"  @close="showOldDriveModel=false">
			<oldDrive @pickerOldDrive="pickerOldDrive"/>
		</u-popup>
		<!-- 已过科目 -->
		<u-picker :show="showSubjectPass" :columns="columnsSubject" keyName="label" @confirm="confirmSubjectPass" @cancel="showSubjectPass=false"></u-picker>
		<!-- 待学科目 -->
		<u-picker :show="showSubjectTreat" :columns="columnsSubject" keyName="label" @confirm="confirmTreat" @cancel="showSubjectTreat=false"></u-picker>
		<!-- 城市 -->
		<u-picker :show="showCity"   ref="uPicker" :columns="[cityArr]" @confirm="confirmCity" @change="changeHandler" keyName="name"  @cancel="showCity=false"></u-picker>
		
	</view>
</template>

<script>
	import comfigPopup from './comp/comfigPopup'
	import searchSchool from './comp/searchSchool'
	import oldDrive from './comp/oldDrive'
	import { areaTree, applyOnline, schoolClass, getSchoolDetail, paymentPrice } from '@/config/api.js'
	import { scanCodeFn } from '@/config/utils.js'
	export default {
		components: { comfigPopup, searchSchool, oldDrive },
		data() {
			return {
				showCity: false,
				showPopup: false,
				showClassModel: false,
				showCar: false,
				showFirstLicenceTime: false,
				showOldDriveModel: false,
				showSubjectPass: false,
				showSubjectTreat: false,
				columnsClassModel: [],//班型
				columnsSubject: [
					[
						{label: '科目一', id: 1},
						{label: '科目二', id: 2},
						{label: '科目三', id: 3},
					]
				],
				columnsCar: [],
				form: {
					school: '',
					classModel: '',
					car: '',
					coach: '',
					cardType: 1,
					idcard: '',
					trainType: '',//车型
					nationality: '中国',
					certificateCodeShow: '',
					driveLicence: '',//原驾驶证号 给后端的
					firstDriveDate: '',//原驾驶证初领日期
					sex: 2,
					phone: '',
					applyType: 1,
					name: '',
					oldTrainType: '',//原准驾车型
					finishSubject: '',//已过科目
					finishSubjectName: '',//已过显示文字
					waitSubjectName: '',//待学科目显示文字
					waitSubject: '',//待学科目
					photoPath: '',
					address: '',
					totalAmount: 0,
					transfer: 2, //是否异地
					businessType: 0, 
					fromArea: '',//异地城市
					
				},
				showSchool: false,
				radiolist1:  [ {name: '初领', id: 0}, {name: '增驾', id: 1}],//0：初领，1：增驾，
				radiolist2: [{name: '否', id: 2}, {name: '是', id: 1}, ],
				radiolist3: [ {name: '全款', id: 1}, {name: '预付款', id: 2}],
				cityArr: [],
				cityArr2: [],
				cityArr3: []
			}
		},
		onLoad(options) {
			if(options.realNameNo) {
				this.realNameNo = options.realNameNo
			}
			this.initUserInfo()
			
			// 监听上一个页面的选择教练
			uni.$on('upDateCoachItem',(item)=>{
				console.log(item)
				this.form.coach = item.name
				this.form.coachId = item.id
			})
			this.areaTreeFn()
			
			// 如果是选择了驾校班型来报名的
			let schoolClass = this.$store.state.school.schoolClass
			if(schoolClass.id) {
				console.log(schoolClass)
				this.form.classModel = schoolClass.name
				this.form.school = schoolClass.schoolName
				this.form.schoolId = schoolClass.schoolId
				this.form.trainType = schoolClass.carType
				this.form.schoolClassId = schoolClass.id
				this.form.totalAmount= schoolClass.totalAmount
			}
			// 如果是选择了驾校教练来报名的/扫二维码
			let schoolCoach = this.$store.state.school.schoolCoach
			if(schoolCoach.id) {
				console.log('schoolCoach')
				console.log(schoolCoach)
				this.form.coach = schoolCoach.name
				this.form.coachId = schoolCoach.id
				this.form.school = schoolCoach.schoolName
				this.form.schoolId = schoolCoach.schoolId
				if(schoolCoach.teachCarType) this.form.trainType = schoolCoach.teachCarType.slice(0,2)
			}
			// 如果是扫驾校的二维码来的
			let schoolCode = this.$store.state.school.schoolCode
			if(schoolCode.schoolId) {
				console.log('schoolCode')
				console.log(schoolCode)
				this.form.school = schoolCode.schoolName
				this.form.schoolId = schoolCode.schoolId
			}
			
			if(this.form.schoolId) {
				this.getSchoolDetailFn()
			}
		},
		onPullDownRefresh() {
			this.initUserInfo()
		},
		methods: {
			async initUserInfo() {
				// 如果不是实名
				// if(!this.realNameNo) {
				// 	await this.$store.dispatch('getUserInfo')
				// }
				console.log(this.vuex_userInfo)
				this.form.userId = this.userId
				this.form.accountId = this.vuex_userInfo.accountId 
				this.form.address = this.vuex_userInfo.address 
				this.form.name = this.vuex_userInfo.name
				this.form.idcard = this.vuex_userInfo.idcard
				this.form.phone = this.vuex_userInfo.phone
				this.form.nationality = this.vuex_userInfo.nationality || '中国'
				this.form.cardType = this.vuex_userInfo.cardType || '1'
				this.form.sex = this.vuex_userInfo.sex
				if(this.vuex_userInfo.photoPath&&this.form.cardType!='1') this.form.photoPath = this.vuex_userInfo.photoPath
			},
			// 查班型
			async schoolClassFn() {
				const {data: res} = await schoolClass({pageNo: 1,pageSize: 100, schoolId: this.form.schoolId, carType: this.form.trainType})
				this.columnsClassModel = [res.list]
				console.log(this.columnsClassModel)
			},
			cityShowFn() {
				this.showCity = true
				this.$nextTick(()=>{
					let  picker = this.$refs.uPicker
					picker.setColumnValues(1, this.cityArr2[0])
					picker.setColumnValues(2, this.cityArr3[0][0])
				})
				
				// picker = this.$refs.uPicker
			},
			 changeHandler(e) {
				const {
					indexs,
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
				if (columnIndex === 0) {
					// picker为选择器this实例，变化第二列对应的选项
					picker.setColumnValues(1, this.cityArr2[index])
					picker.setColumnValues(2, this.cityArr3[index][0])
				}
				if (columnIndex === 1) {
					let index3 = indexs[0]
					// picker为选择器this实例，变化第二列对应的选项
					picker.setColumnValues(2, (this.cityArr3[index3])[index])
				}
				console.log(indexs[0])
				// console.log(this.cityArr3[index3])
				// console.log(value)
				// console.log(values)
				// console.log(columnIndex)
			},
			// 回调参数为包含columnIndex、value、values
			confirmCity(e) {
				console.log('confirm', e) 
				this.form.fromArea = e.value.map((item)=>{
					return item.name
				}).join(',').replace(/,/g, '-')
				this.showCity = false
			},
			// 获取地区
			async areaTreeFn() {
				// this.cityArr2.push(this.traverse(item.children))
				const {data: res} = await areaTree()
				this.cityArr = res.map(item=>{
					let obj = {
						id: item.id,
						name: item.name
					}
					return obj
				})
				
				this.cityArr2 = res.map(item2=>{
					let arr2 = item2.children
					return arr2.map(val=>{
						let obj = {
							id: val.id,
							name: val.name
						}
						return obj
					})
				})
				
				this.cityArr3 = res.map(item2=>{
					let arr2 = item2.children
					return arr2.map(val=>{
						return val.children.map(val3=>{
							let obj = {
								id: val3.id,
								name: val3.name
							}
							return obj
						})
					})
				})
			},
			traverse(arr, result=[]) {
				  for (var i = 0; i < arr.length; i++) {
					  let item = arr[i]
					  let obj = {
					  	id: item.id,
					  	name: item.name
					  }
					  result.push(obj)
				    if(item.children.length) {
						this.traverse(item.children, result)
					}
				  }
				  return result;
			},
			// 选择驾校
			chooseSchool(item) {
				this.form.school = item.name
				this.form.schoolId = item.id
				this.columnsCar = [item.businessScope.split(',')]
				this.form.classModel = ''
				this.form.schoolClassId = ''
				this.form.trainType = ''
				this.form.coach = ''
				this.form.coachId = ''
				this.form.totalAmount = ''
				this.showSchool = false
				this.schoolClassFn()
			},
			// 选择班型
			confirmClassModel(val) {
				let item = val.value[0]
				console.log(item)
				this.showClassModel = false
				this.form.classModel = item.name
				this.form.schoolClassId = item.id
				if(this.form.finishSubject&&this.form.transfer==1) {
					this.paymentPriceFn()
				}else {
					this.form.totalAmount = item.totalAmount
				}
			},
			// 选择车型
			confirmCar(val) {
				let item = val.value[0]
				console.log(item)
				this.showCar = false
				if(this.form.trainType == item) return
				this.form.trainType = item
				this.form.coach = ''
				this.form.coachId = ''
				this.form.classModel = ''
				this.form.schoolClassId = ''
				this.form.totalAmount = ''
				this.schoolClassFn()
			},
			showCarClick() {
				if(!this.form.school)  return this.$u.toast('请先选择驾校')
				this.showCar = true
			},
			// 跳转到选择教练
			goCoach() {
				if(!this.form.schoolId) return this.$u.toast('请先选择驾校')
				if(!this.form.trainType) return this.$u.toast('请先选择车型')
				this.$goPage('/pages/indexEntry/enroll/registInfo/chooseCoach/chooseCoach?schoolId=' + this.form.schoolId+ '&trainType='+ this.form.trainType)
			},
			// 选择原驾驶证初领日期
			confirmFirstLicenceTime(val) {
				console.log(val)
				this.form.firstDriveDate = uni.$u.timeFormat(val.value, 'yyyy-mm-dd');
				this.showFirstLicenceTime = false
			},
			// 选择原准驾车型
			pickerOldDrive(val) {
				this.form.oldTrainType = val
				this.showOldDriveModel = false
				console.log(val)
			},
			// 弹出选择已过科目
			subjectClick() {
				if(!this.form.schoolClassId) return this.$u.toast('请先选择报名班型，方便计算价格')
				this.showSubjectPass=true
			},
			// 选择已过科目
			confirmSubjectPass(val) {
				this.showSubjectPass = false
				let item = val.value[0]
				if(this.form.finishSubject == item.id) return
				this.form.finishSubject = item.id
				this.form.finishSubjectName = item.label
				this.paymentPriceFn()
			},
			// 已过科目价格计算
			async paymentPriceFn() {
				let obj = {
					schoolClassId: this.form.schoolClassId,
					finishSubject: this.form.finishSubject
				}
				const res = await paymentPrice(obj)
				if(res.code==0) {
					this.form.totalAmount = res.data
				}
			},
			// 选择已过科目
			confirmTreat(val) {
				let item = val.value[0]
				this.form.waitSubjectName = item.label 
				this.form.waitSubject = item.id 
				this.showSubjectTreat = false
			},
			// 扫码
			scanCodeFn() {
				let _this = this
				uni.scanCode({
					success: async function(res) {
						console.log('条码类型：' + res.scanType);
						console.log('条码内容：' + res.result);
						let obj = JSON.parse(res.result)
						console.log(obj.QrType)
						console.log(obj.QrType==1)
						if(obj.QrType==1) {
							if( !obj.coachId ) { 
								// 说明是扫驾校码报名的要转一下驾校名称
								obj.schoolName = decodeURIComponent(obj.schoolName)
								
							}
							_this.form.school = obj.schoolName
							_this.form.schoolId = obj.schoolId
							const {data: item} = await getSchoolDetail({id: _this.form.schoolId})
							_this.chooseSchool(item)
							if( !obj.coachId) return
							_this.form.coach = obj.coachName
							_this.form.coachId = obj.coachId
							if(obj.teachCarType) _this.form.trainType = obj.teachCarType.slice(0,2)
							console.log(_this.form)
						}else {
							_this.$u.toast('报名码错误，请扫教练或驾校二维码')
						}
						
					}
				});
			},
			async getSchoolDetailFn() {
				const {data: res} = await getSchoolDetail({id: this.form.schoolId})
				this.columnsCar = [res.businessScope.split(',')]
				console.log('驾校id')
				console.log(res.id)
				this.schoolClassFn()
			},
			changeVal(val) {
				console.log(val)
				console.log(this.form.transfer)
			},
			// 点击确认
			confirmClick() {
				if(!this.form.schoolId) return this.$u.toast('请选择驾校')
				if(!this.form.trainType) return this.$u.toast('请选择车型')
				if(!this.form.schoolClassId) return this.$u.toast('请选择班型')
				this.showPopup = true
			},
			
			async comfigClick(val) {
				console.log(val)
				this.showPopup = false
				if(!val) return false
				let obj = Object.assign({},this.form)
				obj.name = obj.name.replace(/\s+/g, '')
				obj.idcard = obj.idcard.replace(/\s+/g, '')
				const {data: res} = await applyOnline(obj)
				// 报名成功
				console.log(res)
				await this.$store.dispatch('getUserInfo')
				if(val) {
					this.$goPage('/pages/indexEntry/enroll/signContract/signContract?schoolId='+this.form.schoolId)
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.pad {
		padding-bottom: 66rpx;
	}
	.card {
		padding: 10rpx 40rpx 10rpx 32rpx;
		margin-bottom: 20rpx;
	  .row {
		  height: 88rpx;
		  display: flex;
		  align-items: center;
		  width: 100%;
	    .lab {
			width: 152rpx;
			line-height: 88rpx;
			white-space: nowrap;
			&.long {
				width: 230rpx;
			}
	    }
		.scan {
			margin-left: auto;
			width: 40rpx;
			height: 38rpx;
			image {
				display: block;
				width: 100%;
				height: 100%;
			}
		}
	    .rightCon {
			flex: 1;
			width: 0;
			display: flex;
	      .val {
			flex: 1;
			width: 0;
			input {
				font-size: 28rpx;
			}
			&.blue {
				color:  $themC;
			}
			&.red {
				color:  #FF6A2A;
			}
	      }
	
	      .icon {
			  width: 30rpx;
			  height: 30rpx;
	        u-icon {
	
	        }
	      }
	    }
	  }
	}
	.btnBg {
		width: 396rpx;
		margin: 100rpx auto  0 auto;
	}
</style>