<template>
	<view class="content">
		<view class="top-haed">
			<view class="" @click="back()">
				<u-icon name="arrow-left" size="20"></u-icon>
			</view>
			<view class="title_">量表详情页</view>
			<view class=""></view>
		</view>

		<view class="head">
			<image src="../../static/images/banner1.png"></image>
		</view>
		<view class="con">
			<view class="hand">
				<view class="form-area">
					<view class="form-inner">
						<view class="form-item">
							<view class="form-item-label">儿童姓名</view>
							<view class="form-item-input">
								<u--input inputAlign="right" placeholder="请输入孩子姓名" border="none" clearable
									v-model="children.username" placeholderStyle="color:#8C8C8C;text-align:right;"
									fontSize="24rpx"></u--input>
							</view>
						</view>
						<view class="form-item" @click="childSexClick">
							<view class="form-item-label">儿童性别</view>
							<view class="form-item-input" @click="childSexClick">
								<view style="font-size: 12px; text-align: right; " v-if="children.sex">{{children.sex}}
								</view>
								<view style="font-size: 12px; color: #8c8c8c;text-align: right; " v-else>请选择孩子性别</view>
								<!-- 	<u--input inputAlign="right" v-model="children.sex" placeholder="请选择孩子性别" border="none"
									clearable placeholderStyle="color:#8C8C8C;text-align:right;" fontSize="24rpx"
									readonly></u--input> -->
							</view>
						</view>
						<view class="form-item" @click="childDateClick">
							<view class="form-item-label">儿童出生年月</view>
							<view class="form-item-input" @click="childDateClick">
								<view style="font-size: 12px; text-align: right; " v-if="children.birthday">
									{{children.birthday}}
								</view>
								<view style="font-size: 12px; color: #8c8c8c;text-align: right; " v-else>请选择孩子出生日期
								</view>

							</view>
						</view>
						<!-- <view class="form-item">
							<view class="form-item-label">儿童身份证号</view>
							<view class="form-item-input">
								<u--input inputAlign="right" placeholder="请输入18位身份证号" border="none" clearable
									v-model="children.idCard" placeholderStyle="color:#8C8C8C;text-align:right;"
									fontSize="24rpx"></u--input>
							</view>
						</view> -->
						<view class="form-item">
							<view class="form-item-label">家长姓名</view>
							<view class="form-item-input">
								<u--input inputAlign="right" placeholder="请输入家长姓名" border="none" clearable
									v-model="children.parentName" placeholderStyle="color:#8C8C8C;text-align:right;"
									fontSize="24rpx"></u--input>
							</view>
						</view>
						<view class="form-item">
							<view class="form-item-label">手机号</view>
							<view class="form-item-input">
								<u--input inputAlign="right" placeholder="请输入家长手机号" border="none" clearable
									v-model="children.tel" placeholderStyle="color:#8C8C8C;text-align:right;"
									fontSize="24rpx"></u--input>
							</view>
						</view>
						<view class="form-item">
							<view class="form-item-label">与儿童关系</view>
							<view class="form-item-input">
								<u--input inputAlign="right" placeholder="请输入与孩子的关系" border="none" clearable
									v-model="children.relation" placeholderStyle="color:#8C8C8C;text-align:right;"
									fontSize="24rpx"></u--input>
							</view>
						</view>
						<view class="form-item" v-if="deptId&&deptId!=100">
							<view class="form-item-label">所在机构</view>
							<view class="form-item-input">
								<view @click="deptSelect()">{{bm_title}}</view>
								<view v-if="!bm_title" style="font-size: 15px; color: blue;" @click="deptSelect()">选择机构
								</view>

							</view>
						</view>


					</view>
				</view>
			</view>
		</view>

		<!-- 	<view class="privacy-policy" v-if="isAddShow">
			<view class="privacy-policy-checkbox">
				<u-checkbox-group @change="checkboxChange" v-model="privacyPolicyChecked">
					<u-checkbox activeColor="#FFA521" size="16" name="1"></u-checkbox>
				</u-checkbox-group>
			</view>
			<view class="privacy-policy-text">
				<text>同意运营商收集以上信息，</text>
				<text class="privacy-policy-text-btn" @click="goPolicy">《隐私政策》</text>
			</view>
		</view> -->

		<view class="btn" @tap="userAddChildren">
			开始测试
		</view>

		<next-tree ref="nextTreeAsyncRef" labelKey='label' :treeData="treeData" @confirm='deptConfirm'></next-tree>
		<u-picker :show="childSexShow" :columns="childSexColumns" @confirm="childSexConfirm" @cancel="childSexCancel"
			:defaultIndex="childSexDefaultIndex"></u-picker>
		<u-datetime-picker :show="childDateShow" mode="date" @confirm="childDateConfirm" :maxDate="maxDate"
			:minDate="minDate" @cancel="childDateCancel"></u-datetime-picker>
		<u-toast ref="uToast"></u-toast>
		<u-modal :show="payShow" confirmText="支付" :showCancelButton="true" @confirm="payConfirm" @cancel="cancelConfirm"
			:buttonReverse="true">
			<view class="slot-content">
				支付
				<text style="color:red;font-weight: 700;">{{price}}元</text>
				，开启量表测试
				<!-- <text style="font-weight: 700;">{{tableName}}</text> -->
				？
			</view>
		</u-modal>
	</view>
