import { defineStore } from 'pinia'
import { loginApi, getInfoApi } from "@/api/user/user"
import { LoginParm } from "@/api/user/UserModel"
import { Result } from "@/http/request"
import { setUserId, setToken, setExpireTime, getUserId, setSysUserRoleDto, setDeptCodeList } from "@/utils/auth"
//定义state类型
export type UserState = {
    token: string,
    userId: string | number,
    permissions: string[],
    name: string,
    /**
     * 当前用户可选分公司
     */
    deptCodeList: string[],
    /**
     * 角色与用户id
     */
    sysUserRoleDto: {
        id?: number,
        userId?: number,
        roleId?: number,
        oldId?: number//旧用户id
    }
}
//定义store
export const userStore = defineStore('userStore', {
    state: (): UserState => {
        return {
            token: '',
            userId: getUserId() || '',
            permissions: [],
            name: '用户名称',
            deptCodeList: [],
            sysUserRoleDto: {}
        }
    },
    actions: {
        //获取用户信息
        getInfo() {
            return new Promise((resolve, reject) => {
                getInfoApi().then(res => {
                    //设置权限信息到vuex里面
                    if (res.code == 200) {
                        const resData = res.data
                        this.permissions = resData.roles
                        this.name = resData.name
                        this.deptCodeList = resData.deptCodeList;
                        this.sysUserRoleDto = resData.sysUserRoleDto;
                        setDeptCodeList(resData.deptCodeList)
                        setSysUserRoleDto(resData.sysUserRoleDto)
                    } else if(res.code === 500) {
                        reject(res.msg)
                    }
                    resolve(res.data)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        //登录
        login(loginParm: LoginParm) {
            return new Promise<Result>((resolve, reject) => {
                loginApi(loginParm).then(res => {
                    //把返回的token放到vuex里面 和 cookies(sessioStorage)
                    if (res.data.code == 200) {
                        const resData = res.data
                        this.token = resData.token;
                        this.userId = resData.id;
                        //存到cookies ==> sessioStorage
                        setUserId(resData.id)
                        setToken(resData.token)
                        setExpireTime(resData.expireTime)
                    } else if(res.code === 500) {
                        reject(res.msg)
                    }
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        }
    },
    getters: {
        getPermissions(state) {
            return state.permissions
        }
    }
})