import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { customStorage } from '../persist'

/**
 * 消息类型枚举
 */
export const MessageType = {
	NOTIFICATION: 'notification', // 系统通知
	TASK: 'task', // 任务提醒
	WARNING: 'warning', // 警告
	ERROR: 'error', // 错误
	SUCCESS: 'success', // 成功
	INFO: 'info', // 信息
}

/**
 * 消息优先级枚举
 */
export const MessagePriority = {
	LOW: 'low',
	MEDIUM: 'medium',
	HIGH: 'high',
	URGENT: 'urgent',
}

export const useMessageStore = defineStore(
	'message',
	() => {
		// 消息列表
		const messages = ref([])

		// 最大消息数量
		const maxMessages = 100

		// 获取未读消息数量
		const unreadCount = computed(() => {
			return messages.value.filter((m) => !m.read).length
		})

		// 获取所有消息数量
		const totalCount = computed(() => {
			return messages.value.length
		})

		// 根据类型获取消息数量
		const getCountByType = (type) => {
			return messages.value.filter((m) => m.type === type).length
		}

		// 添加消息
		function addMessage(message) {
			const newMessage = {
				id: Date.now() + Math.random(),
				type: MessageType.NOTIFICATION,
				priority: MessagePriority.MEDIUM,
				title: '',
				content: '',
				read: false,
				timestamp: Date.now(),
				...message,
			}

			// 添加到列表开头
			messages.value.unshift(newMessage)

			// 限制消息数量
			if (messages.value.length > maxMessages) {
				messages.value = messages.value.slice(0, maxMessages)
			}

			// 持久化到 localStorage
			persistMessages()

			return newMessage
		}

		// 批量添加消息
		function addMessages(newMessages) {
			newMessages.forEach((msg) => addMessage(msg))
		}

		// 标记消息为已读
		function markAsRead(messageId) {
			const message = messages.value.find((m) => m.id === messageId)
			if (message) {
				message.read = true
				persistMessages()
			}
		}

		// 标记所有消息为已读
		function markAllAsRead() {
			messages.value.forEach((m) => {
				m.read = true
			})
			persistMessages()
		}

		// 删除消息
		function removeMessage(messageId) {
			const index = messages.value.findIndex((m) => m.id === messageId)
			if (index !== -1) {
				messages.value.splice(index, 1)
				persistMessages()
			}
		}

		// 清空所有消息
		function clearAll() {
			messages.value = []
			persistMessages()
		}

		// 清空已读消息
		function clearRead() {
			messages.value = messages.value.filter((m) => !m.read)
			persistMessages()
		}

		// 根据类型清空消息
		function clearByType(type) {
			messages.value = messages.value.filter((m) => m.type !== type)
			persistMessages()
		}

		// 格式化消息时间
		function formatMessageTime(timestamp) {
			const now = Date.now()
			const diff = now - timestamp

			const minute = 60 * 1000
			const hour = 60 * minute
			const day = 24 * hour

			if (diff < minute) {
				return '刚刚'
			} else if (diff < hour) {
				return `${Math.floor(diff / minute)}分钟前`
			} else if (diff < day) {
				return `${Math.floor(diff / hour)}小时前`
			} else if (diff < 7 * day) {
				return `${Math.floor(diff / day)}天前`
			} else {
				const date = new Date(timestamp)
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
			}
		}

		// 持久化消息到 localStorage
		function persistMessages() {
			try {
				localStorage.setItem('message-store', JSON.stringify(messages.value))
			} catch (error) {
				console.error('持久化消息失败:', error)
			}
		}

		// 从 localStorage 恢复消息
		function restoreMessages() {
			try {
				const stored = localStorage.getItem('message-store')
				if (stored) {
					messages.value = JSON.parse(stored)
				}
			} catch (error) {
				console.error('恢复消息失败:', error)
				messages.value = []
			}
		}

		// 处理 WebSocket 消息
		function handleWebSocketMessage(data) {
			const { type, title, message, content, ...extra } = data

			addMessage({
				type: type || MessageType.NOTIFICATION,
				title: title || '系统通知',
				content: message || content || '',
				...extra,
			})
		}

		// 处理数据更新消息
		function handleDataUpdate(data) {
			const { resource_type, action } = data

			let title = '数据更新'
			let content = ''

			switch (action) {
				case 'create':
					title = '新建成功'
					content = `新的${resource_type}已创建`
					break
				case 'update':
					title = '更新成功'
					content = `${resource_type}数据已更新`
					break
				case 'delete':
					title = '删除成功'
					content = `${resource_type}数据已删除`
					break
				default:
					content = `${resource_type}数据已${action}`
			}

			addMessage({
				type: MessageType.SUCCESS,
				title,
				content,
			})
		}

		// 获取消息列表（带分页）
		function getMessages(options = {}) {
			const { page = 1, pageSize = 20, type = null, read = null } = options

			let filtered = [...messages.value]

			// 按类型过滤
			if (type) {
				filtered = filtered.filter((m) => m.type === type)
			}

			// 按已读状态过滤
			if (read !== null) {
				filtered = filtered.filter((m) => m.read === read)
			}

			// 分页
			const start = (page - 1) * pageSize
			const end = start + pageSize
			const list = filtered.slice(start, end)
			const total = filtered.length

			return {
				list,
				total,
				page,
				pageSize,
				totalPages: Math.ceil(total / pageSize),
			}
		}

		return {
			messages,
			unreadCount,
			totalCount,
			MessageType,
			MessagePriority,
			addMessage,
			addMessages,
			markAsRead,
			markAllAsRead,
			removeMessage,
			clearAll,
			clearRead,
			clearByType,
			formatMessageTime,
			handleWebSocketMessage,
			handleDataUpdate,
			getMessages,
			getCountByType,
			restoreMessages,
		}
	},
	{
		persist: {
			key: 'message-store',
			storage: customStorage,
			pick: [], // 不自动持久化，使用自定义 persistMessages 方法
		},
	},
)
