import UserApi, { LoginResult, UserInfo } from "@/api/auth/UserApi";
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 = await uni.getStorage({ key: STORAGE_KEY });
        if (!res.data)
          throw 'no storage';
        const authInfo = JSON.parse(res.data);
        this.token = authInfo.token;
        this.userId = 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.mainBodyUserInfo;
        } else {
          this.userInfo = await UserApi.getUserInfo(this.userId);
        }
      } catch (error) {
        this.token = '';
        this.userId = 0;
        this.userInfo = null;

        console.log('loadLoginState', error);
      }
    },
    async loginWechart(code: string, res: UniApp.GetUserProfileRes) {
      const loginResult = await UserApi.loginThird({
        code,
        encrypted_data: res.encryptedData,
        iv: res.iv,
        platform: 'wechat',
        raw_data: JSON.parse(res.rawData),
        signature: res.signature,
      })
      this.loginResultHandle(loginResult);
    },
    async loginMobile(mobile: string, password: string) {
      const loginResult = await UserApi.loginWithMobile({
        mobile,
        password,
      })
      this.loginResultHandle(loginResult);
    },
    async loginResultHandle(loginResult: LoginResult) {
      this.token = loginResult.auth.token;
      this.userId = loginResult.mainBodyUserInfo.id;
      this.userInfo = loginResult.mainBodyUserInfo;
      this.expireAt = loginResult.auth.expiresIn + Date.now();

      console.log('loginResultHandle');
      
      uni.setStorage({ 
        key: STORAGE_KEY, 
        data: JSON.stringify({ 
          token: this.token, 
          userId: this.userId ,
          expireAt: this.expireAt,
        }) 
      });
    },
    async logout() {
      this.token = '';
      this.userId = 0;
      this.userInfo = null;

      uni.removeStorage({ key: STORAGE_KEY });
    }
  },
  getters: {
    isLogged(state) {
      return state.token != '' && state.userId != 0
    },
  },
})