import { defineStore } from 'pinia';
import { UserInfosState } from 'storeInterface';
import { Session } from '@/utils/storage';
import Cookies from 'js-cookie';
import { letterAvatar } from '@/utils/string';
import { authUser } from '@/api/system/user';
import { goAuth } from '@/utils/util';


/* 获取URL中的参数 */
function getUrlParams(url) {
	// 定义一个空对象，用于存储参数
	const params = {};
	// 获取URL中的查询字符串
	const queryString = url.match(/\?.*/) ? url.match(/\?.*/)[0] : '';

	// 如果查询字符串存在
	if (queryString) {
		// 定义一个正则表达式，用于匹配参数
		const regex = /[?&]?([^=]+)=([^&]*)/g;
		let match;
		while ((match = regex.exec(queryString)) !== null) {
			params[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
		}
	}
	return params as any;
}


export const useUserInfosState = defineStore('userInfos', {
	state: (): UserInfosState => ({
		userInfos: {
			username: '',
			nickname: '',
			photo: '',
			time: 0,
			authBtnList: [],

			userId: 0,
			roleId: 0,
			roleName: '',
			organizationId: 0,
			organizationName: '',
			postId: 0,
			postName: '',

			lastLoginTime: 0,
			lastLoginIp: '127.0.0.1',
		},
	}),
	actions: {
		// 设置用户信息
		getUserInfos(data: object) {
			this.userInfos = data;
		},
		// 设置用户信息
		async setUserInfos() {
			const username = Cookies.get('username');

			// 获取url参数
			const url = getUrlParams(window.location.href);
			// 获取指定的查询参数
			const secret = url && url.secret
			const secretRes = await fetch(`/api/user/oauth/secret/${secret}`)
			console.log("secretRes", secretRes)
			if (!secretRes?.ok) {
				goAuth()
			}
			const secretRes1 = await secretRes.json(); // 解析 JSON 数据
			console.log("secretRes1", secretRes1)
			if (!secretRes1?.data?.uid) {
				goAuth()
			}
			let response = await authUser();
			let loginRes = response.data;

			Cookies.set('nickname', loginRes.user.nickname);
			Session.set('menus', loginRes.menus);
			let perms = loginRes.permissions;
			perms.push('base');
			// 用户信息模拟数据
			const userInfos = {
				userId: loginRes.user.userId,
				username: loginRes.user.username,
				nickname: loginRes.user.nickname,

				roleId: loginRes.user.roleId,
				roleName: loginRes.user.roleName,

				organizationId: loginRes.user.organizationId,
				organizationName: loginRes.user.organizationName,

				postId: loginRes.user.postId,
				postName: loginRes.user.postName,

				// 头像
				photo: loginRes.user.avatar || letterAvatar(loginRes.user.nickname),
				time: new Date().getTime(),
				lastLoginTime: new Date().getTime(),
				lastLoginIp: '127.0.0.1',
				authBtnList: perms,
			};
			// 存储用户信息到浏览器缓存
			Session.set('userInfo', userInfos);

			if (Session.get('userInfo')) {
				this.getUserInfos(Session.get('userInfo'));
			} else {
				this.getUserInfos(userInfos);
			}
		},
		async setUserInfo() {
			this.getUserInfos(Session.get('userInfo'));
		},
	},
});
