import UserApi, { LoginResult, UserInfo } from "@/api/auth/UserApi";
import { RequestSharedData } from "@/common/request/core/RequestSharedData";
import { defineStore } from "pinia"

const STORAGE_KEY = 'authInfo';

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: '',
    expireAt: 0,
    userId: 0,
    userInfo: null as null|UserInfo,
  }),
  actions: {
    async loadLoginState() {
      try {
        const res = localStorage.getItem(STORAGE_KEY);
        if (!res)
          throw 'no storage';
        const authInfo = JSON.parse(res);
        this.setToken(authInfo.token, authInfo.userId);
        this.expireAt = authInfo.expireAt;

        // 检查token是否过期，如果快要过期，则刷新token
        if (Date.now() > this.expireAt + 1000 * 3600 * 5) {
          const refreshResult = await UserApi.refresh();
          this.loginResultHandle(refreshResult);
          this.userInfo = refreshResult.userInfo;
        } else {
          this.userInfo = await UserApi.getUserInfo(this.userId);
        }
      } catch (error) {
        this.setToken('', 0);
        this.userInfo = null;

        console.log('loadLoginState', error);
      }
    },
    async loginAdmin(account: string, password: string) {
      const loginResult = await UserApi.loginAdmin({
        account,
        password,
      })
      this.loginResultHandle(loginResult);
    },
    async loginResultHandle(loginResult: LoginResult) {
      this.setToken(loginResult.userInfo.token, loginResult.userInfo.id);
      this.userInfo = loginResult.userInfo;
      this.expireAt = loginResult.userInfo.expiresIn + Date.now();

      localStorage.setItem(STORAGE_KEY, 
        JSON.stringify({ 
          token: this.token, 
          userId: this.userId ,
          expireAt: this.expireAt,
        }) 
      );
    },
    async logout() {
      this.setToken('', 0);
      this.userInfo = null;

      localStorage.removeItem(STORAGE_KEY);
    },
    setToken(token: string, userId: number) {
      this.token = token;
      this.userId = userId;
      RequestSharedData.set('token', token);
      RequestSharedData.set('userId', userId);
    }
  },
  getters: {
    isLogged(state) {
      return state.token != '' && state.userId != 0
    },
  },
})