/**
 * 消息与待办字段映射
 */

const TYPE_META = {
	pending: { label: '待办', cls: 'pending' },
	error: { label: '异常', cls: 'error' },
	info: { label: '通知', cls: 'info' },
	success: { label: '成功', cls: 'success' }
}

export function mapNotificationItem(raw = {}, index = 0) {
	const id = raw.id != null ? raw.id : index
	const notifyType = raw.notifyType || raw.notify_type || 'info'
	const meta = TYPE_META[notifyType] || TYPE_META.info
	const createTime = raw.createTime || raw.create_time || ''
	const readFlag = raw.readFlag === true || raw.read_flag === true
	const handledFlag = raw.handledFlag === true || raw.handled_flag === true

	return {
		msgKey: id,
		id,
		enterpriseId: raw.enterpriseId != null ? raw.enterpriseId : raw.enterprise_id,
		notifyType,
		typeLabel: meta.label,
		typeClass: meta.cls,
		category: raw.category || '',
		title: raw.title || '消息',
		desc: raw.content || '',
		bizType: raw.bizType || raw.biz_type || '',
		bizId: raw.bizId != null ? raw.bizId : raw.biz_id,
		bizNo: raw.bizNo || raw.biz_no || '',
		actionUrl: raw.actionUrl || raw.action_url || '',
		readFlag,
		handledFlag,
		createTime,
		timeText: formatRelativeTime(createTime),
		itemClass: buildItemClass(readFlag, handledFlag, notifyType)
	}
}

export function mapNotificationPage(raw = {}) {
	const items = Array.isArray(raw.items) ? raw.items : []
	return {
		items: items.map((it, i) => mapNotificationItem(it, i)),
		total: Number(raw.total != null ? raw.total : 0),
		page: Number(raw.page != null ? raw.page : 1),
		size: Number(raw.size != null ? raw.size : 20),
		hasMore: !!(raw.hasMore === true || raw.has_more === true),
		unreadCount: Number(raw.unreadCount != null ? raw.unreadCount : (raw.unread_count != null ? raw.unread_count : 0)),
		pendingCount: Number(raw.pendingCount != null ? raw.pendingCount : (raw.pending_count != null ? raw.pending_count : 0))
	}
}

function buildItemClass(readFlag, handledFlag, notifyType) {
	const parts = []
	if (!readFlag) parts.push('msg-card--unread')
	if (notifyType === 'pending' && !handledFlag) parts.push('msg-card--todo')
	if (handledFlag) parts.push('msg-card--handled')
	return parts.join(' ')
}

function formatRelativeTime(value) {
	if (value == null || value === '') return ''
	const s = String(value).replace('T', ' ')
	const t = Date.parse(s.replace(/-/g, '/'))
	if (Number.isNaN(t)) {
		return s.length >= 16 ? s.slice(0, 16) : s
	}
	const diff = Date.now() - t
	if (diff < 60 * 1000) return '刚刚'
	if (diff < 60 * 60 * 1000) return `${Math.floor(diff / 60000)}分钟前`
	if (diff < 24 * 60 * 60 * 1000) return `${Math.floor(diff / 3600000)}小时前`
	if (diff < 7 * 24 * 60 * 60 * 1000) return `${Math.floor(diff / 86400000)}天前`
	return s.length >= 16 ? s.slice(0, 16) : s
}
