import CollectUserApi from "@/api/auth/CollectUserApi";
import UserApi, { LoginResult, UserInfo } from "@/api/auth/UserApi";
import { defineStore } from "pinia"

const STORAGE_KEY = 'authInfo';

export const LOGIN_TYPE_USER = -1;
export const LOGIN_TYPE_COLLECT = 0;
export const LOGIN_TYPE_COLLECT_ADMIN = 1;

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: '',
    expireAt: 0,
    userId: 0,
    userInfo: null as null|UserInfo,
    loginType: -1,
    loginMp: false,
  }),
  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;
        this.userInfo = authInfo.userInfo;
        this.loginType = authInfo.loginType ?? -1;
        this.loginMp = authInfo.loginMp ?? false;
        this.shareLoginInfo();

        //检查登录是否过期
        await UserApi.checkUserAuthed(this.userId);
        return true;
      } catch (error) {
        this.token = '';
        this.userId = 0;
        this.userInfo = null;
        this.loginMp = false;

        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,
      })
      console.log(loginResult);
      if (loginResult.inheritor) {
        this.loginType = LOGIN_TYPE_COLLECT;
      } else if (loginResult.aub) {
        this.loginType = LOGIN_TYPE_COLLECT_ADMIN;
      } else {
        this.loginType = LOGIN_TYPE_USER;
      }
      this.loginMp = true;
      this.loginResultHandle(loginResult, this.loginType);
    },
    async loginMobile(mobile: string, password: string) {
      const loginResult = await UserApi.loginWithMobile({
        mobile,
        password,
      })
      this.loginMp = false;
      this.loginResultHandle(loginResult);
    },
    async loginCollect(mobile: string, password: string, loginType: number) {
      let loginResult;
      if (loginType == LOGIN_TYPE_COLLECT) {
        loginResult = await CollectUserApi.login({
          mobile,
          password,
        })
      } else if (loginType == LOGIN_TYPE_COLLECT_ADMIN) {
        loginResult = await CollectUserApi.loginAdmin({
          account: mobile,
          password,
        })
      } else
        throw 'login type error';
      this.loginMp = false;
      this.loginResultHandle(loginResult, loginType);
    },
    async loginResultHandle(loginResult: LoginResult, loginType: number = -1) {
      this.token = loginResult.auth.token;
      this.userId = loginResult.mainBodyUserInfo.id;
      this.userInfo = loginResult.mainBodyUserInfo;
      this.loginType = loginType;
      this.expireAt = loginResult.auth.expiresIn + Date.now();
      this.saveLoginState();
    },
    saveLoginState() {
      this.shareLoginInfo();
      uni.setStorage({ 
        key: STORAGE_KEY, 
        data: JSON.stringify({ 
          token: this.token, 
          userId: this.userId ,
          expireAt: this.expireAt,
          userInfo: this.userInfo,
          loginType: this.loginType,
        }) 
      });
    },
    shareLoginInfo() {
      // 全局变量存储
      const app = getApp();
      if (!app.globalData) 
        app.globalData = {};
      app.globalData.token = this.token;
      app.globalData.userId = this.userId;
      app.globalData.userInfo = this.userInfo;
    },
    async logout() {
      this.token = '';
      this.userId = 0;
      this.userInfo = null;
      this.loginMp = false;
      uni.removeStorage({ key: STORAGE_KEY });
    }
  },
  getters: {
    isLoginMp(state) {
      return state.loginMp;
    },
    isLogged(state) {
      return state.token != '' && state.userId != 0
    },
    isCollect(state) {
      return state.loginType === LOGIN_TYPE_COLLECT;
    },
    isCollectAdmin(state) {
      return state.loginType === LOGIN_TYPE_COLLECT_ADMIN;
    },
    isCollectReviewer(state) {
      return state.userInfo?.isReviewer ?? false;
    },  
  },
})