import { defineStore } from 'pinia';

import { getToken, setToken, removeToken } from '@/utils/auth';
import { loginApi, logoutApi } from '@/api/auth';
import { getUserInfo } from '@/api/user';
import { resetRouter } from '@/router';
import { store } from '@/store';
import { LoginData } from '@/api/auth/types';
import { ref } from 'vue';
import { UserInfo } from '@/api/user/types';

export const useUserStore = defineStore('user', () => {
  // state
  const Token = ref<string>(getToken() || '');
  const nickname = ref<string>('');
  const avatar = ref<string>('');
  const roles = ref<Array<string>>([]); // 用户角色编码集合 → 判断路由权限
  const perms = ref<Array<string>>([]); // 用户权限编码集合 → 判断按钮权限
  const badgeval = ref('')
  const webApiBaseUrl: any = process.env.NODE_ENV == 'development' ? import.meta.env.VITE_APP_BASE_API : window.webConfig.webApiBaseUrl
  const WebSocketUrl:any = window.webConfig.WebSocketUrl
  const webApiBaseHttp: any = process.env.NODE_ENV == 'development' ? import.meta.env.VITE_APP_BASE_WEB : window.webConfig.VITEAPPBASEWEB
  const mapUrl: any =  window.webConfig.mapUrl
  const webApiBaseApp: any = window.webConfig.webApiBaseApp
  const title = window.webConfig.title
  const content1 = window.webConfig.content1
  const content2 = window.webConfig.content2
  const content3 = window.webConfig.content3
  const bgImg = window.webConfig.bgImg
  const logo = window.webConfig.loginLogo
  const headerLogo = window.webConfig.headerLogo
  const userId = ref('')
  const institutionName = ref('')
  const institutionId = ref('')

  
  
  // actions

  // 登录
  function login(loginData: LoginData) {
    return new Promise<void>((resolve, reject) => {
      loginApi(loginData)
        .then(response => {
          const { token } = response.data;
          Token.value = token;
          setToken(token);
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      getUserInfo()
        .then(({ data }) => {
          if (!data) {
            return reject('Verification failed, please Login again.');
          }
          if (!data.roles || data.roles.length <= 0) {
            reject('getUserInfo: roles must be a non-null array!');
          }
          nickname.value = data.userInfo.nickname;
          userId.value = data.userInfo.id;
          avatar.value = data.userInfo.avatar;
          roles.value = data.roles;
          perms.value = data.permissions;
          institutionName.value =  data.userInfo.institutionName;
          if(data.userInfo.institution_id !=null&& data.userInfo.institution_id !=''){
            institutionId.value  =  data.userInfo.institution_id
          }
          resolve(data);
        })
        .catch(error => {
          reject(error);
        });
    });
  }

  // 注销
  function logout() {
    return new Promise<void>((resolve, reject) => {
      logoutApi()
        .then(() => {
          resetRouter();
          resetToken();
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  }

  // 重置
  function resetToken() {
    removeToken();
    Token.value = '';
    nickname.value = '';
    avatar.value = '';
    roles.value = [];
    perms.value = [];
  }
  return {
    Token,
    nickname,
    userId,
    avatar,
    roles,
    perms,
    login,
    getInfo,
    logout,
    resetToken,
    badgeval,
    webApiBaseUrl,
    WebSocketUrl,
    mapUrl,
    webApiBaseHttp,
    webApiBaseApp,
    title,
    institutionName,
    institutionId,
    content1,
    content2,
    content3,
    bgImg,
    logo,
    headerLogo
  };
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
