import { defineStore } from "pinia";
import { ref } from "vue";
import { theme } from "@/config/index";
import { useLoginApi } from "@/Apis/login";
import { authInfoApi } from "@/Apis/validInfo.js";
const getApi = useLoginApi();
const getAuthApi = authInfoApi();
export const useMainStore = defineStore('main', () => {
	const storeState = ref({
		token:'',
		userInfo:{}, //userType应该是管理员。2是管理员，3是开门管理员
		location: {},
		hasVerify:false, // 是否已经验证过
		hasTrytoLogin:false, // 是否尝试过登录
	})
	function setToken(token) {
		storeState.value.token = token
	}
	const setHasVerify = (hasVerify) => {
		storeState.value.hasVerify = hasVerify;
	}
	const getHasVerify = async () => {
	    if (!storeState.value.hasVerify) {
	       // 判断是否认证
			let { code, data } =
			await getAuthApi.GetIsCertification();
			if (code == 200 && data?.isPass) {
				setHasVerify(data?.isPass);
				return data;
			}
	    }
		return storeState.value.hasVerify;
	}
	const themeInfo = ref({});
	function setTheme() {
		const language = uni.getStorageSync("eliteSys-language-wx") || "zh-Hans";
		const themeList = [
			{ theme: "default", iconColor: "#FFFFFF", activeColor: "#00A7BE" },
			{ theme: "golden", iconColor: "#0F2232", activeColor: "#F6BD42" },
		];
		let item = themeList.find(item => item.theme == theme);
		item.language = language === "en" ? "en_lang" : "zh_lang";
		themeInfo.value = item;
	}
	// 获取用户信息
	const getUserInfo = ()=>{
		return getApi.GetUserInfo().then(res=>{
			if(res.code == 200){
				storeState.value.userInfo = res.data ?? {}
				storeState.value.hasTrytoLogin = true
				uni.setStorage({
					key:'userInfo',
					data:res.data
				})

			}else{
				storeState.value.userInfo = {}
				logOut()
			}
			return res
		}).catch((err=>{
			storeState.value.userInfo = {}
			logOut()
			return err
		}))
	}
	// 退出登陆
	const logOut = ()=>{
		storeState.value.token = ''
		storeState.value.userInfo = {}
		uni.removeStorage({
			key:'token'
		}); // 清除缓存
	}

	const setLocation = (location) => {
		storeState.value.location = location;
	}

	return { storeState, setToken, themeInfo, setTheme, getUserInfo, logOut, setLocation,getHasVerify };
});