import {to} from 'await-to-js';
import defAva from '@/assets/images/profile.jpg';
import store from '@/store';
import {getToken, removeToken, setToken} from '@/utils/auth';
import {
    login as loginApi,
    logout as logoutApi,
    getInfo as getUserInfo,
    getResource as getResourceApi, loginWxApi
} from '@/api/login';
import {LoginData, LoginResult} from '@/api/types';
import {UserInfo, UserVO} from "@/api/system/user/types";
import {AxiosPromise} from "axios";

export const useUserStore = defineStore('user', () => {
    const token = ref(getToken());
    const name = ref('');
    const nickname = ref('');
    const userId = ref<string | number>();
    const avatar = ref('');
    const roles = ref<Array<string>>([]); // 用户角色编码集合 → 判断路由权限
    const permissions = ref<Array<string>>([]); // 用户权限编码集合 → 判断按钮权限
    const userInfo = ref<UserInfo>(); //

    /**
     * 登录
     * @param userInfo
     * @returns
     */
    const login = async (userInfo: LoginData): Promise<void> => {
        const [err, res] = await to(loginApi(userInfo));
        if (res) {
            const data = res.result;
            setToken(data.token);
            token.value = data.token;
            return Promise.resolve();
        }
        return Promise.reject(err);
    };

    /**
     * 登录
     * @param userInfo
     * @returns
     */
    const loginWx = async (userInfo: LoginData): AxiosPromise<LoginResult> => {
        const [err, res] = await to(loginWxApi(userInfo));
        if (res) {
            const data = res.result;
            setToken(data.token);
            token.value = data.token;
        }
        return res
    };

    // 获取用户信息
    const getInfo = async (): Promise<void> => {
        const [err, res] = await to(getUserInfo());

        if (res) {
            const data = res.result;
            const user = data;
            userInfo.value = data;
            permissions.value = user.btnRes
            name.value = user.realName;
            roles.value = user.roleIds
            nickname.value = user.userName;
            avatar.value = user.avatar;
            userId.value = user.id;
            return Promise.resolve();
        }
        return Promise.reject(err);
    };

    // 注销
    const logout = async (): Promise<void> => {
        token.value = '';
        roles.value = [];
        permissions.value = [];
        removeToken();
        // await logoutApi();

    };

    const setAvatar = (value: string) => {
        avatar.value = value;
    };

    return {
        userId,
        token,
        nickname,
        avatar,
        roles,
        permissions,
        login,
        getInfo,
        logout,
        setAvatar,
        userInfo,
        loginWx
    };
});

export default useUserStore;

// 非setup
export function useUserStoreHook() {
    return useUserStore(store);
}
