import { defineStore } from "pinia";
import { ref, computed } from "vue";
import {
  SseClient,
  type ProjectInitTaskVO,
  type RiskAssessTaskVO
} from "@/utils/sse/SseClient";
import { store } from "../utils";
import {
  getMyTasks as fetchTasksApi,
  type ProjectInitTaskVO as ApiTaskVO
} from "@/api/project";
import { ElNotification } from "element-plus";

export const useSseStore = defineStore("sse", () => {
  // State
  const sseClient = ref<SseClient | null>(null);
  const isConnected = ref(false);
  const currentTask = ref<ProjectInitTaskVO | null>(null);
  const taskProgress = ref(0);
  const taskStatus = ref<
    "idle" | "submitted" | "processing" | "completed" | "error"
  >("idle");
  const errorMessage = ref("");
  // 我的任务列表
  const myTasks = ref<ApiTaskVO[]>([]);
  // 是否有待处理的任务
  const hasProcessingTask = computed(() =>
    myTasks.value.some(t => t.status === "processing" || t.status === "pending")
  );

  // 风险评估任务状态
  const riskAssessTask = ref<RiskAssessTaskVO | null>(null);
  const riskAssessProgress = ref(0);
  const riskAssessStatus = ref<
    "idle" | "submitted" | "processing" | "completed" | "error"
  >("idle");
  const riskAssessErrorMessage = ref("");

  // Getters
  const getIsConnected = computed(() => isConnected.value);
  const getCurrentTask = computed(() => currentTask.value);
  const getTaskProgress = computed(() => taskProgress.value);
  const getTaskStatus = computed(() => taskStatus.value);
  const getMyTasks = computed(() => myTasks.value);
  const getHasProcessingTask = computed(() => hasProcessingTask.value);

  // Actions
  /**
   * 初始化 SSE 连接
   * @param userId 用户ID
   */
  async function initSse(userId: string) {
    // 如果已有连接，先关闭
    if (sseClient.value) {
      sseClient.value.close();
    }

    sseClient.value = new SseClient(userId);

    // 监听连接成功
    sseClient.value.on("connected", () => {
      isConnected.value = true;
      console.log("SSE Store: 连接成功");
    });

    // 监听项目初始化进度
    sseClient.value.on("project-init-progress", (data: ProjectInitTaskVO) => {
      currentTask.value = data;
      taskProgress.value = data.progress;
      taskStatus.value = "processing";
      console.log(
        `SSE Store: 任务进度 ${data.progress}% - ${data.progressMessage}`
      );
    });

    // 监听任务完成
    sseClient.value.on("project-init-complete", (data: ProjectInitTaskVO) => {
      currentTask.value = data;
      taskProgress.value = 100;
      taskStatus.value = "completed";
      console.log("SSE Store: 任务完成", data.result);

      // 发送通知
      ElNotification({
        title: "项目解析完成",
        message: `文件 "${data.originalFilename}" 已解析完成，请前往新建项目查看预览数据。`,
        type: "success",
        duration: 5000,
        position: "top-right"
      });

      // 刷新任务列表
      fetchMyTasks();
    });

    // 监听任务提交
    sseClient.value.on(
      "project-init-submitted",
      (data: { taskId: string; message: string }) => {
        taskStatus.value = "submitted";
        console.log("SSE Store: 任务已提交", data.taskId);
      }
    );

    // 监听错误
    sseClient.value.on("project-init-error", (data: { error: string }) => {
      taskStatus.value = "error";
      errorMessage.value = data.error;
      console.error("SSE Store: 任务错误", data.error);

      // 发送错误通知
      ElNotification({
        title: "项目解析失败",
        message: data.error || "文件解析失败，请重试",
        type: "error",
        duration: 5000,
        position: "top-right"
      });

      // 刷新任务列表
      fetchMyTasks();
    });

    // 监听连接错误
    sseClient.value.on("connection-error", () => {
      isConnected.value = false;
    });

    // ============ 风险评估事件监听 ============
    // 监听风险评估任务提交
    sseClient.value.on("risk-assess-submitted", (data: any) => {
      riskAssessStatus.value = "submitted";
      console.log("SSE Store: 风险评估任务已提交", data);
    });

    // 监听风险评估进度
    sseClient.value.on("risk-assess-progress", (data: RiskAssessTaskVO) => {
      riskAssessTask.value = data;
      riskAssessProgress.value = data.progress;
      riskAssessStatus.value = "processing";
      console.log(
        `SSE Store: 风险评估进度 ${data.progress}% - ${data.progressMessage}`
      );
    });

    // 监听风险评估完成
    sseClient.value.on("risk-assess-complete", (data: RiskAssessTaskVO) => {
      riskAssessTask.value = data;
      riskAssessProgress.value = 100;
      riskAssessStatus.value = "completed";
      console.log("SSE Store: 风险评估完成，完整数据:", data);
      console.log("SSE Store: result 结构:", data.result);

      // 发送通知 - 使用更通用的消息
      ElNotification({
        title: "风险评估完成",
        message: "项目风险评估已完成，请查看风险列表。",
        type: "success",
        duration: 5000,
        position: "top-right"
      });
    });

    // 监听风险评估错误
    sseClient.value.on("risk-assess-error", (data: { error: string }) => {
      riskAssessStatus.value = "error";
      riskAssessErrorMessage.value = data.error;
      console.error("SSE Store: 风险评估错误", data.error);

      // 发送错误通知
      ElNotification({
        title: "风险评估失败",
        message: data.error || "风险评估失败，请重试",
        type: "error",
        duration: 5000,
        position: "top-right"
      });
    });

    // 建立连接（异步，在后台运行）
    sseClient.value.connect().catch(err => {
      console.error("SSE Store: 连接失败", err);
    });
  }

  /**
   * 关闭 SSE 连接
   */
  function closeSse() {
    if (sseClient.value) {
      sseClient.value.close();
      sseClient.value = null;
      isConnected.value = false;
      currentTask.value = null;
      taskProgress.value = 0;
      taskStatus.value = "idle";
      errorMessage.value = "";
    }
  }

  /**
   * 提交项目初始化任务
   */
  async function submitProjectInitTask(file: File) {
    if (!sseClient.value) {
      throw new Error("SSE 未连接");
    }
    taskStatus.value = "submitted";
    taskProgress.value = 0;
    errorMessage.value = "";
    return sseClient.value.submitProjectInitTask(file);
  }

  /**
   * 重置任务状态
   */
  function resetTaskStatus() {
    currentTask.value = null;
    taskProgress.value = 0;
    taskStatus.value = "idle";
    errorMessage.value = "";
  }

  /**
   * 重置风险评估任务状态
   */
  function resetRiskAssessStatus() {
    riskAssessTask.value = null;
    riskAssessProgress.value = 0;
    riskAssessStatus.value = "idle";
    riskAssessErrorMessage.value = "";
  }

  /**
   * 查询我的任务列表
   */
  async function fetchMyTasks() {
    try {
      const { code, data } = await fetchTasksApi();
      if (code === 200 && data) {
        myTasks.value = data;
      }
    } catch (error) {
      console.error("获取任务列表失败", error);
    }
  }

  return {
    // State
    sseClient,
    isConnected,
    currentTask,
    taskProgress,
    taskStatus,
    errorMessage,
    myTasks,
    // 风险评估状态
    riskAssessTask,
    riskAssessProgress,
    riskAssessStatus,
    riskAssessErrorMessage,
    // Getters
    getIsConnected,
    getCurrentTask,
    getTaskProgress,
    getTaskStatus,
    getMyTasks,
    getHasProcessingTask,
    // Actions
    initSse,
    closeSse,
    submitProjectInitTask,
    resetTaskStatus,
    resetRiskAssessStatus,
    fetchMyTasks
  };
});

export function useSseStoreHook() {
  return useSseStore(store);
}
