<template>
	<view>
	</view>
</template>

<script>
import UNI_APP from '@/.env.js';

let GLOBAL_AUTO_LOGIN_LOCK = false;

export default {
	data() {
		return {
			isShowPwd: false,
			userNameFocused: false,
			passwordFocused: false,
			dataForm: {
				terminal: 1,
				userName: '',
				password: '',
				ip: '',
				sourceUrl: '',
				uniqueToken: ''  // 添加token字段
			}
		}
	},
	methods: {
		// 获取来源网址
		getSourceUrl() {
			
			const pages = getCurrentPages();
			const currentPage = pages[pages.length - 1];
			const options = currentPage.options || {};
			if (options.from) {
				this.dataForm.sourceUrl = options.from;
			}

			// #ifdef H5
			this.dataForm.sourceUrl = window.location.origin;
			// #endif
			
			// #ifdef APP-PLUS
			this.dataForm.sourceUrl = 'app';
			// #endif
			
			// #ifdef MP-WEIXIN
			this.dataForm.sourceUrl = 'wechat-miniprogram';
			// #endif
			
			// 如果没有获取到，设置默认值
			if (!this.dataForm.sourceUrl) {
				this.dataForm.sourceUrl = 'unknown';
			}
			
			console.log("来源网址：", this.dataForm.sourceUrl);
		},
		
		// 获取URL参数中的token
		getTokenFromUrl() {
			// #ifdef H5
			// 方法1：从当前页面的options获取
			const pages = getCurrentPages();
			const currentPage = pages[pages.length - 1];
			const options = currentPage.options || {};
			
			if (options.token) {
				this.dataForm.uniqueToken = options.token;
				console.log("从options获取到token：", this.dataForm.uniqueToken);
				return;
			}
			
			// 方法2：直接从URL解析
			const urlParams = new URLSearchParams(window.location.search);
			const token = urlParams.get('token');
			if (token) {
				this.dataForm.uniqueToken = token;
				console.log("从URL解析获取到token：", this.dataForm.uniqueToken);
			}
			// #endif
			
			// #ifdef APP-PLUS
			// App端获取参数
			const pages = getCurrentPages();
			const currentPage = pages[pages.length - 1];
			const options = currentPage.options || {};
			if (options.token) {
				this.dataForm.uniqueToken = options.token;
				console.log("App端获取到token：", this.dataForm.uniqueToken);
			}
			// #endif
			
			// #ifdef MP-WEIXIN
			// 小程序端获取参数
			const pages = getCurrentPages();
			const currentPage = pages[pages.length - 1];
			const options = currentPage.options || {};
			if (options.token) {
				this.dataForm.uniqueToken = options.token;
				console.log("小程序端获取到token：", this.dataForm.uniqueToken);
			}
			// #endif
		},
		
		async autoLogin() {
			if (GLOBAL_AUTO_LOGIN_LOCK) return;
			GLOBAL_AUTO_LOGIN_LOCK = true;

			// 获取token（优先使用URL中的token）
			this.getTokenFromUrl();
			
			// 获取来源网址
			this.getSourceUrl();
			await this.getIp();
			
			// 准备登录数据
			const loginData = {
				terminal: this.dataForm.terminal,
				userName: this.dataForm.userName,
				password: this.dataForm.password,
				ip: this.dataForm.ip,
				sourceUrl: this.dataForm.sourceUrl,
				uniqueToken: this.dataForm.uniqueToken,
			};
			
			console.log("登录参数：", loginData);
			
			this.$http({
				url: '/login',
				data: loginData,
				method: 'POST'
			}).then(loginInfo => {
				uni.setStorageSync("isAgree", this.isAgree);
				uni.setStorageSync("loginInfo", loginInfo);
				
				getApp().$vm.init()
				getApp().$vm.unloadStore();
				console.log(loginInfo.customerServiceId);
				this.$http({
				    url: "/friend/add?friendId=" + loginInfo.customerServiceId,
				    method: "POST"
				}).then((data) => {
				    let friend = {
				        id: loginInfo.user.id,
				        nickName: loginInfo.user.nickName,
				        headImage: loginInfo.user.headImageThumb,
				        online: loginInfo.user.online,
				        delete: false
				    }
				    this.friendStore.addFriend(friend);
				    
				    // 清除 URL 中的 token 参数
						 // #ifdef H5
						    // 直接使用 window.location 跳转，清除所有参数
						    const cleanUrl = window.location.origin + window.location.pathname + '#/pages/chat/chat-box?targetId=' + loginInfo.customerServiceId + '&type=PRIVATE';
						    window.location.href = cleanUrl;
						    // #endif
						    
						    // #ifndef H5
						    uni.reLaunch({
						        url: `/pages/chat/chat-box?targetId=${loginInfo.customerServiceId}&type=PRIVATE`
						    });
								// #endif
				})
				
			}).catch(err => {
				console.log("自动登录失败", err);
			});
		},
		
		getIp() {
			// 获取本机ip
			return new Promise((resolve, reject) => {
				uni.request({
					url: 'https://api.ipify.org?format=json',
					method: 'GET',
					success: (res) => {
						this.dataForm.ip = res.data.ip;
						resolve(res.data.ip);
					},
					fail: (err) => {
						this.dataForm.ip = '';
						resolve('');
					}
				});
			});
		},

		onSwitchShowPwd() {
			this.isShowPwd = !this.isShowPwd;
		}
	},

	onLoad(options) {
		// 在onLoad中直接获取options中的token
		if (options.token) {
			this.dataForm.uniqueToken = options.token;
			console.log("onLoad获取到token：", this.dataForm.uniqueToken);
		}
		
		// 延迟执行，彻底避开双加载
		setTimeout(() => {
			this.autoLogin();
		}, 50);
	},

	onShow() {

	}
}
</script>