<script setup lang="ts">
import { RouterView } from "vue-router";
import { onMounted } from "vue";
import http from "@/api/http";
import { useLoadingStore } from "@/stores/loadingStore";
import {
  configData,
  loginSuccess,
  redirectToExternal,
  headHtml,
  loadHtml,
  headerHtml,
  footerHtml,
} from "@/utils/common";
import { generateECDHKeyPair, deriveSessionKey } from "@/utils/socketio";
import LoadingView from "@/views/LoadingView.vue";

const loadingStore = useLoadingStore();

onMounted(() => {
  login();
});

const login = async function () {
  headerHtml.value = await loadHtml("/Static_zy/header.html");
  loadingStore.setLoading(true);

  const { keyPair, clientPublicKeyB64 } = await generateECDHKeyPair();

  http.post("/api", { clientPublicKey: clientPublicKeyB64 }).then(async (data) => {
    if (data.data.isBlock) {
      redirectToExternal();
      return;
    }
    if (data.data.isFirst) {
      localStorage.removeItem("route")
    }
    let token = data.data.Token;
    if (data.data.mode) {
      localStorage.setItem("mode", data.data.mode);
    }

    // 如果服务端返回了公钥，完成 ECDH 推导会话密钥（兼容大小写两种字段名）
    const serverPubKey = data.data.ServerPublicKey || data.data.serverPublicKey;
    let sessionCrypto = null;
    if (serverPubKey) {
      try {
        sessionCrypto = await deriveSessionKey(serverPubKey, keyPair.privateKey);
      } catch (e) {
        
      }
    }
    loginSuccess(token, data.data.mode, sessionCrypto);

    if (data.data.custom) {
      configData.value = JSON.parse(data.data.custom);
    }
  });
  footerHtml.value = await loadHtml("/Static_zy/footer.html");

};
</script>

<template>
  <div v-html="headHtml"></div>
  <LoadingView />
  <RouterView />
</template>

<style scoped></style>
