import { getInfo, login, logout, refreshToken, ssoLogin, ssoLogout } from '@/api/login'
import request from '@/benyun/utils/request'
import { getToken, removeToken, setExpiresIn, setToken } from '@/benyun/utils/auth'

const user = {
	state: {
		token: getToken(),
		ssoToken: '',
		name: '',
		userInfo: {},
		avatar: '',
		roles: [],
		permissions: []
	},

	mutations: {
		SET_SSOTOKEN: (state : any, ssoToken : string) => {
			state.ssoToken = ssoToken
		},
		SET_TOKEN: (state : any, token : string) => {
			state.token = token
		},
		SET_EXPIRES_IN: (state : any, time : any) => {
			state.expires_in = time
		},
		SET_NAME: (state : any, name : string) => {
			state.name = name
		},
		SET_AVATAR: (state : any, avatar : any) => {
			state.avatar = avatar
		},
		SET_ROLES: (state : any, roles : any) => {
			state.roles = roles
		},
		SET_PERMISSIONS: (state : any, permissions : any) => {
			state.permissions = permissions
		},
		SET_USERINFO: (state : any, userInfo : any) => {
			state.userInfo = userInfo;
		}
	},

	actions: {
		// 登录
		Login({ commit } : any, userInfo : any) {
			const username = userInfo.username.trim()
			const password = userInfo.password
			const code = userInfo.code
			const uuid = userInfo.uuid
			const tenantId = "000000"
			return new Promise((resolve : any, reject : any) => {

				login(username, password, code, uuid, tenantId).then((res : any) => {
					let data = res.data
					setToken(data.access_token)
					commit('SET_TOKEN', data.access_token)
					setExpiresIn(data.expires_in)
					commit('SET_EXPIRES_IN', data.expires_in)
					resolve()
				}).catch((error : any) => {
					reject(error)
				})
			})
		},

		GetToken({commit}:any, params:any) {
			return new Promise((resolve : any, reject : any) => {
				request({
					url: params.url,
					method:'get',
					params:params.data
				}).then((res:any) => {
					let data = res.data
					setToken(data.token)
					commit('SET_TOKEN', data.token)
					commit('SET_SSOTOKEN', data.ssoToken)
					setExpiresIn(720)
					commit('SET_EXPIRES_IN', 720)
					resolve()
				}).catch((error:any) =>{
					reject(error)
				})
				
			})
		},

		// 获取用户信息
		GetInfo({ commit, state } : any) {
			return new Promise((resolve, reject) => {
				getInfo().then((res : any) => {
					const user = res.user
					const avatar = (user.avatar == "" || user.avatar == null) ? require("@/assets/images/profile.jpg") : user.avatar;
					if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
						commit('SET_ROLES', res.roles)
						commit('SET_PERMISSIONS', res.permissions)
					} else {
						commit('SET_ROLES', ['ROLE_DEFAULT'])
					}
					commit('SET_NAME', user.userName)
					commit('SET_AVATAR', avatar)
					commit('SET_USERINFO', user);
					resolve(res)
				}).catch((error : any) => {
					reject(error)
				})
			})
		},

		// 刷新token
		RefreshToken({ commit, state } : any) {
			return new Promise((resolve : any, reject : any) => {
				refreshToken().then((res : any) => {
					setExpiresIn(res.data)
					commit('SET_EXPIRES_IN', res.data)
					resolve()
				}).catch((error : any) => {
					reject(error)
				})
			})
		},

		// 退出系统
		LogOut({ commit, state } : any) {
			return new Promise((resolve : Function, reject : Function) => {
				logout().then(() => {
					commit('SET_TOKEN', '')
					commit('SET_ROLES', [])
					commit('SET_PERMISSIONS', [])
					removeToken()
					resolve()
					// const redirect = location.href.replace(/\??ticket=[^&]*&?/g, '')
					const redirect = location.origin
    			location.href = `${process.env.VUE_APP_LOGIN_URL}?&redirect=${encodeURIComponent(redirect)}`
				}).catch((error : any) => {
					reject(error)
				})
			})
		},

		// 前端 登出
		FedLogOut({ commit } : any) {
			return new Promise((resolve : Function) => {
				commit('SET_TOKEN', '')
				removeToken()
				resolve()
			})
		},

		// 统一系统登录
		ssoLogin({ commit } : any, userInfo : any) {
			const username = userInfo.username.trim()
			const password = userInfo.password
			const code = userInfo.code
			const uuid = userInfo.uuid
			const redirectUri = userInfo.redirectUri
			const appId = userInfo.appId
			return new Promise((resolve : Function, reject : Function) => {
				ssoLogin(username, password, code, uuid, redirectUri, appId).then((res : any) => {
					(window as any).location.href = res
					resolve()
				}).catch((error : any) => {
					reject(error)
				})
			})
		},

		// 退出统一系统
		ssoLogOut({ commit, state } : any) {
			return new Promise((resolve : Function, reject : Function) => {
				ssoLogout().then(() => {
					resolve()
				})
			})
		},
	}
}

export default user