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,
    loginType: 0,
  }),
  actions: {
    async loadLoginState() {
      try {
        const res = await uni.getStorage({ key: STORAGE_KEY });
        if (!res.data)
          return false;
        const authInfo = JSON.parse(res.data);
        this.token = authInfo.token;
        this.userId = authInfo.userId;
        this.userInfo = authInfo.userInfo;
        this.loginType = authInfo.loginType;
        setToken(this.token);
        //检查登录是否过期
        await UserApi.checkUserAuthed();
        return true;
      } catch (error) {
        this.token = '';
        this.userId = 0;
        this.userInfo = null;
        setToken('');
        console.log('loadLoginState', error);
        return false;
      }
    },
    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, 0);
    },
    async loginMobile(account: string, password: string, loginType: number) {
      let loginResult;
      if (loginType == 0) {
        loginResult = await UserApi.login({
          account,
          password,
        })
      } else if (loginType == 1) {
        loginResult = await UserApi.loginAdmin({
          account,
          password,
        })
      } else
        throw 'login type error';
      this.loginResultHandle(loginResult, loginType);
    },
    async loginResultHandle(loginResult: LoginResult, loginType: number) {
      this.token = loginResult.token;
      this.userId = loginResult.userInfo.id;
      this.userInfo = loginResult.userInfo;
      this.loginType = loginType;
      setToken(this.token);
      this.saveLoginState();
    },
    async logout() {
      this.token = '';
      this.userId = 0;
      this.userInfo = null;
      setToken('');
      uni.removeStorage({ key: STORAGE_KEY });
    },
    saveLoginState() {
      uni.setStorage({ 
        key: STORAGE_KEY, 
        data: JSON.stringify({ 
          token: this.token, 
          userId: this.userId ,
          expireAt: this.expireAt,
          userInfo: this.userInfo,
          loginType: this.loginType,
        }) 
      });
    },
    getInternalAuth() {
      return { 
        token: this.token, 
        userId: this.userId ,
        expireAt: this.expireAt,
        userInfo: this.userInfo,
        loginType: this.loginType,
      }
    },
  },
  getters: {
    isAdmin(state) {
      return state.loginType === 1;
    },
    isLogged(state) {
      return state.token != '' && state.userId != 0
    },
  },
})

function setToken(token: string) {
  const app = getApp();
  if (!!app.globalData)
    app.globalData = {};
  return app.globalData!.token = token;
}
