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,
      })
      await this.loginResultHandle(
        loginResult, 
        //登录类型根据返回值判断
        loginResult.isAdmin ? 1 : 0,
      );
      return loginResult;
    },
    /**
     * 手机号登录
     */
    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';
      await this.loginResultHandle(loginResult, loginType);
      return loginResult;
    },
    /**
     * 处理登录结果
     */
    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;
}
