import {defineStore} from "pinia";
import {reactive, ref} from "vue";
import {clearObject, toPage} from "../../utils/uils.js";
import Api from "../../api/index.js";

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

    const logout = async () => {
        isLogin.value = false;
        token.value = null;
        clearObject(userInfo);
        await toPage("/pages/login/index");
    }

    const getUserInfo = async () => {
        const {data} = await Api.system.getInfo();
        Object.assign(userInfo, data);
    }

    const passLogin = async (id) => {
        const {data} = await Api.system.passLogin(id);
        Object.assign(userInfo, data);
        isLogin.value = true;
        token.value = data.token;
        await toPage('/pages/user/index');
    }

    const setToken = (value) => {
        isLogin.value = true;
        token.value = value;
    }

    return {
        isLogin,
        userInfo,
        token,
        logout,
        setToken,
        getUserInfo,
        passLogin,
    }
}, {
    persist: {
        key: 'UserStore',
        pick: ['isLogin', 'userInfo', 'token'],
        storage: {
            getItem(key) {
                return uni.getStorageSync(key);
            },
            setItem(key, value) {
                uni.setStorageSync(key, value);
            }
        },
    }
});
