<template>
	<view class="mine-container">
		<!-- 用户信息卡片 -->
		<view class="user-card" @tap="handleUserCardClick">
			<view class="user-avatar-container">
				<view class="avatar-background"></view>
				<image 
					class="user-avatar" 
					:src="hasUserInfo ? userInfo.avatarUrl : '/static/icons/icon_default_avatar.png'" 
					mode="aspectFill"
				></image>
			</view>
			<view class="user-info-container">
				<text class="user-name">
					{{ hasUserInfo ? userInfo.nickName : "点击登录" }}
				</text>
				<text class="user-status" :class="{ 'status-logged': hasUserInfo }">
					{{ hasUserInfo ? "已登录" : "未登录" }}
				</text>
			</view>
		</view>

		<!-- 功能列表 -->
		<view class="function-list">
			<!-- 联系作者 -->
			<button class="function-item" open-type="contact" hover-class="item-hover">
				<view class="item-left">
					<image class="item-icon" src="/static/icons/icon_author_message.png" mode="widthFix"></image>
					<text class="item-text">联系作者</text>
				</view>
				<text class="iconfont icon-arrow-right item-arrow"></text>
			</button>

			<!-- 反馈问题 -->
			<button class="function-item" @tap="handleFeedback" hover-class="item-hover">
				<view class="item-left">
					<image class="item-icon" src="/static/icons/icon_feedback.png" mode="widthFix"></image>
					<text class="item-text">反馈问题</text>
				</view>
				<text class="iconfont icon-arrow-right item-arrow"></text>
			</button>

			<!-- 清理缓存 -->
			<button class="function-item" @tap="handleClearStorage" hover-class="item-hover">
				<view class="item-left">
					<image class="item-icon" src="/static/icons/icon_clear_catch.png" mode="widthFix"></image>
					<text class="item-text">清理缓存</text>
				</view>
				<text class="iconfont icon-arrow-right item-arrow"></text>
			</button>

			<!-- 开发日志 -->
			<button class="function-item" @tap="handleDevLog" hover-class="item-hover">
				<view class="item-left">
					<image class="item-icon" src="/static/icons/icon_dev_log.png" mode="widthFix"></image>
					<text class="item-text">开发日志</text>
				</view>
				<text class="iconfont icon-arrow-right item-arrow"></text>
			</button>

			<!-- 分享好友 -->
			<button class="function-item" open-type="share" hover-class="item-hover">
				<view class="item-left">
					<image class="item-icon" src="/static/icons/icon_share.png" mode="widthFix"></image>
					<text class="item-text">分享好友</text>
				</view>
				<text class="iconfont icon-arrow-right item-arrow"></text>
			</button>
			
			<!-- 捐赠作者 -->
			<button class="function-item"  @tap="handleAdmire" hover-class="item-hover">
				<view class="item-left">
					<image class="item-icon" src="/static/icons/icon_love.png" mode="widthFix"></image>
					<text class="item-text">捐赠作者</text>
				</view>
				<text class="iconfont icon-arrow-right item-arrow"></text>
			</button>

			<!-- 功能设置 -->
			<button class="function-item" open-type="openSetting" hover-class="item-hover">
				<view class="item-left">
					<image class="item-icon" src="/static/icons/icon_setting.png" mode="widthFix"></image>
					<text class="item-text">功能设置</text>
				</view>
				<text class="iconfont icon-arrow-right item-arrow"></text>
			</button>

			<!-- 退出登录 -->
			<button 
				v-if="hasUserInfo" 
				class="function-item logout-item" 
				@tap="handleLogout" 
				hover-class="item-hover"
			>
				<text class="logout-text">退出登录</text>
			</button>
		</view>
	</view>
</template>

