import type { ChatSessionVo, CreateSessionDTO, GetSessionListParams } from '@/api/session/types';
import { SessionTypeEnum } from '@/api/session/types';
import { Monitor } from '@element-plus/icons-vue';
import { defineStore } from 'pinia';
import { markRaw, ref } from 'vue';
import {
  create_session,
  delete_session,
  get_session,
  get_session_list,
  update_session,
} from '@/api';
import { useUserStore } from './user';

export const useAgentSessionStore = defineStore('agentSession', () => {
  const userStore = useUserStore();

  // 当前选中的会话信息
  const currentSession = ref<ChatSessionVo | null>(null);

  // 设置当前会话
  const setCurrentSession = (session: ChatSessionVo | null) => {
    currentSession.value = session;
  };

  // 会话列表核心状态
  const sessionList = ref<ChatSessionVo[]>([]);
  const currentPage = ref(1);
  const pageSize = ref(25);
  const hasMore = ref(true);
  const isLoading = ref(false);
  const isLoadingMore = ref(false);

  // 获取会话列表
  const requestSessionList = async (page: number = currentPage.value, force: boolean = false) => {
    if (!userStore.token) {
      sessionList.value = [];
      return;
    }

    if (!force && ((page > 1 && !hasMore.value) || isLoading.value || isLoadingMore.value))
      return;

    isLoading.value = page === 1;
    isLoadingMore.value = page > 1;

    try {
      const params: GetSessionListParams = {
        userId: userStore.userInfo?.userId as number,
        skipCount: page,
        maxResultCount: pageSize.value,
        isAsc: 'desc',
        orderByColumn: 'createTime',
        sessionType: SessionTypeEnum.Agent, // 只查询Agent类型
      };

      const resArr = await get_session_list(params);
      const res = processSessions(resArr.data.items);

      const allSessions = new Map(sessionList.value.map(item => [item.id, item]));
      res.forEach(item => allSessions.set(item.id, { ...item }));

      if (page === 1) {
        sessionList.value = [
          ...res,
          ...Array.from(allSessions.values()).filter(item => !res.some(r => r.id === item.id)),
        ];
      }
      else {
        sessionList.value = [
          ...sessionList.value.filter(item => !res.some(r => r.id === item.id)),
          ...res,
        ];
      }

      if (!force)
        hasMore.value = (res?.length || 0) === pageSize.value;
      if (!force)
        currentPage.value = page;
    }
    catch (error) {
      console.error('requestSessionList错误:', error);
    }
    finally {
      isLoading.value = false;
      isLoadingMore.value = false;
    }
  };

  // 创建新会话
  const createSession = async (data: Omit<CreateSessionDTO, 'id' | 'sessionType'>) => {
    if (!userStore.token) {
      return null;
    }

    try {
      const res = await create_session({
        ...data,
        sessionType: SessionTypeEnum.Agent,
      });

      await requestSessionList(1, true);

      const newSessionRes = await get_session(`${res.data.id}`);
      setCurrentSession(newSessionRes.data);

      return newSessionRes.data;
    }
    catch (error) {
      console.error('createSession错误:', error);
      return null;
    }
  };

  // 加载更多会话
  const loadMoreSessions = async () => {
    if (hasMore.value)
      await requestSessionList(currentPage.value + 1);
  };

  // 更新会话
  const updateSession = async (item: ChatSessionVo) => {
    try {
      await update_session(item);
      const targetIndex = sessionList.value.findIndex(session => session.id === item.id);
      const targetPage = targetIndex >= 0
        ? Math.floor(targetIndex / pageSize.value) + 1
        : 1;
      await requestSessionList(targetPage, true);
    }
    catch (error) {
      console.error('updateSession错误:', error);
    }
  };

  // 删除会话
  const deleteSession = async (ids: string[]) => {
    try {
      await delete_session(ids);
      const targetIndex = sessionList.value.findIndex(session => session.id === ids[0]);
      const targetPage = targetIndex >= 0
        ? Math.floor(targetIndex / pageSize.value) + 1
        : 1;
      await requestSessionList(targetPage, true);

      // 如果删除的是当前会话，清空当前会话
      if (currentSession.value && ids.includes(currentSession.value.id!)) {
        setCurrentSession(null);
      }
    }
    catch (error) {
      console.error('deleteSession错误:', error);
    }
  };

  // 预处理会话
  function processSessions(sessions: ChatSessionVo[]) {
    const currentDate = new Date();

    return sessions.map((session) => {
      const createDate = new Date(session.creationTime!);
      const diffDays = Math.floor(
        (currentDate.getTime() - createDate.getTime()) / (1000 * 60 * 60 * 24),
      );

      let group: string;
      if (diffDays < 7) {
        group = '7 天内';
      }
      else if (diffDays < 30) {
        group = '30 天内';
      }
      else {
        const year = createDate.getFullYear();
        const month = String(createDate.getMonth() + 1).padStart(2, '0');
        group = `${year}-${month}`;
      }

      return {
        ...session,
        group,
        prefixIcon: markRaw(Monitor),
      };
    });
  }

  return {
    currentSession,
    setCurrentSession,
    sessionList,
    currentPage,
    pageSize,
    hasMore,
    isLoading,
    isLoadingMore,
    createSession,
    requestSessionList,
    loadMoreSessions,
    updateSession,
    deleteSession,
  };
});
