<template>
	<div class="container">
		<!-- <view class="title-back">
			<view class="left-father" @click="goBack">
				<image class="back-img" src="https://www.focusnu.com/media/directive/index/left.png" />
				<view style="font-size: 30rpx;">监护人信息</view>
			</view>
		</view> -->
		<image class="greenbgc" src="https://www.focusnu.com/media/directive/index/greenbgc.png" />
		<view class="title-back" :style="{height:`${uni.getStorageSync('moveHeight')+40}px`}">
			<view class="left-father" @click="goBack">
				<image class="back-img" src="https://www.focusnu.com/media/directive/index/left.png" />
				<view style="font-size: 30rpx;">监护人信息</view>
			</view>
		</view>
		<view :style="{height:`${uni.getStorageSync('moveHeight') + 40}px`}"></view>
		<view class="white-content">
			<view class="content-title">
				<view class="shu"></view>
				<view class="content-weight">监护人基本信息</view>
			</view>
			<view class="white-photo" @click="selectphoto()">
				<view class="photo-left">
					<view class="photo-weight">监护人人像面</view>
					<view class="photo-font">请上传身份证人像面</view>
				</view>
				<view style="position: relative;">
					<image class="photo"
						:src="specialImge ? `${media_base_url}${specialImge}` : `https://www.focusnu.com/media/directive/index/IDfront.png`" />
					<image style="width: 100%;height: 100%;top: 0;left: 0;z-index: 1;position: absolute;"
						:src="specialImge ? `` : `https://www.focusnu.com/media/directive/index/bian.png`" />
					<image v-if="!specialImge"
						style="position: absolute;top: 50%;left: 50%;width: 70rpx;height: 60rpx;transform: translate(-50%,-50%);"
						src="https://www.focusnu.com/media/directive/index/takephoto.png" />
				</view>

			</view>
			<view class="white-message">
				<view>
					<!-- <view class="one">
						<view class="one-left">与长者关系</view>
						<input class="one-right" maxlength="10" placeholder="请输入与长者关系" v-model="form.relationship" />
					</view> -->
					<view class="one">
						<view class="one-left">姓名</view>
						<input class="one-right" maxlength="5" placeholder="请输入姓名" v-model="form.name" />
					</view>

					<view class="one">
						<view class="one-left">电话</view>
						<input class="one-right" type="number" maxlength="11" placeholder="请输入电话" v-model="form.tel" />
					</view>
					<view class="one">
						<view class="one-left">身份证号</view>
						<input class="one-right" type="number" maxlength="18" placeholder="请输入身份证号"
							v-model="form.idCard" />
					</view>
					<view class="one">
						<view class="one-left">家庭住址</view>
						<input class="one-right" maxlength="30" placeholder="请输入家庭住址" v-model="form.homeAddress" />
					</view>
					<view class="one">
						<view class="one-left">工作单位</view>
						<input class="one-right" maxlength="40" placeholder="请输入工作单位" v-model="form.workUnit" />
					</view>
				</view>
			</view>
		</view>
		<view style="display: flex;width: 100%;position: fixed;bottom: 20rpx;left: 0;">
			<view class="finish-button" @click="next">
				提交
			</view>
		</view>
		<u-action-sheet :list="bottomlist" @click="photoclick" v-model="bottomshow"></u-action-sheet>
	</div>
</template>

