import { defineStore } from 'pinia';
import { LoginFormData } from '@/types/api/system/login';
import { UserState } from '@/types/store/user';

import { localStorage } from '@/utils/storage';
import { extractTokenFromApiBody, removeAccessToken, setAccessToken } from '@/utils/auth-token';
import { login, signIn, signInGoogle } from '@/api/login';
import { resetRouter } from '@/router';

function applyAdminToState(self: any, admin: any, permissions: any) {
  localStorage.set('user', admin.username);
  localStorage.set('userInfo', admin);
  localStorage.set('leftSidebarList', permissions);
  self.username = admin.username;
  self.enable = admin.enable;
  self.roleId = admin.roleId;
  self.realName = admin.realName;
  self.mobilePhone = admin.mobilePhone;
  self.qq = admin.qq;
  self.email = admin.email;
  self.avatar = admin.avatar;
  self.status = admin.status;
  self.roleName = admin.roleName;
}

const useUserStore = defineStore({
  id: 'user',
  state: (): UserState => ({
    username: localStorage.get('user') || '',
    enable: 0,
    roleId: 0,
    realName: '',
    mobilePhone: '',
    qq: '',
    email: '',
    avatar: '',
    status: 0,
    roleName: '',
    roles: [],
    perms: []
  }),
  actions: {
    async RESET_STATE() {
      this.$reset();
    },
    /**
     * 登录
     */
     login(loginData: LoginFormData) {
      const { username, password, captcha } = loginData;
      return new Promise((resolve, reject) => {
        login({
          username: username.trim(),
          password: password,
          captcha: captcha
        })
        .then((response) => {
          const { phone, googleState, tempToken } = response.data as any;
          localStorage.set('userPhone', phone);
          localStorage.set('tempToken', tempToken);
          resolve({ phone, googleState, tempToken })
        })
        .catch((error) => {
          reject(error);
        });
      })
    },
    signIn(tempToken: string) {
      return new Promise((resolve, reject) => {
        signIn(tempToken)
        .then((response) => {
          const { admin, permissions } = (response as any).data;
          const token = extractTokenFromApiBody(response);
          if (token) {
            setAccessToken(token);
          }
          applyAdminToState(this, admin, permissions);
          resolve(response)
        })
        .catch((error) => {
          reject(error);
        })
      })
    },
    signInWithGoogle(tempToken: string, googleCode: string) {
      return new Promise((resolve, reject) => {
        signInGoogle(tempToken, googleCode)
        .then((response) => {
          const { admin, permissions } = (response as any).data;
          const token = extractTokenFromApiBody(response);
          if (token) {
            setAccessToken(token);
          }
          applyAdminToState(this, admin, permissions);
          resolve(response)
        })
        .catch((error) => {
          reject(error);
        })
      })
    },
    /**
     *  获取用户信息（昵称、头像、角色集合、权限集合）
     */
    getUserInfo() {
      return new Promise((resolve, reject) => {
          this.roles = ['ROOT'];
          this.perms = [];
          resolve(null);
      }).catch(err => console.log(err));
    },
    /**
     * 注销
     */
    logout() {
      return new Promise((resolve, reject) => {
        localStorage.remove('userPhone');
        localStorage.remove('tempToken');
        localStorage.remove('user');
        localStorage.remove('userInfo');
        localStorage.remove("leftSidebarList");
        removeAccessToken();

        this.RESET_STATE();
        resetRouter();

        resolve(null);
      }).catch(err => console.log(err))
    },

    /**
     * 清除 Token
     */
    resetToken() {
      return new Promise((resolve) => {
        localStorage.remove('userPhone');
        localStorage.remove('tempToken');
        removeAccessToken();
        this.RESET_STATE();
        resolve(null);
      });
    },
  },
});

export default useUserStore;
