import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { ChatMessage } from '@/api/chat'
import { getChatHistory } from '@/api/chat'
import { useUserStore } from '@/store/user'
import { ElMessage } from 'element-plus'

export const useChatStore = defineStore(
    'chat',
    () => {
        const messages = ref<ChatMessage[]>([])
        const isHistoryLoaded = ref(false)
        const conversationId = ref('')  // Dify 会话 ID，用于上下文记忆

        // 清除消息
        const clearMessages = () => {
            messages.value = []
            isHistoryLoaded.value = false
            conversationId.value = ''
        }

        const setConversationId = (id: string) => {
            conversationId.value = id
        }

        // 重置会话（开始新对话）
        const resetConversation = () => {
            messages.value = []
            conversationId.value = ''
        }

        // 从接口拉取最新历史（合并到本地）
        const loadHistory = async () => {
            const userStore = useUserStore()
            if (!userStore.isLoggedIn) return

            try {
                const res: any = await getChatHistory(50)
                // request 拦截器已剥离 {code, data, message} 外壳，res 直接是 data
                const items = Array.isArray(res) ? res : (res?.data || [])
                messages.value = items
                isHistoryLoaded.value = true
            } catch (e) {
                console.error('Failed to load chat history:', e)
            }
        }

        // 追加单条消息
        const appendMessage = (msg: ChatMessage) => {
            messages.value.push(msg)
        }

        // 追加文本到已有消息
        const appendTextToMessage = (id: string, text: string) => {
            const msg = messages.value.find(m => m.id === id)
            if (msg && msg.type === 'text') {
                msg.content = (msg.content || '') + text
            }
        }

        return {
            messages,
            isHistoryLoaded,
            conversationId,
            clearMessages,
            loadHistory,
            appendMessage,
            appendTextToMessage,
            setConversationId,
            resetConversation,
        }
    },
    {
        persist: {
            key: 'crm-chat-history',
            storage: localStorage,
        }
    }
)