<script>
	const app = getApp();
	import authUtil from '@/utils/auth.js'; // 引入工具类
	
	// 配置常量
	const CONFIG = {
		CONTACT: {
			EMAIL: "lailab_mail@126.com",
			QQ: "1694319867"
		},
		VERSION_LOG: `
			<b>v2.2.5 2022-11-3</b><br />
				1.优化部分代码<br />
				2.去掉微信未开放功能<br />
			<b>v2.2.4 2022-10-28</b><br />
				1.更新部分代码<br />
			<b>v2.2.3 2022-10-26</b><br />
				1.实现根据人数自动开奖的功能<br />
			<b>v2.2.2 2022-10-25</b><br />
				1.实现抽奖页面创建加入界面<br />
				2.实现抽奖页面创建后台逻辑<br />
			<b>v2.2.1 2022-10-24</b><br />
				1.完善抽奖助手子页面<br />
			<b>v2.2 2022-10-23</b><br />
				1.添加抽奖助手界面<br />
			<b>v2.1 2022-10-22</b><br />
				1.添加自动登录逻辑<br />
				2.各个界面微调美化<br />
			<b>v2.0 2022-10-19</b><br />
				1.更新主页空内容显示<br />
				2.实现工具智能抠图、证件照、摩斯电码、随机骰子等功能<br />
				3.实现部分登录逻辑<br />
			<b>v1.0 2022-10-7</b><br />
				1.从微信端进行移植<br />
		`
	};
	
	export default {
		data() {
			return {
				hasUserInfo: false,
				userInfo: {},
				openid: ""
			}
		},
		
		onLoad() {
			console.log("----------------------------- 加载我的页面 -----------------------------");
			this.initPageData();
		},
		
		onShow() {
			console.log("----------------------------- 显示我的页面 -----------------------------");
			this.updateUserInfo();
		},
		
		methods: {
			// 初始化页面数据
			initPageData() {
				this.updateUserInfo();
				this.getStorageSize();
			},
			
			// 更新用户信息
			updateUserInfo() {
				if (app.globalData.hasUserInfo) {
					this.hasUserInfo = true;
					this.userInfo = app.globalData.userInfo;
					console.log("用户信息已更新:", this.userInfo);
				} else {
					console.log("用户未登录");
				}
			},
			
			// 处理用户卡片点击
			async handleUserCardClick() {
				console.log("1.开始检测是否存在用户信息");
				if (!this.hasUserInfo) {
					console.log("2.未查询到用户信息,触发登录流程");
					await this.handleLogin();
				} else {
					console.log("2.查询到信息，提示用户已登录");
					this.toast("您已经登录", 'none');
				}
			},
			
			// 处理登录
			async handleLogin() {
				try {
					this.toast("正在登录", 'loading');
					console.log("3.1 调用wx.getUserProfile()获取信息开始");
					
					const profile = await this.getUserProfile();
					console.log("3.1 用wx.getUserProfile()获取信息结束 返回:", profile.userInfo);
					
					// 更新全局和本地数据
					app.globalData.hasUserInfo = true;
					app.globalData.userInfo = profile.userInfo;
					this.hasUserInfo = true;
					this.userInfo = profile.userInfo;
					console.log("3.2 填充用户信息到界面");
					
					// 注册用户到后端
					console.log("3.3 判断是否存在用户OopnId");
					if (app.globalData.openId) {
						console.log("3.3 获取到OopnId,开始注册");
						await this.registerUser(profile.userInfo);
					} else {
						console.warn("3.3 没有OpenId,重新进入小程序获取");
						this.toast("登录异常，请重新进入小程序", 'error');
						return;
					}
					
					this.toast("登录成功", 'success');
					console.log("登录流程完成");
					
				} catch (error) {
					console.error("登录失败:", error);
					this.toast(error.message, 'error');
				}
			},
			
			// 获取用户信息（Promise封装）
			getUserProfile() {
				return new Promise((resolve, reject) => {
					uni.getUserProfile({
						desc: "获取你的昵称、头像、地区及性别",
						success: resolve,
						fail: () => {
							reject(new Error("您拒绝了授权"));
						}
					});
				});
			},
			
			// 注册用户到后端
			async registerUser(userInfo) {
				try {
					const registerData = {
						...userInfo,
						openId: app.globalData.openId,
						//authCode:authCode,
						// username:"admin",
						// password:"1234",
						// phone:"1234567",
						// email:"1234567",
						creator:"admin",
						source:0,
						status:0
					};
					const result = await this.requestRegister(registerData);
					
					
				} catch (error) {
					console.error("3.4 用户注册失败 返回:", error);
					throw error;
				}
			},
			
			// 请求注册（Promise封装）
			requestRegister(userInfo) {
				console.log("3.4.2 调用:"+app.globalData.website +app.globalData.method.addUser+"()添加用户开始 入参:", userInfo);
				return new Promise((resolve, reject) => {
					uni.request({
						url: app.globalData.website + app.globalData.method.addUser,
						method: 'POST',
						data: userInfo,
						success: (res) => {
							if (res.data.code == 0) {
									console.log("3.4.2 调用:"+app.globalData.method.addUser+"()添加用户结束 返回:", res);
									resolve(res.data);
									this.showRegisterSuccess(res.data.msg);
							}else{
									console.log("3.4.2 调用:"+app.globalData.method.addUser+"()添加用户失败 返回:", res);
									reject(new Error(res.data.msg || "注册失败"));
							}

						},
						fail: (res) => {
							console.error("3.4.2 调用:"+app.globalData.addUser+"()添加用户失败 返回:", res);
							reject(new Error("网络请求失败"));
						}
					});
				});
			},
			
			// 显示注册成功提示
			showRegisterSuccess(message) {
				uni.showModal({
					title: "提示",
					content: message || "注册成功",
					showCancel: false,
					confirmText: "知道了"
				});
			},
			
			// 处理退出登录
			async handleLogout() {
				console.log("用户点击退出登录");
				
				const result = await this.confirmLogout();
				
				if (result) {
					this.performLogout();
				} else {
					this.toast("取消操作", 'none');
				}
			},
			
			// 确认退出登录
			confirmLogout() {
				return new Promise((resolve) => {
					uni.showModal({
						title: "提示",
						content: "是否确定退出登录？",
						confirmText: "确定",
						cancelText: "取消",
						success: (res) => {
							resolve(res.confirm);
						}
					});
				});
			},
			
			// 执行退出登录
			performLogout() {
				// 清除全局数据
				app.globalData.hasUserInfo = false;
				app.globalData.userInfo = {};
				
				// 清除本地数据
				this.hasUserInfo = false;
				this.userInfo = {};
				
				console.log("用户已退出登录");
				this.toast("已退出登录", 'success');
			},
			
			// 处理反馈
			async handleFeedback() {
				console.log("用户点击反馈问题");
				
				const result = await this.showFeedbackDialog();
				
				if (result === 'email') {
					await this.copyToClipboard(CONFIG.CONTACT.EMAIL, "邮箱");
				} else if (result === 'qq') {
					await this.copyToClipboard(CONFIG.CONTACT.QQ, "QQ号");
				}
			},
			
			// 显示反馈对话框
			showFeedbackDialog() {
				return new Promise((resolve) => {
					uni.showModal({
						title: "反馈方式",
						content: `有问题可以通过以下方式联系作者：
1. 邮箱：${CONFIG.CONTACT.EMAIL}
2. QQ：${CONFIG.CONTACT.QQ}

请选择一种方式复制联系方式`,
						confirmText: "复制邮箱",
						cancelText: "复制QQ",
						success: (res) => {
							if (res.confirm) {
								resolve('email');
							} else if (res.cancel) {
								resolve('qq');
							}
						}
					});
				});
			},
			
			// 复制到剪贴板
			async copyToClipboard(text, type) {
				try {
					await this.setClipboardData(text);
					await this.verifyClipboardData();
					
					this.toast(`${type}复制成功`, 'success');
					console.log(`${type}复制成功:`, text);
					
				} catch (error) {
					console.error("复制失败:", error);
					this.toast("复制失败", 'error');
				}
			},
			
			// 设置剪贴板数据
			setClipboardData(text) {
				return new Promise((resolve, reject) => {
					uni.setClipboardData({
						data: text,
						success: resolve,
						fail: reject
					});
				});
			},
			
			// 验证剪贴板数据
			verifyClipboardData() {
				return new Promise((resolve, reject) => {
					uni.getClipboardData({
						success: resolve,
						fail: reject
					});
				});
			},
			// 获取本地缓存大小
			getStorageSize() {
				let that = this;
				try {
					plus.cache.calculate(function(size) {
						let sizeCache = parseInt(size);
						if (sizeCache == 0) {
							that.currentSize = "0B";
						} else if (sizeCache < 1024) {
							that.currentSize = sizeCache + "B";
						} else if (sizeCache < 1048576) {
							that.currentSize = (sizeCache / 1024).toFixed(2) + "KB";
						} else if (sizeCache < 1073741824) {
							that.currentSize = (sizeCache / 1048576).toFixed(2) + "MB";
						} else {
							that.currentSize = (sizeCache / 1073741824).toFixed(2) + "GB";
						}
					});
				} catch (e) {
					return;
				}
			},
			// 清理缓存
			// 处理清理缓存
			async handleClearStorage() {
				let that = this;
				that.toast("正在清理", "loading");
				try {
					let os = plus.os.name;
				
					if (os == 'Android') {
						let main = plus.android.runtimeMainActivity();
						let sdRoot = main.getCacheDir();
						let files = plus.android.invoke(sdRoot, "listFiles");
						let len = files.length;
						console.log(files, len)
						for (let i = 0; i < len; i++) {
							let filePath = '' + files[i]; // 没有找到合适的方法获取路径，这样写可以转成文件路径  
							plus.io.resolveLocalFileSystemURL(filePath, function(entry) {
								if (entry.isDirectory) {
									entry.removeRecursively(function(entry) { //递归删除其下的所有文件及子目录
										that.files = []
										that.toast("清除成功", "success");
										that.getStorageSize(); // 重新计算缓存  
									}, function(e) {
										console.log(e.message)
									});
								} else {
									entry.remove();
								}
							}, function(e) {
								console.log('文件路径读取失败')
							});
						}
					} else { // ios  
						plus.cache.clear(function() {
							that.toast("清除成功", "success");
							that.getStorageSize();
						});
					}
				} catch {
					that.toast("清理完成", "success");
					return;
				}
			},
			// 处理开发日志
			handleDevLog() {
				console.log("用户查看开发日志");
				// encodeURIComponent(CONFIG.VERSION_LOG)
				uni.navigateTo({
					url: `/pages/utils/showText/showText?nodes=${CONFIG.VERSION_LOG}&title=开发日志`
				});
			},
			
			// 捐赠作者（暂时注释）
			handleAdmire() {
				// const url = app.globalData.website + "/image/other/image_admire.jpg";
				// uni.navigateTo({
				// 	url: `/pages/utils/showImg/showImg?id=0&url=${url}&showBar=false&showMode=aspectFit&canLongTap=true`
				// });
				uni.navigateTo({
					url: `/pages/test/test`
				});
			},
			
			// Toast提示
			toast(title, icon = 'none', duration = 2000) {
				uni.showToast({
					title: title,
					icon: icon,
					duration: duration
				});
			},
			
			// 分享配置
			onShareAppMessage() {
				return {
					title: 'LaiLab工具箱 - 我的工具库',
					path: '/pages/mine/mine',
					imageUrl: '/static/share.png'
				};
			}
		}
	}
