import { login } from "@/api/path/login.api";

import { imLogin } from "@/api/path/im.api";
import { userInfo } from "@/api/path/jdfh.api";
import { useWalletStore } from "@/stores/modules/walletStore";
import { useSystemStore } from "@/stores/modules/systemStore";
import { useWebSocketStore } from "@/stores/modules/webSocketStore.js";

const imgHost = import.meta.env.VITE_IM_PATH_FIlE



export async function sysLogin(address) {
  const walletStore = useWalletStore();
  const systemStore = useSystemStore();
  const wsStore = useWebSocketStore();
  wsStore.deleteData();

  systemStore.ImsessionList = [];
  const results = await Promise.allSettled([
    login({ wallet_address: address }),
    imLogin({ uuid: address }),
  ]);
  const loginResult = results[0].value;
  const imLoginResult = results[1].value;

  systemStore.token = loginResult.data.access_token;
  systemStore.USERID = loginResult.data.user_id;

  walletStore.avatar = imgHost + imLoginResult.data.avatar;
  walletStore.username = imLoginResult.data.nickname;
 
  // 节点分红---获取用户是否为管理员以及是否加入了白名单
  const res = await userInfo({ address });
  if (res.ret) {
    const { is_super, is_white, is_exclusive } = res.data;
    const data = {
      is_super: typeof is_super === "boolean" ? is_super : false,
      is_white: typeof is_white === "boolean" ? is_white : false,
      is_exclusive: is_exclusive || false,
    };

    systemStore.Administrator = data;
 
  }
}

// 更新用户信息
export async function updateUserInfo(address,id) {
  const walletStore = useWalletStore();
 

  const res = await imLogin({ uuid: address });
  walletStore.avatar = imgHost + res.data.avatar;
  walletStore.username = res.data.nickname;
  const index = walletStore.walletList.findIndex(item => item.id === id);
  if (index !== -1) {
    walletStore.walletList[index].username = res.data.nickname;
    walletStore.walletList[index].avatar = imgHost + res.data.avatar;
  }
}