</template>
<script>
	import cityData from '@/util/city.js'
	import {
		openPay,
		prepayment,
		lbPrice,
		getAdInfo
	} from "@/common/api/api.js"
	export default {
		data() {
			return {
				isAdVisible: false,
				currentTime: 0, // 当前视频播放时间  
				videourl: '',
				deptId: uni.getStorageSync('CodeDeptId') ? uni.getStorageSync('CodeDeptId') : "",
				payShow: false,
				tableAlias: null,
				treeData: [],
				tabCur: 1,
				childList: [],
				childListPickerShow: false,
				childListPickerLoading: false,
				selectedChild: {},
				// 新增加
				children: {
					"parentName": "",
					"tel": "",
					"username": "",
					"sex": null,
					"birthday": "",
					"idCard": "",
					"relation": "",
					"address": "",
					"state": "",
					"city": "",
					"district": "",
					"school": ""
				},
				cityName: "",

				// 城市选择器
				cityShow: false,
				// 打开选择器显示默认城市
				cityList: [],
				bm_title: "",
				cityLevel1: [],
				cityLevel2: [],
				cityLevel3: [],
				show: false, //是否显示
				columns: [], //省份数据显示，三级联动需要三维数组，展示初始数据
				columnData: [], //市数据
				columnDatas: [], //区地址			
				privacyPolicyChecked: [],
				childSexShow: false,
				childSexColumns: [
					['男', '女']
				],
				childSexDefaultIndex: [0],
				childDate: "",
				childDateShow: false,
				maxDate: new Date((new Date().getFullYear()) + "/12/31").getTime(),
				minDate: new Date("2000/1/1").getTime(),
				isAddShow: true, //新增时显示 修改时不显示
				tableName: "",
				price: "",
				prepay: {},
				selectedChildId: "",
				videoLastTime: 0
			}
		},
		onLoad(option) {
			this.tableAlias = option.alias;
			this.tableName = option.tableName;
			console.log(209, this.tableAlias)
			console.log(210, this.tableName)
			this.initCityData();
			// 默认选中第一个儿童
			this.$myRequest({
				url: '/system/children/userChildrenslist'
			}).then((res) => {
				// console.log(res.data.rows[0]);
				if (res.data.rows.length > 0) {
					console.log(res.data.rows[0]);
					this.selectedChild = res.data.rows[0]
				}

			})
		},
		methods: {
			back() {
				uni.navigateBack()
			},
			close() {
				this.isAdVisible = false
			},
			open() {

			},
			deptConfirm(e) {
				console.log(e);
				if (e[0]) {
					this.bm_title = e[0].label
					this.children.deptId = e[0].id
				}

			},
			async deptSelect() {

				const res = await this.$myRequest({
					url: '/system/user/deptTree2',
					method: 'GET',
					data: {
						deptId: this.deptId
					}
				})

				this.treeData = res.data.data
				console.log('dept', this.treeData)
				this.$refs.nextTreeAsyncRef.showTree = true
			},
			goPolicy() {
				uni.navigateTo({
					url: "/loginPackage/pages/PrivacyPolicy"
				})
			},
			payConfirm() {
				console.log(this.prepay);
				uni.requestPayment({
					provider: "wxpay",
					timeStamp: this.prepay.timeStamp,
					nonceStr: this.prepay.nonceStr,
					package: this.prepay.package,
					signType: this.prepay.signType,
					paySign: this.prepay.paySign,
					success: (rex) => {
						console.log('success:' + JSON.stringify(rex));
						uni.showToast({
							icon: "success",
							title: "支付成功"
						})
						this.payShow = false;
						setTimeout(() => {
							if (this.tabCur == 0) {
								uni.redirectTo({
									url: `/tablePackage/pages/answerDetail?alias=${this.tableAlias}&selectedChildId=${this.selectedChild.id}`
								})
							} else {
								uni.redirectTo({
									url: `/tablePackage/pages/answerDetail?alias=${this.tableAlias}&selectedChildId=${this.selectedChildId}`
								})
							}

						}, 2000)
					},
					fail: (err) => {
						console.log('fail:' + JSON.stringify(err));
						uni.showToast({
							icon: "none",
							title: "支付失败，请重试"
						})
						this.payShow = false;
					}
				});
			},
			cancelConfirm() {
				this.payShow = false;
			},
			// 跳转测试页
			goTest() {
				if (uni.$u.test.isEmpty(this.selectedChild)) {
					return uni.showToast({
						title: '请选择或手动选择儿童',
						icon: 'none'
					})
				}
				// if (uni.$u.test.isEmpty(this.privacyPolicyChecked.length)) {
				// 	return uni.showToast({
				// 		title: '请查看并同意隐私政策',
				// 		icon: 'none'
				// 	})
				// }
				//查询支付信息
				openPay().then(res => {
					if (res.msg == "false") {
						let param = {
							lgt: uni.getStorageSync("lon"),
							lat: uni.getStorageSync("lat")
						}
						console.log(param, 361)
						//关闭支付
						getAdInfo(param).then(adInfo => {
							if (adInfo.data) {
								// this.videourl = this.baseUrl + adInfo.data.video
								uni.navigateTo({
									url: '/tablePackage/pages/vdo?videourl=' + this.baseUrl +
										adInfo.data.video + '&alias=' + this.tableAlias +
										'&selectedChildId=' + this.selectedChild.id
								})
							} else {
								uni.redirectTo({
									url: `/tablePackage/pages/answerDetail?alias=${this.tableAlias}&selectedChildId=${this.selectedChild.id}`
								})
							}
						})

					} else {
						//开启支付
						prepayment(this.deptId).then(res1 => {
							console.log(2262, res1);
							if (res1.paySign) {
								this.prepay = res1;
								//未购买，显示价格
								lbPrice().then(res2 => {
									console.log(266, res2);
									this.price = res2.msg;
									this.payShow = true;
								})
							} else {
								//已购买
								uni.redirectTo({
									url: `/tablePackage/pages/answerDetail?alias=${this.tableAlias}&selectedChildId=${this.selectedChild.id}`
								})

							}
						})
					}
				})


			},
			handleTimeUpdate(e) {

				// 更新当前播放时间  
				this.currentTime = e.detail.currentTime;
				this.videoLastTime = Math.floor(e.detail.duration - e.detail.currentTime)
				console.log(this.videoLastTime, 395)
			},
			handleVideoEnded(e) {
				// 隐藏广告弹出层
				this.isAdVisible = false;

				// 跳转到下一个页面  
				uni.redirectTo({
					url: `/tablePackage/pages/answerDetail?alias=${this.tableAlias}&selectedChildId=${this.selectedChild.id}`
				})
			},
			selectAuto() {
				this.tabCur = 0;
			},
			selectTab() {
				this.tabCur = 1;
			},
			//复选框
			checkboxChange(e) {
				// console.log(e);
				console.log(this.privacyPolicyChecked);
			},
			childSexClick() {
				this.childSexShow = true;
			},
			childSexConfirm(e) {
				this.children.sex = e.value[0];
				this.childSexShow = false
			},
			childSexCancel() {
				this.childSexShow = false
			},

			childDateClick() {
				this.childDateShow = true;
			},
			childDateCancel() {
				this.childDateShow = false;
			},
			childDateConfirm(date) {
				this.children.birthday = uni.$u.timeFormat(date.value, 'yyyy-mm-dd');
				this.childDateShow = false;
			},
			cityClick() {
				console.log(342);
				this.cityShow = true
			},
			// 城市选择器
			initCityData() {
				// 遍历城市js
				cityData.forEach((item1, index1) => {
					let temp2 = [];
					this.cityLevel1.push(item1.provinceName);
					let temp4 = [];
					let temp3 = [];
					// 遍历市
					item1.cities.forEach((item2, index2) => {
						temp2.push(item2.cityName);
						// 遍历区
						item2.counties.forEach((item3, index3) => {
							temp3.push(item3.countyName);
						})
						temp4[index2] = temp3;
						temp3 = [];
					})
					this.cityLevel3[index1] = temp4;
					this.cityLevel2[index1] = temp2;
				})
				// 选择器默认城市
				this.cityList.push(this.cityLevel1, this.cityLevel2[0], this.cityLevel3[0][0]);
			},
			// 选中时执行
			changeHandler(e) {
				const {
					columnIndex,
					index,
					indexs,
					value,
					values,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e;
				if (columnIndex === 0) { // 选择第一列数据时
					// 设置第二列关联数据
					picker.setColumnValues(1, this.cityLevel2[index]);
					// 设置第三列关联数据
					picker.setColumnValues(2, this.cityLevel3[index][columnIndex]);
				} else if (columnIndex === 1) { // 选择第二列数据时
					// 设置第三列关联数据
					picker.setColumnValues(2, this.cityLevel3[indexs[0]][index]);
				}
			},

			// 单击确认按钮时执行
			cityConfirm(e) {
				// 输出数组 [省, 市, 区]
				console.log(e.value);
				this.cityName = e.value.join("-");
				this.children.state = e.value[0];
				this.children.city = e.value[1];
				this.children.district = e.value[2];
				// 隐藏城市选择器
				this.cityShow = false;
			},


			addressClick() {
				this.show = true
			},
			cancel() {
				this.show = false
			},
			confirm(e) {
				console.log(e.value);
				this.children.state = e.value[0].name
				this.children.city = e.value[1].name
				this.children.district = e.value[2].name
				this.cancel()
			},
			// 添加儿童信息
			async userAddChildren() {

				if (uni.$u.test.isEmpty(this.children.username)) {
					this.$refs.uToast.show({
						type: 'error',
						message: "请填写儿童姓名",
					})
					return
				}
				if (uni.$u.test.isEmpty(this.children.sex)) {
					this.$refs.uToast.show({
						type: 'error',
						message: "请选择儿童性别",
					})
					return
				}
				if (uni.$u.test.isEmpty(this.children.birthday)) {
					this.$refs.uToast.show({
						type: 'error',
						message: "请选择出生日期",
					})
					return
				}
				if ((this.deptId && this.deptId != 100) && uni.$u.test.isEmpty(this.children.deptId)) {
					return uni.showToast({
						title: '请选择所在机构',
						icon: 'none'
					})
				}
				// if (uni.$u.test.isEmpty(this.children.idCard)) {
				// 	this.$refs.uToast.show({
				// 		type: 'error',
				// 		message: "请填写身份证号码",
				// 	})
				// 	return
				// }
				// if (!uni.$u.test.idCard(this.children.idCard)) {
				// 	this.$refs.uToast.show({
				// 		type: 'error',
				// 		message: "身份证号码不正确",
				// 	})
				// 	return
				// }
				if (uni.$u.test.isEmpty(this.children.parentName)) {
					this.$refs.uToast.show({
						type: 'error',
						message: "请填写家长姓名",
					})
					return
				}
				if (uni.$u.test.isEmpty(this.children.tel)) {
					this.$refs.uToast.show({
						type: 'error',
						message: "请填写家长手机号",
					})
					return
				}
				if (!uni.$u.test.mobile(this.children.tel)) {
					this.$refs.uToast.show({
						type: 'error',
						message: "家长手机号填写不正确",
					})
					return
				}
				if (uni.$u.test.isEmpty(this.children.relation)) {
					this.$refs.uToast.show({
						type: 'error',
						message: "请填写与儿童关系",
					})
					return
				}
				// if (uni.$u.test.isEmpty(this.children.state) || uni.$u.test.isEmpty(this.children.city) || uni.$u.test
				// 	.isEmpty(this.children.district)) {
				// 	this.$refs.uToast.show({
				// 		type: 'error',
				// 		message: "请选择省市县",
				// 	})
				// 	return
				// }
				// if (uni.$u.test.isEmpty(this.children.address)) {
				// 	this.$refs.uToast.show({
				// 		type: 'error',
				// 		message: "请填写详细地址",
				// 	})
				// 	return
				// }

				const res = await this.$myRequest({
					url: '/system/children/userAddChildren',
					method: 'POST',
					data: this.children
				})
				uni.redirectTo({
					url: `/tablePackage/pages/answerDetail?alias=${this.tableAlias}&selectedChildId=${res.data.data}`
				})
				return
				if (res.data.code == 200) {
					this.selectedChildId = res.data.data;
					this.$refs.uToast.show({
						type: 'success',
						message: res.data.msg,
						complete: () => {
							//查询支付信息//查询支付信息
							openPay().then(rex => {
								console.log(237, rex)
								if (rex.msg == "false") {
									//关闭支付功能
									uni.redirectTo({
										url: `/tablePackage/pages/answerDetail?alias=${this.tableAlias}&selectedChildId=${res.data.data}`
									})
								} else {
									//开启支付功能
									prepayment(this.deptId).then(res1 => {
										console.log(2262, res1);
										if (res1.paySign) {
											this.prepay = res1;
											//未购买，显示价格
											lbPrice().then(res2 => {
												console.log(266, res2);
												this.price = res2.msg;
												this.payShow = true;
											})
										} else {
											//已购买
											uni.redirectTo({
												url: `/tablePackage/pages/answerDetail?alias=${this.tableAlias}&selectedChildId=${res.data.data}`
											})
										}
									})
								}
							})

						}
					})
				} else {
					uni.navigateTo({
						url: '/loginPackage/Login'
					});
				}
			},
			async userChildrenById(id) {
				const res = await this.$myRequest({
					url: '/system/children/userChildrenById/' + id,
					method: 'GET'
				})
				this.children = res.data.data
			},
			// 儿童列表信息
			async userChildrenslist() {
				this.childListPickerShow = true;
				this.childListPickerLoading = true;
				const res = await this.$myRequest({
					url: '/system/children/userChildrenslist'
				})
				if (res.data.code == 200) {
					this.childListPickerLoading = false;
					this.childList = [];
					this.childList.push(res.data.rows)
				}

			},
			// 回调参数为包含columnIndex、value、values
			childListPickerConfirm(e) {
				// console.log('confirm', e.value[0])
				this.selectedChild = e.value[0];
				this.childListPickerClose()
			},
			childListPickerClose() {
				this.childListPickerShow = false
			},




		}
	}
</script>

<style lang="less">
	.top-haed {
		width: 60%;
		margin: 0 auto;
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 44px;

		.title_ {
			font-weight: bold;
		}

	}

	.content {
		.head {
			width: 60%;
			height: 350px;
			margin: 0 auto;

			image {
				width: 100%;
				height: 350px;
			}
		}

		.form-area {
			width: 90%;
			margin: 0 auto;

			.form-inner {
				width: 90%;
				margin: 0 auto;
				height: 100%;
				background-color: #fff;
				border-radius: 20rpx;
				display: flex;
				flex-direction: column;
				align-items: center;

				.form-item {
					width: 95%;
					height: 100rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;
					border-bottom: 2rpx #EEEEF0 solid;

					.form-item-label {
						font-size: 28rpx;
						font-weight: bold;
						color: #101010;
						margin-left: 10rpx;
					}

					.form-item-input {
						cursor: pointer;
						width: 350rpx;
						height: 50rpx;
						margin-right: 10rpx;

					}
				}
			}
		}

		.con {
			width: 60%;
			line-height: 20px;
			border-radius: 10px;
			background-color: rgba(255, 255, 255, 1);
			text-align: center;
			box-shadow: 0px 2px 6px 0px rgba(228, 228, 228, 100);
			margin: 0 auto;

			.tab-con {
				display: flex;

				.tab {
					width: 50%;
					height: 94rpx;
					line-height: 94rpx;

					&.tab-first {
						background-color: rgba(40, 123, 206, 1);
						color: #fff;
						border-top-left-radius: 20rpx;
					}

					&.tab-second {
						background-color: rgba(40, 123, 206, 1);
						color: #fff;
						border-top-right-radius: 20rpx;
					}
				}
			}
		}

		.privacy-policy {
			width: 90%;
			margin: 0 auto;
			height: 100rpx;
			display: flex;
			align-items: center;

			.privacy-policy-checkbox {
				margin-left: 20rpx;
			}

			.privacy-policy-text {
				margin-left: 10rpx;
				font-size: 26rpx;
				color: #000000;

				.privacy-policy-text-btn {
					color: #000000;
				}
			}

		}

		.btn {
			width: 332px;
			height: 50px;
			border-radius: 30px;
			background-color: rgba(40, 123, 206, 1);
			color: rgba(255, 255, 255, 1);
			font-size: 14px;
			text-align: center;
			line-height: 100rpx;
			margin: 20rpx auto;
		}

	}

	.bo-box {
		width: 95%;
		margin: 15px auto;
	}
</style>