import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Message } from '@/api/notice'
import { getMessageList, markMessageRead, markAllMessageRead, getUnreadMessageCount } from '@/api/notice'
import * as websocket from '@/utils/websocket'
import type { SocketMessage } from '@/utils/websocket'

export const useNotificationStore = defineStore('notification', () => {
  // State
  const messages = ref<Message[]>([])
  const unreadCount = ref(0)
  const loading = ref(false)
  const connected = ref(false)

  // Getters
  const taskUnreadCount = computed(() => messages.value.filter(m => (m.messageType || m.type) === 'task' && (m.isRead === 0 || m.readStatus === 0)).length)

  // Actions
  async function loadMessages(pageNum = 1, pageSize = 50) {
    loading.value = true
    try {
      const res = await getMessageList(pageNum, pageSize)
      messages.value = res.rows || []
    } catch (error) {
      console.error('加载消息列表失败', error)
      messages.value = []
    } finally {
      loading.value = false
    }
  }

  async function fetchUnreadCount() {
    try {
      const count = await getUnreadMessageCount()
      unreadCount.value = count || 0
    } catch (error) {
      console.error('加载未读消息数失败', error)
      unreadCount.value = 0
    }
  }

  async function markAsRead(messageId?: number) {
    if (!messageId) return
    try {
      await markMessageRead(messageId)
      const msg = messages.value.find(m => m.messageId === messageId)
      if (msg) {
        msg.isRead = 1
        msg.readStatus = 1
      }
      await fetchUnreadCount()
    } catch (error) {
      console.error('标记已读失败', error)
    }
  }

  async function markAllAsRead() {
    try {
      await markAllMessageRead()
      messages.value.forEach(m => {
        m.isRead = 1
        m.readStatus = 1
      })
      unreadCount.value = 0
    } catch (error) {
      console.error('全部已读失败', error)
    }
  }

  function prependMessage(msg: Message) {
    messages.value.unshift(msg)
    unreadCount.value++
  }

  function handleSocketMessage(data: SocketMessage) {
    const msg: Message = {
      messageId: data.businessId ? Number(data.businessId) : undefined,
      title: data.title || '新消息',
      content: data.content || '',
      messageType: data.type || 'task',
      type: data.type || 'task',
      senderId: data.senderId,
      senderName: data.senderName,
      isRead: 0,
      readStatus: 0,
      createTime: data.sendTime || new Date().toISOString(),
      extraData: data.extra ? JSON.stringify(data.extra) : (data.businessId ? String(data.businessId) : undefined),
    }
    prependMessage(msg)
  }

  function connectSocket(token: string) {
    if (!token) return
    websocket.close()
    websocket.connect(token)
    websocket.onMessage((data) => {
      handleSocketMessage(data)
    })
    connected.value = true
  }

  function disconnectSocket() {
    websocket.close()
    connected.value = false
  }

  function ensureConnected(token: string) {
    if (!websocket.isConnected() && token) {
      connectSocket(token)
    }
  }

  return {
    messages,
    unreadCount,
    loading,
    connected,
    taskUnreadCount,
    loadMessages,
    fetchUnreadCount,
    markAsRead,
    markAllAsRead,
    connectSocket,
    disconnectSocket,
    ensureConnected,
    prependMessage,
  }
})
