import { useRef, useEffect } from "react";
import { useModel } from "umi";
import Header from "./components/Header";
import ToolBar from "./components/Toolbar";
import { useEvent } from "./useEvent";
import Libary from "./components/Libary";
import { useParams } from "umi";
import { GetWorkFlow } from "@/api/node";
import { useRequest, useSearchParams } from "umi";
import { Spin } from "antd";

import ConfigModal from "./modals";
import LineModal from "./modals/lineModal";

export default function index() {
  const ref = useRef<HTMLDivElement>(null);
  const { init, graph, loadWorkflow } = useModel("flowModel");
  const [searchParams] = useSearchParams();
  const mode = searchParams.get("mode") || "edit"; // edit ops
  const params = useParams();

  const { run, loading } = useRequest(GetWorkFlow, {
    manual: true,
    onSuccess: (res) => {
      console.log("流程详情:", res);
      if (res?.result) {
        loadWorkflow(res.result);
      }
    },
  });

  useEvent(graph);

  useEffect(() => {
    if (!ref.current) return;
    init(ref.current, mode as any);
    if (params?.id) {
      run({
        id: params.id,
      });
      sessionStorage.setItem("workflowId", params.id);
    }
  }, []);

  return (
    <Spin spinning={loading}>
      <div className="w-100vw h-100vh flex flex-col overflow-hidden">
        <div className="w-full h-60px bg-#ffffff border-b border-#eaeaea border-b-solid box-shadow-sm">
          <Header />
        </div>
        <div className="flex-1 relative" style={{ height: "calc(100% - 60px)" }}>
          <div className="w-full h-full" ref={ref} />
          <Libary />
          <ToolBar />
        </div>
        <ConfigModal />
        <LineModal />
      </div>
    </Spin>
  );
}
