<template>
	<view class="container">
		<!-- 个人信息设置 -->
		<view class="profile-section">
			<!-- 头像 -->
			<!--      <view class="profile-item" @click="changeAvatar">
        <view class="item-label">头像</view>
        <view class="item-content">
          <image
            class="avatar"
            :src="userInfo.avatar"
            mode="aspectFill"
          ></image>
          <uv-icon name="arrow-right" size="16" color="#ccc"></uv-icon>
        </view>
      </view> -->

			<!-- 用户名 -->
			<view class="profile-item" @click="editUsername">
				<view class="item-label">用户名</view>
				<view class="item-content">
					<text class="item-value">{{ userStore.userInfo.username }}</text>
					<uv-icon name="arrow-right" size="16" color="#ccc"></uv-icon>
				</view>
			</view>

			<!-- 邮箱 -->
			<view class="profile-item" @click="editEmail">
				<view class="item-label">邮箱</view>
				<view class="item-content">
					<text class="item-value">{{ userStore.userInfo.email }}</text>
					<uv-icon name="arrow-right" size="16" color="#ccc"></uv-icon>
				</view>
			</view>

			<!-- 电话 -->
			<view class="profile-item" @click="changePhone">
				<view class="item-label">手机号</view>
				<view class="item-content">
					<text class="item-value">{{ userStore.userInfo.phone }}</text>
					<uv-icon name="arrow-right" size="16" color="#ccc"></uv-icon>
				</view>
			</view>
		</view>


		<!-- 应用设置 -->
		<!-- <view class="app-section">

			<view class="profile-item" @click="viewUserAgreement">
				<view class="item-label">用户协议</view>
				<view class="item-content">
					<uv-icon name="arrow-right" size="16" color="#ccc"></uv-icon>
				</view>
			</view>

			<view class="profile-item" @click="viewAbout">
				<view class="item-label">关于我们</view>
				<view class="item-content">
					<uv-icon name="arrow-right" size="16" color="#ccc"></uv-icon>
				</view>
			</view>
		</view> -->

		<!-- 退出登录按钮 -->
		<!-- <view class="logout-section">
			<uv-button type="primary" size="large" @click="logout" :loading="logoutLoading">
				退出登录
			</uv-button>
		</view> -->

		<!-- 编辑弹窗 -->
		<uv-popup ref="editPopup" mode="center" @close="closeEditModal" :round="10">
			<view class="edit-modal">
				<view class="modal-title">
					编辑{{
            editType === "username"
              ? "用户名"
              : editType === "phone"
              ? "电话"
              : editType === "email"
              ? "邮箱"
              : ""
          }}
				</view>
				<uv-input v-model="editValue" :placeholder="getPlaceholder()" :type="
            editType === 'phone'
              ? 'number'
              : editType === 'email'
              ? 'email'
              : 'text'
          " border="bottom" clearable></uv-input>
				<view class="modal-actions">
					<uv-button type="default" @click="closeEditModal">取消</uv-button>
					<uv-button type="primary" @click="saveEdit">保存</uv-button>
				</view>
			</view>
		</uv-popup>

		<!-- 头像选择弹窗 -->
		<uv-popup ref="avatarSheet" mode="bottom" @close="closeAvatarSheet" :round="10">
			<view class="avatar-sheet">
				<view class="sheet-header">
					<view class="sheet-title">选择头像</view>
				</view>
				<view class="sheet-actions">
					<view class="action-item" @click="selectAvatarSource('camera')">
						<uv-icon name="camera-fill" size="24" color="#4285f4"></uv-icon>
						<text class="action-text">拍照</text>
					</view>
					<view class="action-item" @click="selectAvatarSource('album')">
						<uv-icon name="photo-fill" size="24" color="#4285f4"></uv-icon>
						<text class="action-text">从相册选择</text>
					</view>
				</view>
				<view class="sheet-cancel">
					<uv-button type="default" size="large" @click="closeAvatarSheet">
						取消
					</uv-button>
				</view>
			</view>
		</uv-popup>

		<uv-popup ref="popup" mode="center" :closeOnClickOverlay="false" :round="10">
			<view class="bind-phone-modal">
				<view class="modal-header">
					<view class="modal-title">换绑手机号</view>
					<view class="modal-subtitle">请输入换绑手机号信息</view>
				</view>

				<view class="modal-form">
					<uv-form :model="bindPhoneInfo" :rules="bindPhoneRules" ref="bindPhoneForm">
						<uv-form-item prop="phone">
							<uv-input v-model="bindPhoneInfo.phone" placeholder="请输入手机号" type="number" maxlength="11"
								border="surround"></uv-input>
						</uv-form-item>
						<uv-form-item prop="code">
							<uv-input v-model="bindPhoneInfo.code" placeholder="请输入验证码" border="surround">
								<template v-slot:suffix>
									<uv-code ref="bindCodeRef" @change="bindCodeChange" seconds="60"
										changeText="X秒重新获取"></uv-code>
									<text style="color: #4d82fd; font-size: 12px" @click="getBindCode">
										{{ bindCodeTips }}
									</text>
								</template>
							</uv-input>
						</uv-form-item>
					</uv-form>
				</view>

				<view class="modal-actions">
					<uv-button type="default" @click="closeBindPhoneModal" customStyle="margin-right: 12px;">
						取消
					</uv-button>
					<uv-button type="primary" @click="confirmBindPhone" :loading="bindingPhone">
						确认绑定
					</uv-button>
				</view>
			</view>
		</uv-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from "vue";
	import {
		onShow
	} from "@dcloudio/uni-app";
	import {
		useAuthStore,
		useUserStore
	} from "@/store";
	import RPC from "@/utils/request";

	const authStore = useAuthStore();
	const userStore = useUserStore();

	// 响应式数据
	const userInfo = ref({
		avatar: "/static/imgs/avatar.png",
		username: "张三",
		phone: "15825556676",
		email: "235382903@qq.com",
	});

	const cacheSize = ref("36MB");
	const logoutLoading = ref(false);
	const editType = ref("");
	const editValue = ref("");
	const editPopup = ref(null);
	const avatarSheet = ref(null);

	// 更换头像
	const changeAvatar = () => {
		console.log("点击更换头像");
		avatarSheet.value.open();
	};

	// 关闭头像选择弹窗
	const closeAvatarSheet = () => {
		avatarSheet.value.close();
	};

	// 选择头像来源
	const selectAvatarSource = (source) => {
		console.log("选择头像方式:", source);
		avatarSheet.value.close();

		uni.chooseImage({
			count: 1,
			sizeType: ["compressed"],
			sourceType: source === "camera" ? ["camera"] : ["album"],
			success: (res) => {
				const tempFilePath = res.tempFilePaths[0];
				console.log("选择图片成功:", tempFilePath);

				// 这里应该上传图片到服务器
				// uploadAvatar(tempFilePath)

				// 临时更新头像显示
				userInfo.value.avatar = tempFilePath;

				uni.showToast({
					title: "头像更新成功",
					icon: "success",
				});
			},
			fail: (err) => {
				console.error("选择图片失败:", err);
				uni.showToast({
					title: "选择图片失败",
					icon: "none",
				});
			},
		});
	};

	// 编辑用户名
	const editUsername = () => {
		editType.value = "username";
		editValue.value = userStore.userInfo.username;
		editPopup.value.open();
	};

	// 编辑电话
	const editPhone = () => {
		editType.value = "phone";
		editValue.value = userStore.userInfo.phone;
		editPopup.value.open();
	};

	// 编辑邮箱
	const editEmail = () => {
		editType.value = "email";
		editValue.value = userStore.userInfo.email;
		editPopup.value.open();
	};

	// 获取输入框占位符
	const getPlaceholder = () => {
		switch (editType.value) {
			case "username":
				return "请输入用户名";
			case "phone":
				return "请输入手机号";
			case "email":
				return "请输入邮箱地址";
			default:
				return "请输入";
		}
	};

	// 关闭编辑弹窗
	const closeEditModal = () => {
		editPopup.value.close();
		editType.value = "";
		editValue.value = "";
	};

	// 保存编辑
	const saveEdit = async () => {
		if (!editValue.value.trim()) {
			uni.showToast({
				title: "请输入内容",
				icon: "none",
			});
			return;
		}
		if (editType.value === 'username') {
			RPC.post('/user/update', {
				id: userStore.userInfo.id,
				username: editValue.value
			}).then(() => {
				uni.showToast({
					title: "保存成功",
					icon: "success",
				});
				userStore.setUserInfo({
					...userStore.userInfo,
					username: editValue.value
				})
				closeEditModal()
			})
		}
		if (editType.value === 'email') {
			RPC.post('/user/update', {
				id: userStore.userInfo.id,
				email: editValue.value
			}).then(() => {
				uni.showToast({
					title: "保存成功",
					icon: "success",
				});
				userStore.setUserInfo({
					...userStore.userInfo,
					email: editValue.value
				})
				closeEditModal()
			})
		}

		// try {
		//   // 调用更新用户信息API
		//   // await RPC.post('/api/user/update', {
		//   //   [editType.value]: editValue.value
		//   // })

		//   // 更新本地数据
		//   userInfo.value[editType.value] = editValue.value;

		//   uni.showToast({
		//     title: "保存成功",
		//     icon: "success",
		//   });

		//   closeEditModal();
		// } catch (error) {
		//   console.error("保存失败:", error);
		//   uni.showToast({
		//     title: "保存失败，请重试",
		//     icon: "none",
		//   });
		// }
	};

	// 清除缓存
	const clearCache = () => {
		uni.showModal({
			title: "清除缓存",
			content: "确定要清除应用缓存吗？",
			success: (res) => {
				if (res.confirm) {
					uni.showLoading({
						title: "清除中...",
					});

					// 模拟清除缓存
					setTimeout(() => {
						uni.hideLoading();
						cacheSize.value = "0MB";
						uni.showToast({
							title: "缓存清除成功",
							icon: "success",
						});
					}, 1500);
				}
			},
		});
	};

	// 查看用户协议
	const viewUserAgreement = () => {
		uni.navigateTo({
			url: "/pagesA/user-agreement/user-agreement",
		});
	};

	// 查看关于我们
	const viewAbout = () => {
		//   uni.navigateTo({
		//     url: "/pagesA/about/about",
		//   });
	};

	// 退出登录
	const logout = () => {
		uni.showModal({
			title: "退出登录",
			content: "确定要退出登录吗？",
			success: (res) => {
				if (res.confirm) {
					logoutLoading.value = true;

					// 模拟退出登录
					setTimeout(() => {
						authStore.signOut();
						logoutLoading.value = false;

						// 清除用户信息和token
						// authStore.logout()

						uni.showToast({
							title: "已退出登录",
							icon: "success",
						});

						// 跳转到登录页
						uni.reLaunch({
							url: "/pages/login/login",
						});
					}, 1000);
				}
			},
		});
	};

	// 加载用户信息
	const loadUserInfo = async () => {
		try {
			// 调用获取用户信息API
			// const result = await RPC.get('/api/user/info')
			// userInfo.value = result.data
		} catch (error) {
			console.error("加载用户信息失败:", error);
		}
	};

	// 计算缓存大小
	const calculateCacheSize = () => {
		// 实际项目中应该计算真实的缓存大小
		// const size = await getCacheSize()
		// cacheSize.value = formatSize(size)
	};

	onMounted(() => {
		loadUserInfo();
		calculateCacheSize();
	});

	onShow(() => {
		// 页面显示时刷新用户信息
		loadUserInfo();
	});

	const popup = ref(null);
	const bindingPhone = ref(false);
	const bindCodeTips = ref("获取验证码");
	const bindCodeRef = ref(null);
	const bindPhoneForm = ref(null);
	const bindPhoneInfo = ref({
		phone: "",
		code: "",
	});
	
	const changePhone = () => {
		bindPhoneInfo.value = {
			phone: "",
			code: "",
		}
		popup.value.open()
	}
	const bindPhoneRules = ref({
		phone: [{
				required: true,
				message: "请输入手机号",
				trigger: ["blur", "change"],
			},
			{
				pattern: /^1[3-9]\d{9}$/,
				message: "请输入正确的手机号",
				trigger: ["blur", "change"],
			},
		],
		code: {
			required: true,
			message: "请输入验证码",
			trigger: ["blur", "change"],
		},
	});
	
	const bindCodeChange = (text) => {
		bindCodeTips.value = text;
	};
	
	const closeBindPhoneModal = () => {
		popup.value.close();
		bindPhoneInfo.value = {
			phone: "",
			code: "",
		};
		bindCodeTips.value = "获取验证码";
	};
	
	const confirmBindPhone = async () => {
		try {
			await bindPhoneForm.value.validate();
	
			bindingPhone.value = true;
	
			// 调用绑定手机号API
			RPC.post('/user/bind_phone', {
				phone: bindPhoneInfo.value.phone,
				code: bindPhoneInfo.value.code,
				token: authStore.accessToken
			}).then((res) => {
				console.log('bind_phone', res)
				bindingPhone.value = false;
				uni.showToast({
					title: "换绑成功",
					icon: "success",
				});
				popup.value.close()
				RPC.post('/user/info', {
						token: authStore.accessToken,
					})
					.then((res) => {
						userStore.setUserInfo(res)
					})
			})
		} catch (error) {
			console.error("换绑手机号失败:", error);
			bindingPhone.value = false;
		}
	};
	
	const getBindCode = () => {
		if (!bindPhoneInfo.value.phone) {
			uni.showToast({
				title: "请输入手机号",
				icon: "none",
			});
			return;
		}
	
		if (!/^1[3-9]\d{9}$/.test(bindPhoneInfo.value.phone)) {
			uni.showToast({
				title: "请输入正确的手机号",
				icon: "none",
			});
			return;
		}
	
		if (bindCodeRef.value.canGetCode) {
			uni.showLoading({
				title: "正在获取验证码",
			});
			// 调用发送验证码API
			RPC.post('/user/bind_phone/send_code', {
				phone: bindPhoneInfo.value.phone,
				token: authStore.accessToken
			}).then(() => {
				uni.hideLoading()
				uni.showToast({
					title: '验证码已发送',
					icon: 'success'
				})
				bindCodeRef.value.start()
			}).catch(() => {
				uni.hideLoading()
				uni.showToast({
					title: '发送失败，请重试',
					icon: 'none'
				})
			})
		} else {
			uni.showToast({
				title: "倒计时结束后再发送",
				icon: "none",
			});
		}
	};
