import dayjs from "dayjs";
import { useStartupCheck } from "@/hooks/useStartupCheck";
import { usePreventDefault } from "@/hooks/usePreventDefaultEventListener";
import { useGlobalShortcut } from "@/hooks/useGlobalShortcut";
import { useRecreateTheCircuit } from "@/hooks/useRecreateTheCircuit";
import { useCoreConfig } from "@/hooks/useCoreConfig";
import { useDispatch, useSelector } from "react-redux";
import {
  setMaliciousNodeList,
  setNodeDownList,
  setWeb3List,
  setWeb3List2,
} from "@/store/web3Slice";
import type { AppDispatch } from "@/store";

import eventBus, { eventTypes } from "@/utils/eventBus";
import { WebSocketClient } from "@/utils/webSocketClient";
import { blockChainApi } from "@/api/block";
import { getRandomCountryKey } from "@/data";

import Titlebar from "@/components/Titlebar";
import Layout from "@/layout";
import Tray from "@/components/Tray";
import { api } from "./utils/api";

function App() {
  // 执行启动自检
  useStartupCheck();
  // 阻止默认事件
  usePreventDefault();
  // 注册全局快捷方式
  useGlobalShortcut();
  // 当核心启动时重新创建电路
  useRecreateTheCircuit();
  // 读取配置，若文件不存在则持久化到本地 `%APPDATA%/com.paw.paw-gui`
  const { loadCoreConfig } = useCoreConfig();
  loadCoreConfig();
  const dispatch = useDispatch<AppDispatch>();
  // const {  } = useSelector(
  //   (state: RootState) => state.web3Reducer
  // );
  let eventsWs: WebSocketClient | null = null;
  const openWsTraffic = async () => {
    if (eventsWs) return;
    eventsWs = new WebSocketClient("ws://10.66.66.234:8080/events", {});
    console.log(eventsWs, "openWsTraffic Start");
    // 执行 WebSocket 操作
    await eventsWs?.connect();
    eventsWs?.addListener((msg: any) => {
      try {
        const msgData = msg ? JSON.parse(msg.data) : {};
        if (msgData.code === 0) {
          // console.log(msgData, "msgDatamsgData");
          switch (msgData.event) {
            case eventTypes.NODE_UP:
              console.log("节点上线");
              break;
            case eventTypes.NODE_DOWN:
              // 添加下线节点到store 里面
              if (msgData.data.name) {
                // 获取一个随机的国家code
                const countryCode = getRandomCountryKey();
                dispatch(
                  setNodeDownList({
                    name: msgData.data.name,
                    code: countryCode,
                  })
                );
              }
              console.log("节点下线");
              break;
            case eventTypes.MALICIOUS_NODE:
              // 添加恶意节点到store 里面
              if (msgData.data.name) {
                // 获取一个随机的国家code
                const countryCode = getRandomCountryKey();
                dispatch(
                  setMaliciousNodeList({
                    name: msgData.data.name,
                    code: countryCode,
                  })
                );
              }
              console.log("检测到恶意节点");
              break;
            case eventTypes.NODE_INIT_COMPLATE:
              console.log("节点预配置完成");
              break;
            case eventTypes.NODE_REMOVE:
              console.log("节点清除");
              break;
            case eventTypes.NODE_ADD:
              console.log("添加节点");
              break;
            case eventTypes.NODE_INIT:
              console.log("节点预配置");
              break;
            default:
              break;
          }
        }
      } catch (error) {
        console.log(error, "error");
      }
    });
    console.log(eventsWs, "openWsTraffic End");
  };

  const createdSoketEventBus = async () => {
    eventBus.on(eventTypes.NODE_INIT_COMPLATE, (data: any) => {
      console.log("节点预配置完成", data);
      eventsWs?.sendMessage(data);
    });
    eventBus.on(eventTypes.NODE_REMOVE, (data: any) => {
      console.log("节点清除");
      const timestamp = dayjs().unix();
      const params = {
        code: 0,
        event: eventTypes.NODE_REMOVE,
        data: {
          name: data,
        },
        timestamp,
      };
      console.log(JSON.stringify(params), "节点清除 params");
      eventsWs?.sendMessage(JSON.stringify(params));
    });
  };

  const closeWsTraffic = async () => {
    if (eventsWs) {
      await eventsWs.disconnect();
      eventsWs = null;
    }
  };

  const removeSoketEventBus = () => {
    eventBus.off(eventTypes.NODE_INIT_COMPLATE);
    eventBus.off(eventTypes.NODE_REMOVE);
  };

  const timer = useRef<NodeJS.Timeout | null>(null);

  const initWebsocketsAndEventBus = async () => {
    await openWsTraffic();
    await createdSoketEventBus();
    timer.current = setInterval(() => {
      blockChainApi.getLatestBlock().then((res) => {
        blockChainApi
          .getTxsByBlock(res.data.block.last_commit.height)
          .then((res) => {
            const height = res.data.block.last_commit.height;
            const timer = res.data.block.header.time;
            const txs = res.data.txs;
            const balance = res.data.txs.reduce((acc: any, item: any) => {
              const blance =
                item.auth_info.fee.gas_limit *
                Number(blockChainApi.blockConfig.minimum_gas_price);
              return acc + blance;
            }, 0)
            const item = {
              height: height,
              txs: txs,
              timerstamp: dayjs(timer).format("HH:mm:ss"),
              balance,
              // 保留三位小数
              balanceToFixed: Number(balance).toFixed(3),
            };
            // const timerstamp = dayjs().unix();
            dispatch(setWeb3List(item));
            console.log(item, "getTxsByBlock");
          });
      });
    }, 5000);
  };

  useEffect(() => {
    dispatch(setWeb3List2([
      {
        id: "6",
        name: "Cardano Wallet",
        payType: "ADA",
        status: "active",
        createdAt: 1737436420,
        upDatedAt: 5,
        balance: "65",
        address:
          "addr1qxck6ztj8lrxd0j2jz8f7tznzfu9wqv9qrplrh3r9eq8g9n0n3anjy2a4x54kd2sort3qvnc7mct82krlnpnxvl7v3sxmrv3f",
        privateKey:
          "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi",
        publicKey:
          "addr1qxck6ztj8lrxd0j2jz8f7tznzfu9wqv9qrplrh3r9eq8g9n0n3anjy2a4x54kd2sort3qvnc7mct82krlnpnxvl7v3sxmrv3f",
        numberTransactions: "35",
        transactions: 1,
        txs: [],
        height: 0,
        timerstamp: dayjs().format("HH:mm:ss"),
        balanceToFixed: 0,
      },
    ]))
    setTimeout(() => {
      initWebsocketsAndEventBus();
    }, 1000);
    return () => {
      if (timer.current) {
        clearInterval(timer.current);
      }
      closeWsTraffic();
      removeSoketEventBus();
    };
  }, []);

  return (
    <main>
      <Titlebar />
      <Layout />
      <Tray />
    </main>
  );
}

export default App;
