import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { customStorage } from '../persist'
import systemApi from '@/api/system'
import { message } from 'ant-design-vue'

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

/**
 * 通知分类枚举
 */
export const NotificationCategory = {
	SYSTEM: 'system', // 系统通知
	TASK: 'task', // 任务通知
	MESSAGE: 'message', // 消息通知
	REMINDER: 'reminder', // 提醒通知
	ANNOUNCEMENT: 'announcement', // 公告通知
}

/**
 * 通知操作类型枚举
 */
export const NotificationActionType = {
	NONE: 'none', // 无操作
	LINK: 'link', // 跳转链接
	MODAL: 'modal', // 打开弹窗
}

export const useNotificationStore = defineStore(
	'notification',
	() => {
		// 通知列表
		const notification = ref([])

		// 未读数量
		const unreadCount = ref(0)

		// 加载状态
		const loading = ref(false)

		// 当前页码
		const currentPage = ref(1)

		// 每页数量
		const pageSize = ref(20)

		// 总数量
		const total = ref(0)

		// 获取未读数量（计算属性）
		const unreadCountComputed = computed(() => unreadCount.value)

		// 获取已读数量
		const readCount = computed(() => total.value - unreadCount.value)

		// 获取通知列表
		async function fetchNotifications(params = {}) {
			try {
				loading.value = true
				const res = await systemApi.notification.list.get({
					page: params.page || currentPage.value,
					page_size: params.page_size || pageSize.value,
					...params,
				})

				notification.value = res.data.list || []
				total.value = res.data.total || 0
				currentPage.value = res.data.page || 1
				pageSize.value = res.data.page_size || 20

				return res.data
			} catch (error) {
				message.error(error.message || '获取通知列表失败')
				throw error
			} finally {
				loading.value = false
			}
		}

		// 获取未读通知列表
		async function fetchUnreadNotifications(params = {}) {
			try {
				loading.value = true
				const res = await systemApi.notification.unread.get({
					page: params.page || 1,
					page_size: params.page_size || 10,
					...params,
				})

				return res.data
			} catch (error) {
				message.error(error.message || '获取未读通知失败')
				throw error
			} finally {
				loading.value = false
			}
		}

		// 获取未读数量
		async function fetchUnreadCount() {
			try {
				const res = await systemApi.notification.unreadCount.get()
				// 安全访问 count 字段，处理 res.data 可能为 undefined 的情况
				const count = res?.data?.count ?? 0
				unreadCount.value = count
				return unreadCount.value
			} catch (error) {
				console.error('获取未读数量失败:', error)
				unreadCount.value = 0
				return 0
			}
		}

		// 标记为已读
		async function markAsRead(id) {
			try {
				await systemApi.notification.markAsRead.post(id)

				// 更新本地状态
				const notification = notification.value.find((n) => n.id === id)
				if (notification && !notification.is_read) {
					notification.is_read = true
					notification.read_at = new Date().toISOString()
					unreadCount.value = Math.max(0, unreadCount.value - 1)
				}

				return true
			} catch (error) {
				message.error(error.message || '标记已读失败')
				throw error
			}
		}

		// 批量标记为已读
		async function batchMarkAsRead(ids) {
			try {
				const res = await systemApi.notification.batchMarkAsRead.post({
					ids,
				})

				// 更新本地状态
				ids.forEach((id) => {
					const notification = notification.value.find((n) => n.id === id)
					if (notification && !notification.is_read) {
						notification.is_read = true
						notification.read_at = new Date().toISOString()
					}
				})

				// 更新未读数量
				unreadCount.value = Math.max(0, unreadCount.value - (res.data.count || ids.length))

				return res.data
			} catch (error) {
				message.error(error.message || '批量标记已读失败')
				throw error
			}
		}

		// 标记全部为已读
		async function markAllAsRead() {
			try {
				await systemApi.notification.markAllAsRead.post()

				// 更新本地状态
				notification.value.forEach((n) => {
					n.is_read = true
					n.read_at = n.read_at || new Date().toISOString()
				})
				unreadCount.value = 0

				return true
			} catch (error) {
				message.error(error.message || '标记全部已读失败')
				throw error
			}
		}

		// 删除通知
		async function deleteNotification(id) {
			try {
				await systemApi.notification.delete.delete(id)

				// 更新本地状态
				const index = notification.value.findIndex((n) => n.id === id)
				if (index !== -1) {
					const notification = notification.value[index]
					if (!notification.is_read) {
						unreadCount.value = Math.max(0, unreadCount.value - 1)
					}
					notification.value.splice(index, 1)
					total.value = Math.max(0, total.value - 1)
				}

				return true
			} catch (error) {
				message.error(error.message || '删除通知失败')
				throw error
			}
		}

		// 批量删除通知
		async function batchDeleteNotification(ids) {
			try {
				const res = await systemApi.notification.batchDelete.post({
					ids,
				})

				// 更新本地状态
				const deletedCount = 0
				ids.forEach((id) => {
					const index = notification.value.findIndex((n) => n.id === id)
					if (index !== -1) {
						const notification = notification.value[index]
						if (!notification.is_read) {
							unreadCount.value = Math.max(0, unreadCount.value - 1)
						}
						notification.value.splice(index, 1)
					}
				})
				total.value = Math.max(0, total.value - ids.length)

				return res.data
			} catch (error) {
				message.error(error.message || '批量删除通知失败')
				throw error
			}
		}

		// 清空已读通知
		async function clearReadNotifications() {
			try {
				await systemApi.notification.clearRead.post()

				// 更新本地状态
				notification.value = notification.value.filter((n) => !n.is_read)
				total.value = notification.value.length

				return true
			} catch (error) {
				message.error(error.message || '清空已读通知失败')
				throw error
			}
		}

		// 获取通知详情
		async function getNotificationDetail(id) {
			try {
				const res = await systemApi.notification.detail.get(id)
				return res.data
			} catch (error) {
				message.error(error.message || '获取通知详情失败')
				throw error
			}
		}

		// 发送通知（管理员功能）
		async function sendNotification(params) {
			try {
				const res = await systemApi.notification.send.post(params)
				message.success('发送通知成功')
				return res.data
			} catch (error) {
				message.error(error.message || '发送通知失败')
				throw error
			}
		}

		// 重试发送失败的通知（管理员功能）
		async function retryUnsentNotifications(params = {}) {
			try {
				const res = await systemApi.notification.retryUnsent.post(params)
				message.success('重试发送成功')
				return res.data
			} catch (error) {
				message.error(error.message || '重试发送失败')
				throw error
			}
		}

		// 获取通知统计信息
		async function fetchStatistics() {
			try {
				const res = await systemApi.notification.statistics.get()
				return res.data
			} catch (error) {
				message.error(error.message || '获取统计信息失败')
				throw error
			}
		}

		// 处理 WebSocket 消息
		function handleWebSocketMessage(data) {
			if (data.type === 'notification') {
				const notification = data.data

				// 添加到通知列表顶部
				notification.value.unshift(notification)
				total.value++

				// 如果是未读，增加未读数量
				if (!notification.is_read) {
					unreadCount.value++
				}

				// 限制本地存储的通知数量
				if (notification.value.length > 100) {
					notification.value = notification.value.slice(0, 100)
				}

				// 显示通知提示
				message.info(`新通知: ${notification.title}`)
			}
		}

		// 格式化通知时间
		function formatNotificationTime(timestamp) {
			if (!timestamp) return '-'

			const now = Date.now()
			const diff = now - new Date(timestamp).getTime()

			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')}`
			}
		}

		// 获取通知类型文本
		function getNotificationTypeText(type) {
			const texts = {
				info: '信息',
				success: '成功',
				warning: '警告',
				error: '错误',
				task: '任务',
				system: '系统',
			}
			return texts[type] || type
		}

		// 获取通知类型颜色
		function getNotificationTypeColor(type) {
			const colors = {
				info: 'blue',
				success: 'green',
				warning: 'orange',
				error: 'red',
				task: 'purple',
				system: 'cyan',
			}
			return colors[type] || 'default'
		}

		// 获取通知分类文本
		function getNotificationCategoryText(category) {
			const texts = {
				system: '系统通知',
				task: '任务通知',
				message: '消息通知',
				reminder: '提醒通知',
				announcement: '公告通知',
			}
			return texts[category] || category
		}

		// 重置状态
		function reset() {
			notification.value = []
			unreadCount.value = 0
			currentPage.value = 1
			total.value = 0
			loading.value = false
		}

		return {
			notification,
			unreadCount,
			loading,
			currentPage,
			pageSize,
			total,
			unreadCountComputed,
			readCount,
			fetchNotifications,
			fetchUnreadNotifications,
			fetchUnreadCount,
			markAsRead,
			batchMarkAsRead,
			markAllAsRead,
			deleteNotification,
			batchDeleteNotification,
			clearReadNotifications,
			getNotificationDetail,
			sendNotification,
			retryUnsentNotifications,
			fetchStatistics,
			handleWebSocketMessage,
			formatNotificationTime,
			getNotificationTypeText,
			getNotificationTypeColor,
			getNotificationCategoryText,
			reset,
			NotificationType,
			NotificationCategory,
			NotificationActionType,
		}
	},
	{
		persist: {
			key: 'notification-store',
			storage: customStorage,
			pick: [], // 不自动持久化，通知数据从服务器获取
		},
	},
)
