<template>
	<view class="container">
		<view class="header_banner"></view>
		<view class="header">
			<view class="avatar-container">
				<image v-if="userInfo.avatarUrl" :src="userInfo.avatarUrl"
					style="width:80px;height:80px;border-radius:50%" @tap="handleAvatarClick" />
				<button v-else open-type="chooseAvatar" @chooseavatar="onChooseAvatar">选择头像</button>
				<image src="/static/images/v.png" v-if="examine==1"
					style="position: absolute;bottom: 15px;right: 5px; width: 20px;height: 20px;"></image>
			</view>
			<view class="header_box">
				<view class="left">
					<view class="phone_name">
						<image src="/static/images/myUser.png" alt="" style="width: 24px;height: 24px;" />
						:
						<view class="user_name">
							<!-- <text v-if="userInfo.customName" style="margin-left:10px">{{ userInfo.customName }}</text>else- -->
							<text v-if="userInfo.nickName" style="margin-left:10px">{{ userInfo.nickName }}</text>
							<button v-else open-type="getUserProfile" @tap="getUserProfile" class="text-style-button"
								style="margin-left: 15px;color: #1296db;">获取微信昵称</button>
						</view>
						<button v-if="userInfo.nickName||userInfo.customName" @tap="showNameInput"
							class="text-style-button"
							style="margin-left: 15px;color: #1296db;text-decoration: underline">修改</button>
					</view>
					<view class="phone_name">
						<image src="/static/images/手机号码.png" mode="aspectFit" style="width: 24px; height: 24px;">
						</image>
						:
						<view style="margin-left:15px;">
							<button v-if="!userInfo.phoneNumber" open-type="getPhoneNumber"
								@getphonenumber="onGetPhoneNumber" class="text-style-button"
								style="color: #1296db;">获取手机号</button>
							<text v-else>{{ userInfo.phoneNumber }}</text>
						</view>
						<button v-if="userInfo.phoneNumber" open-type="getPhoneNumber"
							@getphonenumber="onGetPhoneNumber" class="text-style-button"
							style="margin-left: 15px;color: #1296db;text-decoration: underline">修改</button>
					</view>
					<view style="display: flex;">
						<image src="/static/images/用户类型.png" mode="aspectFit" style="width: 20px; height: 20px;">
						</image>
						:
						<view class="picker" style="margin-left: 10px;"><!-- { color: isChanged ? '#999' : '#000' } -->
							{{ array && array[examine] ? array[examine].name : '' }}
						</view>
						<button v-if="examine==0" @tap="openForm" class="text-style-button"
							style="margin-left: 15px;color: #1296db;text-decoration: underline">员工认证</button>
						<text v-if="examine==2" style="margin-left: 15px;color: #1296db;">认证中</text>
						<!-- <picker @change="onPickerChange" :value="index" :range="array" range-key="name"
							:disabled="isChanged" style="border: 1px solid #ccc;">
							<view class="picker" @tap="openForm" :style="{ color: isChanged ? '#999' : '#000' }">
								当前选择：<text>{{ array[index].name }}</text> 
								<text v-if="isChanged">(待审核)</text>
							</view>
						</picker> -->
					</view>

				</view>
				<!-- <view class="right" @click="goToSettings">
					<image src="/static/images/setting.png" style="width:24px;height:24px"></image>
				</view> -->
			</view>

		</view>
		<!-- 新增弹窗表单 -->
		<uni-popup ref="popup" type="center">
			<view class="popup-content">
				<view class="popup-header">
					<text class="popup-title">用户信息</text>
					<text class="popup-close" @tap="closePopup">×</text>
				</view>
				<form @submit="submitForm">
					<view class="form-item">
						<text>微信昵称：</text>
						<input type="text" v-model="formData.nickName" placeholder="微信昵称" required />
					</view>
					<view class="form-item">
						<text>姓名：</text>
						<input type="text" v-model="formData.realName" placeholder="姓名" required />
					</view>
					<view class="form-item">
						<text>手机号：</text>
						<input type="number" v-model="formData.phoneNumber" placeholder="手机号" required
							@blur="validatePhoneNumber" />
						<text v-if="errors.phoneNumber" class="error-message">{{ errors.phoneNumber }}</text>
					</view>
					<view class="form-item">
						<text>身份证号：</text>
						<input type="idcard" v-model="formData.idCard" placeholder="身份证号" required
							@blur="validateIdCard" />
						<text v-if="errors.idCard" class="error-message">{{ errors.idCard }}</text>
					</view>
					<view class="form-item">
						<text>用户类型：</text>
						<picker @change="onFormPickerChange" :value="formData.userType" :range="array" range-key="name">
							<view class="picker">
								{{ array[formData.userType].name }}
							</view>
						</picker>
					</view>
					<button form-type="submit">提交</button>
				</form>
			</view>
		</uni-popup>
		<view v-if="showNamePopup" class="custom-popup">
			<view class="custom-popup-content">
				<text>输入您的名称</text>
				<input v-model="tempCustomName" placeholder="请输入您的名称" />
				<view class="custom-popup-buttons">
					<button @tap="closeNamePopup">取消</button>
					<button @tap="confirmCustomName">确定</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				openId: '',
				userInfo: {
					avatarUrl: '',
					nickName: '',
					customName: '',
					phoneNumber: ''
				},
				tempCustomName: '',
				showNamePopup: false,
				array: [{
					id: 1,
					name: "游客",
					value: "0"
				}, {
					id: 2,
					name: "员工",
					value: "1"
				}, {
					id: 3,
					name: "游客",
					value: "2"
				}],
				index: 0,
				examine: 0,
				isChanged: false,
				// 表单
				formData: {
					nickName: '',
					realName: '',
					phoneNumber: '',
					idCard: '',
					userType: 0
				},
				errors: {
					phoneNumber: '',
					idCard: ''
				},
				apiUrl: 'https://ylaiapi.raycos.com.cn' //https://qlaiapi.raycos.com.cn'https://doc.shqlsy.com',https://ylaiapi.raycos.com.cn

			}
		},
		onLoad() {
			console.log('onLoad 被调用')
			this.checkLogin()
			this.handleLogin()

		},
		onShow() {
			console.log('onShow 被调用')
			if (this.openId) {
				this.showLoginButton = false
			} else {
				this.checkLogin()
			}
		},
		methods: {
			/* 表单操作 */
			closePopup() {
				this.$refs.popup.close();
			},
			openForm() {
				if (!this.openId) {
					uni.showToast({
						title: '请登录',
						icon: 'none'
					});
					return
				}
				this.formData.nickName = this.userInfo.nickName || '';
				this.formData.phoneNumber = this.userInfo.phoneNumber || '';
				this.formData.userType = 1;
				this.$refs.popup.open();
			},
			onFormPickerChange(e) {
				this.formData.userType = e.detail.value;
			},
			validatePhoneNumber() {
				const phoneRegex = /^1[3-9]\d{9}$/;
				if (!phoneRegex.test(this.formData.phoneNumber)) {
					this.errors.phoneNumber = '请输入有效的11位手机号码';
				} else {
					this.errors.phoneNumber = '';
				}
			},

			validateIdCard() {
				const idCardRegex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
				if (!idCardRegex.test(this.formData.idCard)) {
					this.errors.idCard = '请输入有效的身份证号码';
				} else {
					this.errors.idCard = '';
				}
			},

			submitForm() {
				this.validatePhoneNumber();
				this.validateIdCard();

				if (this.errors.phoneNumber || this.errors.idCard) {
					uni.showToast({
						title: '请修正表单错误',
						icon: 'none'
					});
					return;
				}

				if (!this.formData.nickName || !this.formData.realName || !this.formData.phoneNumber || !this.formData
					.idCard) {
					uni.showToast({
						title: '请填写所有必填字段',
						icon: 'none'
					});
					return;
				}
				uni.request({
					url: this.apiUrl + '/wechat/updateUserInfo',
					method: 'POST',
					data: {
						openid: this.openId,
						purePhoneNumber: this.formData.phoneNumber,
						id_card: this.formData.idCard,
						name: this.formData.realName,
						nikeName: this.formData.nickName,
						examine: 2
					}, //JSON.stringify()level: this.formData.userType,
					header: {
						'content-type': 'application/x-www-form-urlencoded' // 设置正确的内容类型
					},
					success: (res) => {
						console.log(res);
						if (res.data && res.data.status == 200) {
							this.$refs.popup.close();
							this.getUserInfo()
							uni.showToast({
								title: '提交成功！',
								icon: 'success'
							});
						} else {
							console.error('提交失败', res);
							uni.showToast({
								title: res.data && res.data.message ? res.data.message : '提交失败，请重试',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error('请求失败', err);
						uni.showToast({
							title: '网络错误，请重试',
							icon: 'none'
						});
					}
				});
				//console.log('Form submitted:', this.formData);

				// 更新页面上的用户类型显示
				//this.index = this.formData.userType;
				//this.submitToBackend();
			},
			/* 终 */
			/* 获取昵称 */
			getUserProfile() {
				uni.getUserProfile({
					desc: '用于完善会员资料',
					success: (res) => {
						this.userInfo.nickName = res.userInfo.nickName;
						this.saveUserInfo();
						console.log('获取用户信息成功', res.userInfo);
					},
					fail: (err) => {
						console.error('获取用户信息失败', err);
						uni.showToast({
							title: '获取用户信息失败',
							icon: 'none'
						});
					}
				});
			},

			showNameInput() {
				this.tempCustomName = this.userInfo.customName || this.userInfo.nickName || '';
				this.showNamePopup = true;
			},

			confirmCustomName() {
				this.userInfo.customName = this.tempCustomName;
				uni.request({
					url: this.apiUrl + '/wechat/updateNikeName',
					method: 'POST',
					data: {
						nikeName: this.userInfo.customName,
						openid: this.openId
					}, //JSON.stringify()
					header: {
						'content-type': 'application/x-www-form-urlencoded' // 设置正确的内容类型
					},
					success: (res) => {
						if (res.data && res.data.status == 200) {
							this.saveUserInfo();
							this.getUserInfo()
							this.closeNamePopup();
							uni.showToast({
								title: '修改成功',
								icon: 'success'
							});
						} else {
							console.error('修改失败', res);
							uni.showToast({
								title: '修改失败',
								icon: 'none'
							});
						}
					}
				});

			},

			closeNamePopup() {
				this.showNamePopup = false;
			},

			getUserInfo() {
				uni.request({
					url: this.apiUrl + '/wechat/getUserInfo',
					method: 'POST',
					data: {
						openid: this.openId
					},
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
						console.log('获取用户信息成功', res.data);
						if (res.data && res.data.data) {
							this.examine = Number(res.data.data.examine);

							// 检查 nikeName 是否为空或 null
							if (!res.data.data.nikeName || res.data.data.nikeName === 'null') {
								console.log('服务器返回的 nickName 为空或 null，保持当前昵称不变');
							} else {
								// 如果不为空，则使用服务器返回的 nickName
								this.userInfo.nickName = res.data.data.nikeName;

								// 更新本地存储
								this.updateLocalStorage();
							}

							this.isChanged = this.userInfo.status === 5;
						}
					},
					fail: (err) => {
						console.error('获取用户信息失败', err);
						uni.showToast({
							title: '获取用户信息失败，请重试',
							icon: 'none'
						});
					}
				});
			},

			// 新增方法：更新本地存储
			updateLocalStorage() {
				const storedUserInfo = uni.getStorageSync('userInfo');
				if (storedUserInfo) {
					const parsedUserInfo = JSON.parse(storedUserInfo);
					parsedUserInfo.nickName = this.userInfo.nickName;
					uni.setStorageSync('userInfo', JSON.stringify(parsedUserInfo));
				} else {
					// 如果本地存储中没有 userInfo，则直接存储当前的 userInfo
					uni.setStorageSync('userInfo', JSON.stringify(this.userInfo));
				}
				console.log('本地存储的 userInfo 已更新');
			},

			onPickerChange(e) {
				if (!this.isChanged) {
					this.index = e.detail.value;
					console.log('picker发送选择改变，携带值为', this.array[this.index].name);

					// 调用提交数据的方法
					this.submitToBackend();
				}
			},

			submitToBackend() {
				uni.request({
					url: this.apiUrl + '/wechat/updateUserInfo', // 请确保这是正确的接口地址
					method: 'POST',
					data: {
						openid: this.openId,
						level: this.index, // 提交 index 作为参数
						phoneNumber: this.userInfo.phoneNumber,
						status: 5
					},
					header: {
						'content-type': 'application/x-www-form-urlencoded' // 设置正确的内容类型
					},
					success: (res) => {
						console.log('提交成功', res.data);
						this.isChanged = true; // 标记为已变更
						uni.showToast({
							title: '更新成功,待审核',
							icon: 'success'
						});
					},
					fail: (err) => {
						console.error('提交失败', err);
						uni.showToast({
							title: '更新失败，请重试',
							icon: 'none'
						});
					}
				});
			},

			restoreOpenId() {
				const storedOpenId = uni.getStorageSync('openId')
				if (storedOpenId) {
					this.openId = storedOpenId
					console.log('恢复 openId:', this.openId)
				} else {
					console.log('未找到存储的 openId，需要重新登录')
					this.login()
				}
			},
			checkLogin() {
				uni.checkSession({
					success: () => {
						console.log('Session 有效')
						this.loadUserInfo()
						this.showLoginButton = false
					},
					fail: () => {
						console.log('Session 已过期，需要重新登录')
						this.showLoginButton = true
					}
				})
			},
			login() {
				console.log('执行login')
				uni.login({
					success: (res) => {
						if (res.code) {
							console.log('获取到登录code:', res); // 添加日志
							this.requestLogin(res.code)
						} else {
							console.log('获取code失败！' + res.code)
						}
					}
				})
			},
			requestLogin(code) {
				console.log('Sending login request with code:', code); // 添加日志
				uni.request({
					url: this.apiUrl + '/wechat/wechatLogin', // 确保这是正确的URL
					method: 'POST',
					data: {
						code: code
					}, //JSON.stringify()
					header: {
						'content-type': 'application/x-www-form-urlencoded' // 设置正确的内容类型
					},
					success: (res) => {
						console.log('Login response:', res.data);
						if (res.data && res.data.status === 200 && res.data.data && res.data.data.openid) {
							this.openId = res.data.data.openid;
							// 存储整个 res.data.data 对象
							uni.setStorageSync('userData', JSON.stringify(res.data.data));
							uni.setStorageSync('openId', this.openId);
							console.log('登录成功，openId:', this.openId);
							this.showLoginButton = false;
							this.loadUserInfo();
							this.getUserInfo();	
						} else {
							console.error('登录失败，未获取到 openId', res.data);
							this.showLoginButton = true;
							uni.showToast({
								title: '登录失败，请重试',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error('登录请求失败', err);
						this.showLoginButton = true;
						uni.showToast({
							title: '登录失败，请重试',
							icon: 'none'
						});
					}
				})
			},
			loadUserInfo() {
				const storedInfo = uni.getStorageSync('userInfo')
				if (storedInfo) {
					this.userInfo = JSON.parse(storedInfo)
					this.showLoginButton = false
				} else {
					this.showLoginButton = true
				}
			},
			handleAvatarClick() {
				console.log('头像被点击')
			},
			onChooseAvatar(e) {
				this.userInfo.avatarUrl = e.detail.avatarUrl
				console.log(this.userInfo.avatarUrl);
				this.saveUserInfo()
			},
			onGetPhoneNumber(e) {
				console.log(e);
				if (e.detail.errMsg === 'getPhoneNumber:ok') {
					const code = e.detail.code;
					console.log('onGetPhoneNumber called, current openId:', this.openId);
					if (this.openId) {
						this.requestPhoneNumber(e.detail.code, this.openId);
					} else {
						console.error('openId 未定义，无法获取手机号');
						uni.showToast({
							title: '获取手机号失败，请先登录',
							icon: 'none'
						});
					}
				} else {
					console.error('获取手机号失败', e.detail.errMsg);
					uni.showToast({
						title: '获取手机号失败',
						icon: 'none'
					});
				}
			},
			requestPhoneNumber(code, openId) {
				uni.request({
					url: this.apiUrl + '/wechat/getUserPhoneNumber',
					method: 'POST',
					data: {
						code: code,
						openid: openId
					}, //JSON.stringify()
					header: {
						'content-type': 'application/x-www-form-urlencoded' // 设置正确的内容类型
					},
					success: (res) => {
						if (res.data && res.data.data.purePhoneNumber) {
							this.userInfo.phoneNumber = res.data.data.purePhoneNumber;
							this.saveUserInfo();
							uni.showToast({
								title: '获取手机号成功',
								icon: 'success'
							});
						} else {
							console.error('获取手机号失败', res);
							uni.showToast({
								title: '获取手机号失败',
								icon: 'none'
							});
						}
					}
				});
			},
			saveUserInfo() {
				uni.setStorageSync('userInfo', JSON.stringify(this.userInfo))
				this.showLoginButton = false
			},
			handleLogin() {
				this.login()
			},
			goToSettings() {
				uni.navigateTo({
					url: '/pages/my/setting/setting',
					success: (res) => {
						console.log('成功跳转到设置页面');
					},
					fail: (err) => {
						console.error('跳转到设置页面失败', err);
						uni.showToast({
							title: '跳转失败，请重试',
							icon: 'none'
						});
					}
				});
			}
		}
	}
</script>

<style>
	.container {

		min-height: 100vh;
	}

	.header_banner {
		width: 100%;
		height: 200px;
		background-color: #1296db;
		border-radius: 0 0 30px 30px;
	}

	.header {

		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 20px 20px;
		margin-top: -50px;
	}

	.header_box {
		width: 100%;
		display: flex;
		align-items: flex-start;
		justify-content: space-between;

	}

	.phone_name {
		display: flex;
		align-items: center;
		margin-bottom: 15px;

	}

	.avatar-container {
		width: 90px;
		height: 90px;
		border-radius: 50%;
		overflow: hidden;
		position: relative;
	}

	.avatar-container button {

		width: 100%;
		height: 100%;
		padding: 30px 10px;
		background-color: royalblue;
		z-index: 5;
	}

	.left {
		display: flex;
		flex-direction: column;

	}

	.right {
		padding: 10px;
	}

	button {

		background-color: #1296db;
		color: #fff;
		border: none;
		border-radius: 5px;
		padding: 2px 7px;
		font-size: 14px;
	}

	::v-deep .uni-popup__wrapper {
		width: 80%;
		max-width: 600px;
	}

	.popup-content {
		background-color: #fff;
		padding: 20px;
		border-radius: 10px;
	}

	.form-item {
		margin-bottom: 15px;
	}

	.form-item text {
		display: block;
		margin-bottom: 5px;
	}

	.form-item input {

		height: 40px;
		border: 1px solid #ccc;
		border-radius: 5px;
		padding: 0 10px;
	}

	.error-message {
		color: red;
		font-size: 12px;
		margin-top: 5px;
	}

	.text-style-button {
		background: none;
		border: none;
		color: #000;
		/* Or any color you prefer */
		padding: 0;
		font: inherit;
		cursor: pointer;
		outline: inherit;
		/* text-decoration: underline; */
	}

	.text-style-button:hover {
		opacity: 0.8;
	}

	.text-style-button:after {
		border: none;
	}

	.custom-popup {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 999;
	}

	.custom-popup-content {
		background-color: #fff;
		padding: 20px;
		border-radius: 10px;
		width: 80%;
		max-width: 300px;
	}

	.custom-popup-content input {
		width: 100%;
		margin: 10px 0;
		padding: 5px;
		border: 1px solid #ccc;
		border-radius: 5px;
	}

	.custom-popup-buttons {
		display: flex;
		justify-content: space-between;
		margin-top: 15px;
	}

	.custom-popup-buttons button {
		width: 45%;
	}

	.popup-content {
		background-color: #fff;
		padding: 20px;
		border-radius: 10px;
		width: 80%;
		max-width: 600px;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
	}

	.popup-title {
		font-size: 18px;
		font-weight: bold;
	}

	.popup-close {
		font-size: 24px;
		cursor: pointer;
		padding: 5px;
	}
</style>