</script>

<style lang="scss">
	@import url("../../static/iconfont/iconfont.css");
	
	.mine-container {
		min-height: 100vh;
		background: white;//linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
		padding: 20rpx 0;
	}
	
	/* 用户卡片样式 */
	.user-card {
		display: flex;
		align-items: center;
		background: #f6f7f9;//white;
		border-radius: 50rpx;
		padding: 40rpx 32rpx;
		margin: 32rpx 32rpx;
		//box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
		transition: all 0.3s ease;
		position: relative;
		
		&:active {
			background: #f8f9fa;
			transform: translateY(-2rpx);
		}
	}
	
	.user-avatar-container {
		position: relative;
		width: 140rpx;
		height: 140rpx;
		padding: 20rpx;
		background: #eee;
		border-radius: 28rpx;
		flex-shrink: 0;
	}
	
	.avatar-background {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 140rpx;
		height: 140rpx;
		background: white;
		//background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		//box-shadow: #07c160 solid;
		border-radius: 28rpx;
		opacity: 0.1;
	}
	
	.user-avatar {
		width: 140rpx;
		height: 140rpx;
		border-radius: 24rpx;
		background: white;
		//border: 4rpx solid white;
		//box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
	}
	
	.user-info-container {
		flex: 1;
		margin-left: 32rpx;
	}
	
	.user-name {
		display: block;
		font-size: 55rpx;
		font-weight: 600;
		color: #333;
	}
	
	.user-status {
		font-size: 24rpx;
		color: #999;
		
		&.status-logged {
			color: #07c160;
		}
	}
	
	.arrow-icon {
		font-size: 28rpx;
		color: #ccc;
	}
	
	/* 功能列表样式 */
	.function-list {
		background: #f6f7f9;//white;
		border-radius: 50rpx;
		margin: 0 32rpx;
		overflow: hidden;
		//box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
	}
	
	.function-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 32rpx 40rpx;
		background: transparent;
		border-bottom: 1rpx solid #f0f0f0;
		position: relative;
		text-align: left;
		line-height: normal;
		
		&:after {
			border: none;
		}
		
		&:last-child {
			border-bottom: none;
		}
		
		&.item-hover {
			background: #f8f9fa;
		}
	}
	
	.item-left {
		display: flex;
		align-items: center;
		flex: 1;
	}
	
	.item-icon {
		width: 60rpx;
		height: 60rpx;
		margin-right: 24rpx;
	}
	
	.item-text {
		font-size: 34rpx;
		color: #000;
		margin-left: 10rpx;
		flex: 1;
	}
	
	.item-arrow {
		font-size: 32rpx;
		color: #888;
		margin-right: 30rpx;
	}
	
	.item-extra {
		font-size: 28rpx;
		color: #999;
	}
	
	/* 退出登录样式 */
	.logout-item {
		margin-top: 32rpx;
		//background: #fff5f5;
		border-radius: 24rpx;
		justify-content: center;
		
		&:active {
			background: #ffeaea;
		}
	}
	
	.logout-text {
		color: #ff6b6b;
		font-size: 32rpx;
		font-weight: 600;
	}
	
	
	/* 分割线 */
	.function-item + .logout-item {
		margin-top: 0;
		border-top: 1rpx solid #f0f0f0;
	}
</style>