import { loginApi, getInfoApi } from "@/services/api/user/userAPI"
import { LoginParm } from "@/services/types/user/UserModel"
import { ActionContext } from "vuex"
import { RootState } from "../index"
import { setUserId, setToken, setExpireTime } from "@/utils/auth";
import { toLogin } from "@/services/api/login/login"

//定义state类型
export type UserState = {
    token: string,
    userId: string,
    userName: string,
    permissions: string[],
    userAvatar:string
}
//定义state
export const state: UserState = {
    token: '',
    userId: '',
    userName: '',
    permissions: [],
    userAvatar:''
}
//定义mutations
export const mutations = {
    setToken(state: UserState, token: string) {
        state.token = token
    },
    setUserId(state: UserState, userId: string) {
        state.userId = userId
    },
    setRoles(state: UserState, roles: string[]) {
        state.permissions = roles;
    },
    setUserName(state: UserState, userName: string) {
        state.userName = userName
    },
    setUserAvatar(state: UserState, userAvatar:string){
        state.userAvatar = userAvatar
    }
}
//定义actions
export const actions = {
    //获取用户信息
    getInfo({ commit }: ActionContext<UserState, RootState>) {
        return new Promise((resolve, reject) => {
            getInfoApi().then(res => {
                //设置权限信息到vuex里面
                if (res.code == 200) {
                    commit('setUserAvatar',res.data.avatar)
                    commit('setRoles', res.data.roles)
                }
                resolve(res.data)
            }).catch(error => {
                reject(error)
            })
        })
    },
    //登录
    login({ commit }: ActionContext<UserState, RootState>, loginParm: LoginParm) {
        return new Promise((resolve, reject) => {
            toLogin(loginParm).then((res: any) => {
                //把返回的token放到vuex里面 和 cookies(sessioStorage)
                if (res.code == 200) {
                    commit('setToken', res.data.token)
                    commit('setUserId', res.data.id)
                    //存到cookies ==> sessioStorage
                    setUserId(res.data.id)
                    setToken(res.data.token)
                    setExpireTime(res.data.expireTime)
                }
                resolve(res)
            })
        })
    }
}
//定义getters
export const getters = {
    //获取用户的权限字段
    getPermissions(state: UserState) {
        return state.permissions
    },
    //获取token
    getToken(state:UserState){
        return state.token
    }
}
export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}
