import { BASE_URL } from '@/utils/CommonValues.js';
import StaticValue from '@/utils/StaticValue.js';
import { GET, GET_TOKEN } from '@/utils/request';
import { login } from '@/api/user.js';
var uuid = '';
var code = '';
const getUserInfo = StaticValue.getUserInfo;
const setUserInfo = StaticValue.setUserInfo;
// 登录系统
export async function loginSystem() {
	return new Promise((resolve, reject) => {
		// 登录[获取token]
		uni.request({
			method: 'GET',
			url: `${BASE_URL}/captchaImage`,
			dataType: 'json',
			success: res => {
				uuid = res.data.uuid
				code = res.data.codeStr
				const data = {
					"username": "admin",
					"password": "admin123",
					"uuid": uuid,
					"code": code
				}
				var str = JSON.stringify(data)
				uni.request({
					method: 'POST',
					url: `${BASE_URL}/login`,
					header: {
						"Content-Type":"application/json;charset=UTF-8"
					},
					data: str,
					dataType: 'json',
					success: res => {
						if(res.data.code == '200') {
							resolve(res.data.token)
						} else {
							reject(res)
						}
					},
					fail: err => {
						reject(res)
					}
				})
			},
			fail(error) {
				console.log("获取验证码失败", error)
			}
		})
	})
}

export async function getToken() {
	// uni.clearStorage('APP_TOKEN')
	console.log("获取token被执行了")
	loginSystem().then(token => {
		uni.setStorage({
			key: 'APP_TOKEN',
			data: token,
			success(res) {
				console.log("存入token", token, res)
			},
			fail(err) {
				console.log("存入token失败", token, err)
			}
		})
	}).catch(error => {
		console.log("获取token失败", error)
	})
	setTimeout(() => {
		getToken();
	}, 58*60*1000)
}

// 校验本地登录信息
export async function checkLoginStatus() {
	const userInfo = getUserInfo();
	if(!userInfo) {
		return;
	}
	const token = await loginSystem();
	console.log(token)
	if(token.data) {
		// 如果有code表示没有拿到token
		checkLoginStatus()
		return;
	}
	login(userInfo).then(res => {
		const userData = res.data;
		// 保存信息到本地
		setUserInfo(userData);
		console.log('自动登录成功:', userData);
	}).catch(err => {
		console.log('login err: ', err);
	})
}