import { defineStore } from 'pinia'
import { miniAppLogin } from '../services/common'

export const useUserStore = defineStore('user', () => {
	// 用户信息
	const userInfo = ref(uni.getStorageSync('userInfo') || {})
	const setUserInfo = data => {
		userInfo.value = data
		uni.setStorageSync('userInfo', data)
	}

	// token
	const token = ref(uni.getStorageSync('token') || '')
	const setToken = data => {
		token.value = data
		uni.setStorageSync('token', data)
	}

	// 角色
	const roles = ref(uni.getStorageSync('roles') || [])
	const setRoles = data => {
		roles.value = data
		uni.setStorageSync('roles', data)
	}

	// openId
	const openId = ref(uni.getStorageSync('openId') || '')
	const setOpenId = data => {
		openId.value = data
		uni.setStorageSync('openId', data)
	}

	// 系统信息
	const systemInfo = ref(uni.getStorageSync('systemInfo') || {})
	const setSystemInfo = data => {
		systemInfo.value = data
		uni.setStorageSync('systemInfo', data)
	}

	const login = data => {
		return new Promise((resolve, reject) => {
			miniAppLogin().then(res => {
				if (res.success) {
					setUserInfo(res.user || {})
					setToken(res.token || '')
					setRoles((res.roles || []).map(item => item.name))
					setOpenId(res.openId || '')
					resolve(res)
				} else {
					reject(res)
				}
			}).catch(err => {
				logout()
				reject(err)
			})
		})
	}

	const logout = () => {
		return new Promise(resolve => {
			setUserInfo({})
			setToken('')
			setRoles([])
			setOpenId('')
			setSystemInfo({})
			resolve()
		})
	}

	return {
		userInfo,
		setUserInfo,
		token,
		setToken,
		roles,
		setRoles,
		openId,
		setOpenId,
		systemInfo,
		setSystemInfo,
		login,
		logout
	}
})
