import storage from '@/utils/storage';
import { getInfo, getTokenByUserId } from "@/api/login";

const AccessTokenKey = 'ACCESS_TOKEN'
const RefreshTokenKey = 'REFRESH_TOKEN'

// ========== Storage 相关 ==========

export function clearStorge() {
	// console.log('clear---------')
	uni.clearStorageSync();
}

// ========== Token 相关 ==========

export function getAccessToken() {
	return uni.getStorageSync(AccessTokenKey)
}

export function getRefreshToken() {
	return uni.getStorageSync(RefreshTokenKey)
}

export function setToken(token) {
	uni.setStorageSync(AccessTokenKey, token.accessToken)
	uni.setStorageSync(RefreshTokenKey, token.refreshToken)
}

export function removeToken() {
	uni.removeStorageSync(AccessTokenKey)
	uni.removeStorageSync(RefreshTokenKey)
}


// ========== 用户相关 ==========
export function getTenantId() {
	const tenantId = uni.getStorageSync('tenantId');
	// console.log('getTenantId---------', tenantId)
	// return tenantId
	return '1'
}

export function setTenantId(tenantId) {
	uni.setStorageSync('tenantId', tenantId)
}

export function removeTenantId() {
	uni.removeStorageSync('tenantId')
}

export function setUserId(userid) {
	// console.log('setUserId---------', userid)
	uni.setStorageSync('userId', userid);
}
export function getUserId() {
	const userId = uni.getStorageSync('userId');
	// console.log('getUserId---------', userId)
	return userId
}
export function setDeptId(deptId) {
	// console.log('setDeptId---------', deptId)
	uni.setStorageSync('deptId', deptId);
}
export function getDeptId() {
	const deptId = uni.getStorageSync('deptId');
	// console.log('getDeptId---------', deptId)
	return deptId
}
export function setUserInfo(data) {
	// console.log('setUserInfo---------', data)
	uni.setStorageSync('userInfo', JSON.stringify(data));
}
export function getUserInfo() {
	const info = uni.getStorageSync('userInfo');
	// console.log('getUserInfo---------', info)
	return info
}
export function removeUserInfo() {
	uni.removeStorageSync('deptId')
	uni.removeStorageSync('userId')
	uni.removeStorageSync('userInfo')
}

/**
 * 通过userId刷新token
 * @param userId
 * @returns {Promise<void>}
 */
export const reloginByUserId = async (userId) => {
	if (!userId) return
	const isLoggedIn = uni.getStorageSync("userId")
	if (!isLoggedIn) {
		const result = await getTokenByUserId(userId)
		setUserId(result.data.userId)
		setToken(result.data)

		const info = (await getInfo()).data
		setUserInfo(JSON.stringify({ user: info.user, roles: info.roles }))
		setDeptId(info.user.deptId)
	}
}