import {globalConfig} from '@/config';
import storage from '@/utils/storage';
import {constant} from '@/utils/constant';
import { login, logout, getInfo } from '@/api/login';
import { getToken, setToken, removeToken, setCurrentUserSync, setCurrentUserNameSync } from '@/utils/auth';
import profileImg from '@/static/images/profile.jpg';

type State = {
  token: string,
  name: string,
  username: string,
  avatar: string,
  roles: string[],
  permissions: string[],
}

const tokenValue = getToken() ??'' as string;
console.log('Token value:', tokenValue);

const nameValue = storage.get(constant.name)??'' as string;
console.log('Name value:', nameValue);

const usernameValue = storage.get(constant.username)??'' as string;
console.log('UserName value:', usernameValue);

const avatarValue = storage.get(constant.avatar)??'' as string;
console.log('Avatar value:', avatarValue);

const rolesValue = storage.get(constant.roles)?? [] as string[];
console.log('Roles value:', rolesValue);

const permissionsValue = storage.get(constant.permissions)?? [] as string[];
console.log('Permissions value:', permissionsValue);

export const state = reactive({
  token: tokenValue,
  name: nameValue as string,
  username: usernameValue as string,
  avatar: avatarValue as string,
  roles: rolesValue as string[],
  permissions: permissionsValue as string[]
} as State)

export const SetToken=(token: string)=>{
	state.token = token;
	setToken(token)
}

export const SetCurrentUser=(username: string)=>{
	state.username = username;
	setCurrentUserNameSync(username)
}

export const SetUserName=(name: string)=>{
	state.name = name;
	setCurrentUserSync(name)
}

export const cleanAll=()=>{
	uni.removeStorageSync('storage_data')
}

export const SetAvatar=(avatar: string)=> {
	state.avatar = avatar;
	storage.set(constant.avatar, avatar);
}

export const SetRoles=(roles: string[])=>{
    state.roles = roles;
    storage.set(constant.roles, roles);
}
	
export const SetPermissions=(permissions: string[]) =>{
	  state.permissions = permissions;
	  storage.set(constant.permissions, permissions);
}
  // 登录
export const Login=(userInfo:UTSJSONObject):Promise<void>=> {
    const username:string = (userInfo.getString("username") as string).trim() as string;
    const password:string = userInfo.getString("password") as string;
    const code:string = userInfo.getString("code") as string;
    const uuid:string = userInfo.getString("uuid") as string;
			
	return new Promise((resolve, reject) => {
	  login(username, password, code, uuid).then((res:UTSJSONObject) => {
	    //SetToken(res.getString("token") as string);
		let msg = res.getString("errMsg")
		let data = res.getArray("data") as UTSJSONObject[]
		if(msg == 'ok' && data.length>0){
			SetToken(data[0].getString("token") as string)
			SetUserName(data[0].getString("name") as string)
			SetCurrentUser(username)
			resolve()
		}else{
			reject('登录失败,账户或密码不匹配！')
		}	    
	  })
	})
  }

  // 获取用户信息
export const GetInfo=():Promise<UTSJSONObject>=> {
  return new Promise((resolve, reject) => {
	getInfo().then((res:UTSJSONObject) => {
	console.log(res)	
	  let avatar:string=profileImg as string
	  let username:string="" as string
	  let name:string="" as string
	  let roles=[] as string[]
	  const resMap=res.toMap() as Map<string,any>
	   if(resMap.has("data")){
		   const data:UTSJSONObject[]|null = resMap?.get("data") as UTSJSONObject[] ?? null;
		   if(data!=null && data.length>0){
			const user = data?.[0] as UTSJSONObject   
			const userMap=user.toMap() as Map<string,any>
			console.log(userMap)
			if(userMap.has("avatar")&&user.getString("avatar")!=null&&user.getString("avatar")!=""){
				avatar=globalConfig.baseUrl + user.getString("avatar") as string
			}
			if(userMap.has("username")&&user.getString("username")!=null&&user.getString("username")!=""){
				username= user.getString("username") as string
			}
			if(userMap.has("name")&&user.getString("name")!=null&&user.getString("name")!=""){
				name= user.getString("name") as string
			}
			if(userMap.has("role") &&user.getString("role")!=null&&user.getString("role")!=""){
				roles.push(user.getString("role") as string)
			}
		   }
	   }
	   
	   if(resMap.has("roles")){
		   roles=res.getArray<string>("roles") as string[]
		   if(roles.length>0){
			   let permissions=[] as string[]
			   if(resMap.has("permissions")){
				   permissions=res.getArray<string>("permissions") as string[]
			   }
			   SetPermissions?.(permissions);
		   }
	   }
	   SetRoles?.(roles)
	   SetUserName?.(name);
	   SetCurrentUser?.(username);
	   SetAvatar?.(avatar);
	   resolve(res)
	})
  })
}

  // 退出系统
  export const LogOut=():Promise<UTSJSONObject>=> {
	return new Promise<UTSJSONObject>((resolve, reject) => {
	  console.log(state.token)
	  logout().then(() => {
	    SetToken('');
		SetRoles([]);
		SetCurrentUser('');
		SetUserName('');
		SetPermissions([]);   
		removeToken();
		cleanAll();
	    resolve({});
	  })
	})
  }

