import {defineStore} from "pinia";
import {ref} from "vue";
import {useSystemStore} from "../SystemStore/index.js";
import Api from "../../api/index.js";
import {toPath} from "../../utils/index.js";

export const useUserStore = defineStore("UserStore", () => {
    const isLogin = ref(false);
    const userInfo = ref(null);
    const token = ref(null);

    const login = async (isRoot = false, form) => {
        // 请求
        const data = {};
        if (isRoot) { // 管理员
            if (form.code) {
                const {data: _data} = await Api.admin.phoneLogin(form);
                Object.assign(data, _data);
            } else {
                const {data: _data} = await Api.admin.login(form);
                Object.assign(data, _data);
            }
        } else { // 商户
            if (form.code) {
                const {data: _data} = await Api.merchant.phoneLogin(form);
                Object.assign(data, _data);
            } else {
                const {data: _data} = await Api.merchant.login(form);
                Object.assign(data, _data);
            }
        }
        // 修改状态
        isLogin.value = true;
        token.value = data.token;
        userInfo.value = data;
        // // 获取并安装路由
        const {setRouter} = useSystemStore();
        await setRouter(isRoot);
        // // 跳转
        toPath('/home');
    }

    const logout = async () => {
        isLogin.value = false;
        userInfo.value = null;
        token.value = null;
        const {clearRouter} = useSystemStore();
        await clearRouter();
    }
    return {
        isLogin,
        userInfo,
        token,
        login,
        logout,
    }
}, {
    persist: {
        key: 'UserStore',
        storage: localStorage,
        pick: ['isLogin', 'token', 'userInfo']
    }
});
