<script>
	import authUtil from '@/utils/auth.js'; // 引入工具类
	import userUtil from '@/utils/user.js'; // 引入工具类
	export default {
		globalData: {
			website: "https://www.lailab.cc:8080",
			hasUserInfo: false,
			userInfo: {},
			openId: null,
			defaultAuthCode: "D768ECAAB35C55ABBA071C5415D6520E",
			method: {
				getOpenId: "/api/wx/getOpenId",
				getUserByOpenId: "/api/user/getUserByOpenId",
				addUser: "/api/user/addUser",
				getConfigAll: "/api/pic/getPicAll",
				getAuthMd5Code: "/api/auth/getAuthMd5Code"
			},
			homePageData:{
				tip: {
					msg:"世上无难事，只要肯攀登。",
					isShow:true,
					level:2
				},
				swiper: {
					background: [
						{
							type:"color",
							background: "#0226",
							text:"广告位1",
							clickable:true,
							action:"dialog",
							content:"你点击了广告位1",
							
						}, 
						{
							type:"image",
							background: "",
							mode:"scale",
							text:"广告位2",
							clickable:true,
							action:"goto",
							content:"/pages/utils/showImg/showImg"
							
						},
						{
							type:"color",
							background: "#A70",
							text:"广告位3",
							clickable:true,
							action:"dialog",
							content:"你点击了广告位3"
							
						}
					],
					indicatorDots: true,
					autoplay: true,
					interval: 2000,
					duration: 500,
					vertical: false,
					circular: true
				},
				pics: [
					{
						url:"https://img1.baidu.com/it/u=2172818577,3783888802&fm=253&app=138&f=JPEG?w=800&h=1422",
						source:"LaiLab",
						id:"1"
					},
					{
						url:"https://hellorfimg.zcool.cn/provider_image/large/hi2241910533.jpg?x-image-process=image/format,webp",
						source:"百度",
						id:"2"
					},
					{
						url:"https://c-ssl.dtstatic.com/uploads/blog/202403/13/0GSvde87c0G05zE.thumb.1000_0.jpg",
						source:"百度",
						id:"3"
					},
					{
						url:"https://img0.baidu.com/it/u=3815152378,1770089461&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=1082",
						source:"百度",
						id:"4"
					},
					{
						url:"https://img1.baidu.com/it/u=1046630760,1711311937&fm=253&app=138&f=JPEG?w=800&h=1428",
						source:"百度",
						id:"5"
					},
					{
						url:"https://c-ssl.dtstatic.com/uploads/blog/202312/04/0GSvVw6Xt0exN0g.thumb.1000_0.jpg",
						source:"百度",
						id:"6"
					},
					{
						url:"https://img0.baidu.com/it/u=41840629,336950107&fm=253&app=138&f=JPEG?w=500&h=1109",
						source:"百度",
						id:"7"
					},
					{
						url:"https://hellorfimg.zcool.cn/provider_image/large/hi2241910533.jpg?x-image-process=image/format,webp",
						source:"百度",
						id:"8"
					}
				]
			},
			morePageData:{
				tools: [
					{
						name:"Hello",
						cards:[
							{
								title:"测试",
								detail:"村上春树",
								color:"#aaa",
								icon:"../../static/icons/icon_qrcode.png",
								url:""
								
							}
							
						]
					},
				],
			}
			
		},
		
		onLaunch: function() {
			console.log("=== LaiLab小程序主页 ===");
			this.login();
		},
		methods: {
			async login() {
				const that = this;
				const gData = this.globalData;
				
				if (gData.hasUserInfo) {
					console.log("已获取用户信息，跳过登录流程");
					return;
				}
				
				console.log("未获取用户信息，开始获取");
				
				try {
					// 步骤1: 获取微信code
					const step1Result = await this.getWechatCode();
					
					// 步骤2: 获取用户信息
					const step2Result = await this.getUserInfo();
					
					// 步骤3: 获取OpenId
					console.log(`3.调用方法 ${gData.method.getOpenId} 开始 入参: ${step1Result.code}`);
					const openId = await userUtil.getOpenId(step1Result.code);
					console.log(`3.调用方法 ${gData.method.getOpenId} 结束 返回: ${openId}`);
					gData.openId = openId;
					
					// 获取授权码	
					var requestData_getAuth = {
						openId: gData.openId
					};
					console.log(`4.1 调用方法 ${gData.method.getAuthMd5Code} 开始 入参: ${JSON.stringify(requestData_getAuth)}`);
					var authCode = await authUtil.getAuthMd5Code(requestData_getAuth)
					console.log(`4.1 调用方法 ${gData.method.getAuthMd5Code} 结束 返回: ${authCode}`);
					// 若用户未注册，则以下步骤将都无法进行，所以填充默认授权码
					if(authCode===''||authCode===null){
						authCode = gData.defaultAuthCode;
					}
					
					// 步骤4: 检查用户注册状态	
					var requestData_checkUser = {
						openId: gData.openId,
						authCode: authCode
					};
					console.log(`4.2 调用方法 ${gData.method.getUserByOpenId} 开始 入参: ${JSON.stringify(requestData_checkUser)}`);
					const userData = await userUtil.checkUserStatus(requestData_checkUser);
					console.log(`4.2 调用根据 ${gData.method.getUserByOpenId} 结束 返回: ${isexist}`);
					const isexist = userData.data.code;
					switch (isexist) {
						case -1:
							console.log("用户未注册");
							this.handleUserNotRegistered();
							break;
					
						case -2:
							console.error(`报错: ${userData.data.message}`);
							this.toast(userData.data.message || "查询用户信息失败", 'error');
							break;
					
						case 0:
							console.log(`用户已注册,自动登录！用户信息: ${JSON.stringify(userData.data.data)}`);
					
							gData.userInfo = userData.data.data;
							gData.hasUserInfo = true;
							this.toast("自动登录成功", 'success');
							break;
					
						default:
							console.warn(`4.未知状态码: ${isexist}`);
							break;
					}
					
				} catch (error) {
					console.error("登录流程失败:", error);
					this.toast("登录失败，请重试", 'error');
				}
			},
			
			// 步骤1: 获取微信code
			getWechatCode() {
				return new Promise((resolve, reject) => {
					console.log("1.调用登录接口wx.login()开始");
					
					uni.login({
						success: function(res) {
							console.log(`1.调用登录接口wx.login()结束 返回: ${JSON.stringify(res)}`);
							console.log(`1.返回参数: code=${res.code}`);
							resolve(res);
						},
						fail: function(res) {
							console.error(`1.调用微信接口wx.login()失败 返回: ${JSON.stringify(res)}`);
							reject(new Error("微信登录失败"));
						}
					});
				});
			},
			
			// 步骤2: 获取用户信息
			getUserInfo() {
				return new Promise((resolve, reject) => {
					console.log("2.调用用户信息接口wx.getUserInfo()开始");
					
					uni.getUserInfo({
						success: (res) => {
							console.log("2.调用用户信息接口wx.getUserInfo()结束 返回:", res);
							console.log("2.返回参数: userInfo=", res.userInfo);
							resolve(res);
						},
						fail: (res) => {
							console.error(`2.调用微信接口wx.getUserInfo()失败 返回: ${JSON.stringify(res)}`);
							this.authorizeCheck("scope.userInfo");
							reject(new Error("获取用户信息失败"));
						}
					});
				});
			},
			
			// 处理用户未注册情况
			handleUserNotRegistered() {
				const that = this;
				
				uni.showModal({
					title: '提示',
					content: '检测到您尚未登录，某些工具可能无权使用，请先去登录。',
					confirmText: '去登陆',
					cancelText: '取消',
					success(res) {
						if (res.confirm) {
							console.log("用户选择去登录");
							that.userLogin();
						} else {
							console.log("用户点击取消");
							
						}
					}
				});
			},
			
			// 用户登录（手动）
			async userLogin() {
				const that = this;
				const gData = this.globalData;
				
				// 若用户未登录
				if (!gData.hasUserInfo) {
					this.toast("正在登录", 'loading');
					
					try {
						// 获取详细用户信息
						const profile = await this.getUserProfileWithDesc();
						
						gData.hasUserInfo = true;
						gData.userInfo = profile.userInfo;
						
						this.toast("登录成功", 'success');
						
						// 注册用户
						if (gData.openId) {
							console.log(`4.3 调用 ${gData.method.addUser} 开始 入参: ${profile.userInfo}`);
							const result = await userUtil.registerUser(profile.userInfo);
							console.log(`4.3 调用 ${gData.method.addUser} 结束 返回: ${result}`);
							
						} else {
							console.warn("没有OpenId，无法注册用户");
							this.toast("登录异常，请重新进入小程序", 'error');
							return;
						}
						
						// 跳转到个人中心
						uni.switchTab({
							url: '/pages/mine/mine'
						});
						
					} catch (error) {
						console.error("用户登录失败:", error);
						this.toast(error.message || "登录失败", 'error');
					}
				} else {
					this.toast("您已经登录", 'none');
				}
			},
			
			// 获取用户详细信息（带描述）
			getUserProfileWithDesc() {
				return new Promise((resolve, reject) => {
					uni.getUserProfile({
						desc: "获取你的昵称、头像、地区及性别",
						success: resolve,
						fail: (res) => {
							reject(new Error("您拒绝了授权请求"));
						}
					});
				});
			},
			
			
			// 授权检查
			authorizeCheck(scope) {
				console.log(`检查授权: ${scope}`);
				
				uni.authorize({
					scope: scope,
					success: () => {
						console.log(`${scope} 授权成功`);
					},
					fail: () => {
						console.log(`${scope} 授权失败`);
						this.toast("需要授权才能使用完整功能", 'none');
					}
				});
			},
			
			// Toast提示
			toast(title, icon = 'none', duration = 2000) {
				uni.showToast({
					title: title,
					icon: icon,
					duration: duration
				});
			},
			
			// 分享相关方法（保留原有逻辑）
			getRandomShareTitle: function() {
				var arr = [];
				
				if (this.globalData.shareapptext) {
					arr = this.globalData.shareapptext;
				}
				
				return arr[Math.floor(Math.random() * arr.length)];
			},
			
			getMainAppShare: function() {
				return {
					title: this.getRandomShareTitle(),
					path: '/pages/index/index',
					success: function(res) {
						console.log("分享成功");
					},
					fail: function(res) {
						console.log("分享失败");
					}
				}
			}
		}
	}
</script>

<style>
	/* 每个页面公共css */
	uni-page-body,
	html,
	body {
		height: 100%;
	}
</style>