export const CHAT_TYPE_LABELS = {
	employment: '用工需求咨询',
	knowledge: '用工知识咨询',
	order: '用工订单管理',
	cost: '成本测算',
	attendance: '现场考勤记录',
	emergency: '紧急事件处理'
}

/** 上次停留的会话编号（按用户隔离，退出再进助手时恢复） */
const LAST_CONVERSATION_KEY_PREFIX = 'fe_last_conversation_no_'

function lastConversationStorageKey(userId) {
	const uid = userId != null && userId !== '' ? String(userId) : 'guest'
	return LAST_CONVERSATION_KEY_PREFIX + uid
}

/**
 * 读取用户上次打开的会话编号
 * @param {string|number|null} [userId]
 * @returns {string}
 */
export function getLastConversationNo(userId) {
	try {
		const value = uni.getStorageSync(lastConversationStorageKey(userId))
		return value ? String(value) : ''
	} catch (e) {
		return ''
	}
}

/**
 * 记录用户当前停留的会话编号
 * @param {string|number|null} [userId]
 * @param {string} conversationNo
 */
export function setLastConversationNo(userId, conversationNo) {
	if (!conversationNo) return
	try {
		uni.setStorageSync(lastConversationStorageKey(userId), String(conversationNo))
	} catch (e) {
		// 存储失败不影响主流程
	}
}

/** 会话消息分页默认每页条数 */
export const CONVERSATION_MESSAGE_PAGE_SIZE = 30

/**
 * 根据总条数计算最后一页页码（接口按时间正序，最后一页为最新消息）
 */
export function calcLastMessagePage(total = 0, size = CONVERSATION_MESSAGE_PAGE_SIZE) {
	if (!total || total <= 0) return 1
	return Math.ceil(total / size)
}

/**
 * 将接口消息映射为聊天气泡结构
 */
export function mapConversationMessage(item = {}) {
	const role = item.role === 'user' ? 'user' : 'ai'
	const contentType = item.contentType || item.content_type || 'text'
	const relatedDraftIdRaw = item.relatedDraftId != null ? item.relatedDraftId : item.related_draft_id
	const relatedDraftId =
		relatedDraftIdRaw != null && relatedDraftIdRaw !== '' ? Number(relatedDraftIdRaw) : null

	return {
		id: item.id,
		msgKey: item.id,
		type: 'text',
		role,
		content: item.content || '',
		contentType,
		relatedDraftId: relatedDraftId != null && !Number.isNaN(relatedDraftId) ? relatedDraftId : null,
		nextAction: item.nextAction || item.next_action || null,
		cardPayload: item.cardPayload || item.card_payload || null,
		createTime: item.createTime
	}
}

/**
 * 开启新对话时的时段问候语
 * @param {Date} [date]
 */
export function getNewChatGreeting(date = new Date()) {
	const hour = date.getHours()
	let period = '晚上'
	if (hour >= 5 && hour < 11) {
		period = '早上'
	} else if (hour >= 11 && hour < 14) {
		period = '中午'
	} else if (hour >= 14 && hour < 18) {
		period = '下午'
	}
	return `老板${period}好，有什么可以帮助您`
}

/**
 * 格式化会话列表时间展示
 * @param {string} value ISO 或 yyyy-MM-dd HH:mm:ss
 */
export function formatConversationTime(value) {
	if (!value) return ''
	const normalized = String(value).replace(' ', 'T')
	const date = new Date(normalized)
	if (Number.isNaN(date.getTime())) return ''

	const now = new Date()
	const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime()
	const targetStart = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime()
	const diffDays = Math.floor((todayStart - targetStart) / 86400000)

	const hh = String(date.getHours()).padStart(2, '0')
	const mm = String(date.getMinutes()).padStart(2, '0')
	const timeStr = `${hh}:${mm}`

	if (diffDays === 0) return `今天 ${timeStr}`
	if (diffDays === 1) return `昨天 ${timeStr}`
	if (diffDays < 7) return `${diffDays}天前`
	return `${date.getMonth() + 1}月${date.getDate()}日`
}

/**
 * 将接口会话摘要映射为侧边栏展示结构
 */
export function mapConversationItem(item = {}) {
	const chatType = item.chatType || 'employment'
	return {
		id: item.id,
		conversationNo: item.conversationNo,
		title: item.title || CHAT_TYPE_LABELS[chatType] || '新对话',
		time: formatConversationTime(item.lastMessageAt || item.createTime),
		chatType,
		status: item.status,
		lastMessageAt: item.lastMessageAt,
		createTime: item.createTime
	}
}
