<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: '',
				customerid: ''
			}
		}
	},
	methods: {
		// 获取来源网址
		getSourceUrl() {
			// #ifdef H5
			const referrer = document.referrer;
			if (referrer) {
				this.dataForm.sourceUrl = referrer;
			} else {
				const pages = getCurrentPages();
				const currentPage = pages[pages.length - 1];
				const options = currentPage.options || {};
				if (options.from) {
					this.dataForm.sourceUrl = options.from;
				} else {
					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';
			}
			this.dataForm.sourceUrl = this.dataForm.sourceUrl.replace(/\/+$/, '');
			console.log("来源网址：", this.dataForm.sourceUrl);
		},

		// 获取URL参数中的token和customerid
		getTokenFromUrl() {
			// #ifdef H5
			const pages = getCurrentPages();
			const currentPage = pages[pages.length - 1];
			const options = currentPage.options || {};

			if (options.token) {
				this.dataForm.uniqueToken = options.token;
			}

			if (options.customerid) {
				this.dataForm.customerid = options.customerid;
			}

			const urlParams = new URLSearchParams(window.location.search);
			const token = urlParams.get('token');
			const customerid = urlParams.get('customerid');

			if (token) {
				this.dataForm.uniqueToken = token;
			}

			if (customerid) {
				this.dataForm.customerid = customerid;
			}
			// #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;
			}
			if (options.customerid) {
				this.dataForm.customerid = options.customerid;
			}
			// #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(options);
			if (options.customerid) {
				this.dataForm.customerid = options.customerid;
			}
			// #endif
		},

		async autoLogin() {
			if (GLOBAL_AUTO_LOGIN_LOCK) return;
			GLOBAL_AUTO_LOGIN_LOCK = true;

			// 获取token（优先使用URL中的token）
			this.getTokenFromUrl();

			// 判断是否有 token，没有则跳转 404
			if (!this.dataForm.uniqueToken) {
				console.log("未携带token，跳转到404页面");
				// #ifdef H5
				window.location.href = '/h5/#/pages/login/404';
				// #endif

				// #ifndef H5
				uni.redirectTo({
					url: '/pages/login/404'
				});
				// #endif

				GLOBAL_AUTO_LOGIN_LOCK = false;
				return;
			}

			// 获取来源网址
			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,
				customerId: this.dataForm.customerid,
			};

			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();
				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);

					this.clearUrlParams();

					// #ifdef H5
					const cleanUrl = window.location.origin + '/h5/#/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);
				GLOBAL_AUTO_LOGIN_LOCK = false;
				this.clearUrlParams();

				// #ifdef H5
				window.location.href = '/h5/#/pages/login/404';
				// #endif

				// #ifndef H5
				uni.redirectTo({ url: '/pages/login/404' });
				// #endif
			});
		},

		clearUrlParams() {
			// #ifdef H5
			const url = new URL(window.location.href);
			url.searchParams.delete('token');
			url.searchParams.delete('customerid');
			window.history.replaceState(null, '', url.pathname + url.search + url.hash);
			// #endif
		},

		getIp() {
			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) {
		if (options.token) {
			this.dataForm.uniqueToken = options.token;
			console.log("onLoad获取到token：", this.dataForm.uniqueToken);
		}
		if (options.customerid) {
			this.dataForm.customerid = options.customerid;
			console.log("onLoad获取到customerid：", this.dataForm.customerid);
		}
		setTimeout(() => {
			this.autoLogin();
		}, 50);
	},

	onShow() {

	}
}
</script>