<script setup>
	import {
		ref,
		reactive
	} from 'vue'
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';
	import {
		base_url,
		media_base_url
	} from '@/request/index.js';
	import {
		savePayer,
		changePayer
	} from './api/api.js'
	import {
		getMessage
	} from '@/api/loginApi.js'
	
	const bottomshow = ref(false);

	const form = reactive({
		name: "",
		tel: "",
		advisoryType: 1,
		status: 2,
		idCard: "",
		homeAddress: "",
		workUnit: "",
		izJs: 1,
		openId: uni.getStorageSync('openid'),
		relationship: ""
	})
	const bottomlist = [{
		text: '拍摄图片',
		fontSize: 40
	}, {
		text: '图片预览',
		fontSize: 40
	}]

	function isValid11DigitNumber(val) {
		// return /^(\d{11})$/.test(val);
		return /^1[3-9]\d{9}$/.test(val);
	}

	function isValid18DigitNumber(val) {
		return /^(\d{18})$/.test(val);
	}
	const photoclick = (element) => {
		if (element) {
			uni.previewImage({
				urls: [specialImgeshow.value], // 必填，所有要预览的图片地址数组
				current: specialImgeshow.value, // 可选，当前显示图片的地址，默认是 urls[0]
				indicator: 'default', // 可选，指示器样式，H5/App 有效，值为 'default'（圆点）或 'number'（数字）
				longPressActions: { // 可选，仅 App 支持，长按图片时弹出的操作项
					itemList: ['保存图片到相册'],
				},
			});
		} else {
			angetMessage()
		}

	}
	const specialImge = ref("")
	const uping = ref(true)
	const selectphoto = () => {
		// console.log("0000",bottomshow.value)
		if (!uping.value) {
			return
		}

		if (specialImge.value) {
			
			bottomshow.value = true;
			
		} else {
			angetMessage()
		}
	}
	// 拍照并上传
	function angetMessage() {
		// 使用 UniApp 的 API 调用摄像头
		uni.chooseImage({
			count: 1,
			sourceType: ['album', 'camera'],
			success: chooseRes => {
				// tempImagePath.value = chooseRes.tempFilePaths[0]
				// 拍照成功后，调用上传函数
				uni.navigateTo({
					url: `/compontent/public/camera?url=${chooseRes.tempFilePaths[0]}&type=0`
				});
			},
			fail: err => {
				console.error('拍照失败：', err)
			}
		})
	}
	const ukey = ref(
		`${uni.getStorageSync('openid') || ''}jhbg${String(Date.now()).slice(-5)}${String(Math.floor(Math.random() * 900) + 100)}`
	)
	const next = () => {

		// if (!form.relationship) {
		// 	uni.showToast({
		// 		title: '请填写与长者关系',
		// 		icon: 'error'
		// 	})
		// } else
		if (!form.name) {
			uni.showToast({
				title: '请填写姓名',
				icon: 'error'
			})
		} else if (!form.tel) {
			uni.showToast({
				title: '请填写电话',
				icon: 'error'
			})
		} else if (!isValid11DigitNumber(form.tel)) {
			uni.showToast({
				title: '电话格式错误',
				icon: 'none'
			})
			return
		} else if (!form.idCard) {
			uni.showToast({
				title: '请填写身份证号',
				icon: 'error'
			})
		} else if (!isValid18DigitNumber(form.idCard)) {
			uni.showToast({
				title: '身份证号格式错误',
				icon: 'none'
			})
			return
		} else if (!form.homeAddress) {
			uni.showToast({
				title: '请填写家庭住址',
				icon: 'error'
			})
		} else if (!form.workUnit) {
			uni.showToast({
				title: '请填写工作单位',
				icon: 'error'
			})
		} else {
			if (uni.getStorageSync('allinfo').name) {
				let data = uni.getStorageSync('allinfo');
				data.guardianName = form.name
				data.guardianPhone = form.tel
				data.guardianIdCard = form.idCard
				data.guardianHomeAddress = form.homeAddress
				data.guardianWorkUnit = form.workUnit
				data.relationship = form.relationship
				data.guardianIdCardPositive = specialImge.value
				data.modifyType = "jhr"
				const urlpost = `${base_url}/api/elderInfo/updateElderInfo?ukey=${ukey.value}`;
				uni.request({
					url: urlpost,
					method: 'POST',
					header: {
						'Content-Type': 'application/json',
						'X-Access-Token': uni.getStorageSync('token') || '',
					},
					data: data,
					success: (res) => {
						if (res.data.result == '重复提交') {
							uni.showToast({
								title: `重复提交`,
								icon: 'error'
							})
							return
						}
						if (res.data.result == '未做变更') {
							uni.showToast({
								title: `当前无变更，无需提交`,
								icon: 'none'
							})
							return
						}
						if (res.data.success) {
							getMessage(uni.getStorageSync('openid')).then(res => {
								uni.setStorageSync('allinfo', res.result);
								uni.reLaunch({
									url: '/pages/oldmanindex/oldmansuccess?type=1&jianhu=1'
								})
							})
						}
					},
					fail: (e) => {
						console.log("????", e)
					}
				});
			} else {
				let data = {}
				data.guardianName = form.name
				data.guardianPhone = form.tel
				data.guardianIdCard = form.idCard
				data.guardianHomeAddress = form.homeAddress
				data.guardianWorkUnit = form.workUnit
				data.relationship = form.relationship
				data.guardianIdCardPositive = specialImge.value
				const urlpost = `${base_url}/api/elderInfo/addElder?ukey=${ukey.value}`;
				uni.request({
					url: urlpost,
					method: 'POST',
					header: {
						'Content-Type': 'application/json',
						'X-Access-Token': uni.getStorageSync('token') || '',
					},
					data: data,
					success: (res) => {

						if (res.data.result == '重复提交') {
							uni.showToast({
								title: `重复提交`,
								icon: 'error'
							})
							return
						}
						if (res.data.result == '未做变更') {
							uni.showToast({
								title: `当前无变更，无需提交`,
								icon: 'none'
							})
							return
						}
						if (res.data.code != 200) {
							uni.showToast({
								title: res.data.message,
								icon: 'none', // 'success' 成功图标，'none' 无图标
								duration: 2000 // 显示时长 ms
							})
							return
						} else {
							uni.reLaunch({
								url: '/pages/oldmanindex/oldmansuccess?type=1&jianhu=1'
							})
						}

						//  return
						// 		const connectinon = {
						// 			nuId: data.nuId,
						// 			openId: uni.getStorageSync('openid'),
						// 			elderId: r.data.result,
						// 			sysOrgCode: data.sysOrgCode,

						// 		}
						// 		const urlpost = `${payurl.value}/api/nuBaseInfo/bindNu`;
						// 		uni.request({
						// 			url: urlpost,
						// 			method: 'POST',
						// 			header: {
						// 				'Content-Type': 'application/json',
						// 				'X-Access-Token': uni.getStorageSync('token') || '',
						// 			},
						// 			data: connectinon,
						// 			success: (r) => {
						// 				uni.reLaunch({
						// 					url: '/pages/oldmanindex/oldmansuccess'
						// 				})

						// 				// console.log("????", r)
						// 			},
						// 			fail: (e) => {
						// 				// console.log("????", e)
						// 			}
						// 		});

						// console.log("????", r)
					},
					fail: (e) => {
						// console.log("????", e)
					}
				});
				/* savePayer(form).then((res) => {
					// if (res.code == 401) {
					// 	savePayer(form).then((res) => {
					// 		if (res.success) {
					// 			getMessage(uni.getStorageSync('openid')).then(res => {
					// 				uni.setStorageSync('allinfo', res.result);
					// 				uni.reLaunch({
					// 					url: "/pages/login/callback",
					// 				})
					// 			})
					// 		}
					// 	})
					// }
					if (res.success) {
						getMessage(uni.getStorageSync('openid')).then(res => {
							uni.setStorageSync('allinfo', res.result);
							uni.reLaunch({
								url: "/pages/login/callback",
							})
						})
					}
				}) */
			}
		}
	}
	const goBack = () => {
		uni.navigateBack()
	}
	const specialImgeshow = ref("")
	onLoad(() => {
		if (uni.getStorageSync('allinfo').name) {
			let data = uni.getStorageSync('allinfo');
			const keys = [
				"openId",
				"name",
				"tel",
				"advisoryType",
				"status",
				"idCard",
				"homeAddress",
				"workUnit",
				"izJs",
				"relationship"
			]

			keys.forEach(key => {
				form[key] = data[key] || ""
			})
			specialImge.value = data.guardianIdCardPositive
			specialImgeshow.value = media_base_url + data.guardianIdCardPositive
			console.log("????", uni.getStorageSync('allinfo'))
		}

	})
	// 上传图片到服务器
	function uploadImage(filePath) {
		uping.value = false;
		uni.showLoading()
		uni.uploadFile({
			url: `${base_url}/api/ocr/idCard`, // 替换为您的POST接口地址
			filePath,
			name: 'file', // 后端接收时的字段名
			header: {
				'X-Access-Token': uni.getStorageSync('token') || '',
			},
			formData: {},
			success: uploadRes => {
				if (!JSON.parse(uploadRes.data).success) {
					uni.hideLoading()
					uni.showToast({
						title: '识别失败',
						icon: 'error',
						duration: 2000
					})
					uping.value = true;
					return
				}
				
					if (JSON.parse(JSON.parse(uploadRes.data).result.data).data.face) {
						let father = JSON.parse(JSON.parse(uploadRes.data).result.data).data.face.data;
						specialImgeshow.value = filePath;
						form.name = father.name;
						form.idCard = father.idNumber;
						form.homeAddress = father.address
						savephoto(filePath);
					}
				
				
				
			},
			fail: err => {
				uni.showToast({
					title: '上传出错',
					icon: 'error'
				})
				uni.hideLoading()
			}
		})
	}
	const savephoto = (filePath, type) => {
		uni.uploadFile({
			url: `${base_url}/sys/common/upload`, // 替换为您的POST接口地址
			filePath,
			name: 'file', // 后端接收时的字段名
			header: {
				'X-Access-Token': uni.getStorageSync('token') || '',
			},
			formData: {
				biz: `temp`
			},
			success: uploadRes => {
				specialImge.value = JSON.parse(uploadRes.data).message
				uni.hideLoading()
				
				uping.value = true;
			},
			fail: err => {
				uni.showToast({
					title: '上传出错',
					icon: 'error'
				})
				uni.hideLoading()
			}
		})
	}
	onShow(() => {
		const img = uni.getStorageSync('imgkey0')
		if (img) {
			uploadImage(img)
			uni.removeStorageSync('imgkey0')
		}
	})
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		width: 100%;
		background-color: #F7F7F7;
		position: relative;

		.white-content {
			width: 90%;
			margin-left: 5%;
			border-radius: 35rpx;


			.content-title {
				display: flex;
				align-items: center;
				height: 100rpx;
				position: relative;
				font-weight: 600;

				.content-weight {
					font-size: 32rpx;
				}

				.content-img {
					position: absolute;
					right: 0;
					top: 0;
					width: 400rpx;
					height: 100%;
				}
			}
		}
	}


	.finish-button {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 80%;
		height: 90rpx;
		margin: 0rpx auto;
		margin-bottom: 80rpx;
		margin-top: 20rpx;
		background: linear-gradient(to bottom, #e7f4ff, #c5e5ff);
		border: 2rpx solid #9AD1FF;
		color: #007CFF;
		border-radius: 35rpx;
		font-size: 33rpx;
	}

	.title-back {
		background-color: #F7F7F7;
		width: 100%;
		height: 70rpx;
		display: flex;
		justify-content: space-between;
		align-items: flex-end;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #cbd1d2;
		position: fixed;
		top: 0;
		left: 0;
		z-index: 9999;
	}

	.left-father {
		display: flex;
		align-items: center;

		.back-img {
			width: 45rpx;
			height: 40rpx;
			margin-left: 40rpx;
			margin-right: 15rpx;
		}
	}

	.shu {
		width: 14rpx;
		height: 36rpx;
		background-color: #0097FF;
		border-radius: 10rpx;
		margin: 3rpx 20rpx 0 30rpx;
	}

	.white-message {
		width: 100%;
		margin-top: 20rpx;
		padding-top: 20rpx;
		padding-bottom: 20rpx;
		margin-bottom: 30rpx;
		border-radius: 35rpx;
		background-color: #fff;
		justify-content: space-around;
		display: flex;
		flex-direction: column;

		.one {
			width: 90%;
			margin-left: 5%;
			height: 100rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 10rpx;

			.one-left {
				margin-left: 10rpx;
				font-size: 30rpx;
				// color: red;
				color: black;
				z-index: 1;
			}

			.one-right {
				margin-right: 10rpx;
				font-size: 30rpx;
				color: #999999;
				overflow: hidden;
				/* 隐藏超出内容 */
				white-space: nowrap;
				/* 不换行 */
				text-overflow: ellipsis;
				max-width: 380rpx;
			}
		}
	}

	.greenbgc {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 700rpx;
	}
	.white-photo {
		width: 100%;
		height: 300rpx;
		border-radius: 35rpx;
		background-color: #fff;
		justify-content: space-around;
		align-items: center;
		display: flex;
	
		.photo {
			width: 300rpx;
			height: 200rpx;
		}
	}
	.photo-left {
		.photo-weight {
			font-size: 32rpx;
			font-weight: 600;
			color: #333;
		}
	
		.photo-font {
			font-size: 28rpx;
			margin-top: 10rpx;
			color: #666;
		}
	
	}
</style>