import {
	defineStore
} from 'pinia'
import {
	ref
} from 'vue'
import {
	login,
	getInfo,
	logout
} from '@/api/login.js'
import {
	getUserInfo,
	getSession,
	setSession
} from '@/utils/auth'
import {
	reLogin,
	keepSession
} from '@/api/login.js'


export const useUserStore = defineStore('user', () => {
	const user = ref(getUserInfo()) // 用户信息
	const useId = ref(0) // staffId
	const timer = ref(true) //定时器
	function keep() {
		keepSession().then(res => {
			setTimeout(() => {
				if (timer.value) {
					keep()
				}
			}, 600000)
		})
	}
	// 登录方法
	function Login(userInfo) {
		const username = userInfo.username
		const password = userInfo.password
		const loginInfo = {
			username,
			password
		}
		return new Promise((resolve, reject) => {
			login(username.trim(), password)
				.then(res => {
					useId.value = res.returnParams.useId // 设置staffId
					user.value = res.returnParams
					//保存账号密码
					uni.setStorageSync('loginInfo', loginInfo)
					// setSession(res.session)
					reLogin(username.trim(), password).then((res) => {
						if ("ok" === res.data) {
							setSession(res.cookies[0].split("=")[1].split(";")[0]);
							timer.value = true
							keep()
						}
					})
					resolve(res)
				})
				.catch(error => {
					reject(error)
				})
		})
	}

	function GetInfo(index) {
		const roleIndex = index || 0
		return new Promise((resolve, reject) => {
			getInfo(useId.value).then(res => {
					const source = res.returnParams[roleIndex]
					Object.keys(source).forEach(key => {
						// 目标对象没有该属性或者该属性为 null，则赋值
						if (!(key in user.value) || user.value[key] === null || user.value[
								key] === "") {
							user.value[key] = source[key] === undefined ? user.value[key] :
								source[key];
						}
					});
					// 保存 用户信息
					uni.setStorageSync('userInfo', user.value)
					resolve(res)
				})
				.catch(error => {
					reject(error)
				})
		})
	}

	function LogOut() {
		return new Promise((resolve, reject) => {
			// logout().then(() => {
			user.value = {}
			useId.value = 0
			timer.value = false
			uni.clearStorageSync()
			resolve()
		}).catch(error => {
			reject(error)
		})
		// })
	}


	return {
		user,
		useId,
		Login,
		GetInfo,
		LogOut
	}
})