import { ref } from 'vue';

import { defineStore } from 'pinia';

import tianti from '#/io/tianti';
import { getCurrentUser } from '#/io/user';

export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref<string>();
    const perms = ref<string[]>([]);
    const userInfo = ref({});

    const setToken = (_token: string) => {
      token.value = _token;
    };

    /** 清空登录态(token、userInfo...) */
    const clearLoginStatus = () => {
      token.value = '';
      perms.value = [];
      userInfo.value = {};
      setTimeout(() => {
        localStorage.clear();
      });
    };
    /** 登录 */
    const login = async () => {
      tianti.checkQuery();
      const token = localStorage.getItem('y-code-access-token');
      if (token) {
        setToken(token);
        setTimeout(() => {
          getCurrentUser().then((res) => {
            userInfo.value = res.data.data;
            console.log('userInfo', userInfo.value);
          });
        }, 1000);
      }
    };
    /** 登出 */
    const logout = async () => {
      await tianti.logout();
      clearLoginStatus();
    };

    function $reset() {
      token.value = '';
      perms.value = [];
      userInfo.value = {};
    }

    return {
      $reset,
      token,
      perms,
      userInfo,
      login,
      logout,
      clearLoginStatus,
    };
  },
  {
    persist: {
      pick: ['token'],
    },
  },
);