</script>

<style lang="scss" scoped>
	.container {
		font-size: 14px;
		min-height: 100vh;
		background-color: #f8f8f8;
		padding: 16px;
	}

	.profile-section,
	.app-section {
		background: white;
		border-radius: 12px;
		margin-bottom: 16px;
		overflow: hidden;

		.profile-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 16px;
			border-bottom: 1px solid #f0f0f0;

			&:last-child {
				border-bottom: none;
			}

			.item-label {
				font-size: 16px;
				color: #333;
				font-weight: 500;
			}

			.item-content {
				display: flex;
				align-items: center;
				gap: 8px;

				.avatar {
					width: 40px;
					height: 40px;
					border-radius: 50%;
				}

				.item-value {
					font-size: 14px;
					color: #666;
				}
			}
		}
	}

	.logout-section {
		margin-top: 32px;
	}

	.edit-modal {
		width: 300px;
		padding: 24px;

		.modal-title {
			font-size: 18px;
			font-weight: bold;
			color: #333;
			text-align: center;
			margin-bottom: 20px;
		}

		.modal-actions {
			display: flex;
			gap: 12px;
			margin-top: 20px;

			.uv-button {
				flex: 1;
			}
		}
	}

	.avatar-sheet {
		padding: 20px;

		.sheet-header {
			text-align: center;
			margin-bottom: 20px;

			.sheet-title {
				font-size: 18px;
				font-weight: bold;
				color: #333;
			}
		}

		.sheet-actions {
			display: flex;
			justify-content: space-around;
			margin-bottom: 20px;

			.action-item {
				display: flex;
				flex-direction: column;
				align-items: center;
				gap: 8px;
				padding: 20px;
				border-radius: 8px;
				background: #f8f9fa;
				min-width: 100px;
				transition: all 0.3s;

				&:active {
					background: #e9ecef;
					transform: scale(0.95);
				}

				.action-text {
					font-size: 14px;
					color: #333;
				}
			}
		}

		.sheet-cancel {
			margin-top: 10px;
		}
	}
	.bind-phone-modal {
		width: 320px;
		padding: 24px;
	
		.modal-header {
			text-align: center;
			margin-bottom: 24px;
	
			.modal-title {
				font-size: 18px;
				font-weight: bold;
				color: #333;
				margin-bottom: 8px;
			}
	
			.modal-subtitle {
				font-size: 14px;
				color: #666;
			}
		}
	
		.modal-form {
			margin-bottom: 24px;
	
			.uv-form-item {
				margin-bottom: 16px;
			}
		}
	
		.modal-actions {
			display: flex;
			gap: 12px;
	
			.uv-button {
				flex: 1;
			}
		}
	}
</style>