/** 结算方式展示 */
const SETTLEMENT_MODE_LABELS = {
	daily: '日结',
	piece: '计件',
	monthly: '月结'
}

const SCHEME_ICONS = {
	SCHEME_A: '⭐',
	SCHEME_B: '💡'
}

/**
 * 从 SSE 事件 JSON 提取卡片元数据（camelCase / snake_case 兼容）
 */
export function extractChatCardMeta(data) {
	if (!data || typeof data !== 'object') return null

	const contentType = data.content_type || data.contentType || null
	const rawDraftId = data.related_draft_id != null ? data.related_draft_id : data.relatedDraftId
	const relatedDraftId = rawDraftId != null && rawDraftId !== '' ? Number(rawDraftId) : null
	const nextAction = data.next_action || data.nextAction || null
	const cardPayload = data.card_payload || data.cardPayload || null

	if (!contentType && (relatedDraftId == null || Number.isNaN(relatedDraftId)) && !cardPayload && !nextAction) {
		return null
	}

	return {
		contentType,
		relatedDraftId: relatedDraftId != null && !Number.isNaN(relatedDraftId) ? relatedDraftId : null,
		nextAction,
		cardPayload
	}
}

/**
 * 合并流式过程中出现的卡片元数据（后出现的非空字段覆盖）
 */
export function mergeChatCardMeta(prev, next) {
	if (!next) return prev || null
	if (!prev) return next
	return {
		contentType: next.contentType || prev.contentType,
		relatedDraftId: next.relatedDraftId != null ? next.relatedDraftId : prev.relatedDraftId,
		nextAction: next.nextAction || prev.nextAction,
		cardPayload: next.cardPayload || prev.cardPayload
	}
}

/**
 * 是否应查询用工草稿详情并生成草稿卡片
 */
export function shouldFetchDraftCard(meta) {
	return !!(
		meta &&
		meta.contentType === 'card_draft' &&
		meta.relatedDraftId != null &&
		!Number.isNaN(Number(meta.relatedDraftId))
	)
}

/**
 * 草稿状态
 */
export function getDraftStatus(draft) {
	if (!draft) return 'pending'
	return draft.status || (draft.detail && draft.detail.status) || 'pending'
}

/**
 * 草稿是否已补全，可调用成本测算（仅 pending）
 */
export function isDraftReadyForCost(draft) {
	if (!draft) return false
	if (getDraftStatus(draft) !== 'pending') return false
	const missing = draft.missingFields || (draft.detail && draft.detail.missingFields) || []
	return Array.isArray(missing) && missing.length === 0
}

/**
 * pending 但必填未补全
 */
export function isDraftIncomplete(draft) {
	if (!draft) return false
	if (getDraftStatus(draft) !== 'pending') return false
	const missing = draft.missingFields || (draft.detail && draft.detail.missingFields) || []
	return Array.isArray(missing) && missing.length > 0
}

/**
 * 已确认草稿 → 用明细/缓存拼一版成本卡片（不可再调 cost-comparison）
 */
export function buildConfirmedCostPlans(draft) {
	if (!draft) return []
	if (Array.isArray(draft.costPlans) && draft.costPlans.length) {
		return draft.costPlans.map((plan) => ({ ...plan }))
	}
	if (draft.confirmedPlan && typeof draft.confirmedPlan === 'object') {
		return [{ ...draft.confirmedPlan, recommended: true }]
	}

	const detail = draft.detail || {}
	const code = draft.selectedSchemeCode || detail.selectedSchemeCode || 'SCHEME_A'
	const workerCount = draft.workerCount != null ? draft.workerCount : detail.workerCount
	const total = draft.estimatedTotal != null ? draft.estimatedTotal : detail.estimatedTotal
	const perCapita = draft.estimatedPerCapita != null
		? draft.estimatedPerCapita
		: detail.estimatedPerCapita
	const title = draft.confirmedPlanTitle || (code === 'SCHEME_B' ? '劳务报酬模式' : '灵活用工模式（推荐）')

	let avgCostText = '—'
	if (perCapita != null && perCapita !== '') {
		avgCostText = `${formatDraftMoney(perCapita)}/人`
	} else if (total != null && workerCount > 0) {
		avgCostText = `${formatDraftMoney(Number(total) / Number(workerCount))}/人`
	}

	return [{
		id: code,
		code,
		recommended: true,
		icon: SCHEME_ICONS[code] || '⭐',
		title,
		total: formatDraftMoney(total),
		avgCost: avgCostText,
		rows: [],
		breakdown: [],
		compliance: ['已确认']
	}]
}

export function formatSettlementMode(mode) {
	if (!mode) return '待补充'
	return SETTLEMENT_MODE_LABELS[mode] || mode
}

export function formatDraftMoney(val) {
	if (val == null || val === '') return '—'
	const n = Number(val)
	if (Number.isNaN(n)) return String(val)
	return `¥${n.toLocaleString('zh-CN', { maximumFractionDigits: 2 })}`
}

function pickField(obj, ...keys) {
	if (!obj || typeof obj !== 'object') return null
	for (let i = 0; i < keys.length; i++) {
		const key = keys[i]
		if (obj[key] != null && obj[key] !== '') return obj[key]
	}
	return null
}

/**
 * 接口方案 → 成本卡片展示结构
 * @param {Array} schemes McpDraftSchemeResponse[]
 * @param {{ workerCount?: number }} [ctx]
 */
export function mapCostSchemesToPlans(schemes = [], ctx = {}) {
	const workerCount = ctx.workerCount != null && ctx.workerCount > 0 ? Number(ctx.workerCount) : 1
	const list = Array.isArray(schemes) ? schemes : []

	return list.map((scheme, index) => {
		const code = scheme.code || `SCHEME_${index}`
		const title = scheme.title || code
		const tags = Array.isArray(scheme.tags) ? scheme.tags : []
		const cost = scheme.cost || {}
		const income = scheme.workerIncome || scheme.worker_income || {}

		const totalCost = pickField(cost, 'totalCost', 'total_cost')
		const companyPay = pickField(cost, 'companyPay', 'company_pay')
		const serviceFee = pickField(cost, 'serviceFee', 'service_fee')
		const gross = pickField(income, 'gross')
		const tax = pickField(income, 'tax')
		const net = pickField(income, 'net')

		const totalNum = Number(totalCost)
		let avgCostText = '—'
		if (!Number.isNaN(totalNum) && workerCount > 0) {
			avgCostText = `${formatDraftMoney(totalNum / workerCount)}/人`
		}

		const recommended =
			!!scheme.recommended ||
			code === 'SCHEME_A' ||
			String(title).indexOf('推荐') >= 0 ||
			tags.indexOf('推荐') >= 0

		const breakdown = []
		if (companyPay != null) breakdown.push({ label: '劳务费', value: formatDraftMoney(companyPay) })
		if (serviceFee != null) breakdown.push({ label: '服务费', value: formatDraftMoney(serviceFee) })
		if (tax != null) breakdown.push({ label: '代扣税费', value: formatDraftMoney(tax) })

		const rows = []
		if (net != null) rows.push({ label: '工人到手', value: formatDraftMoney(net) })
		if (gross != null) rows.push({ label: '税前收入', value: formatDraftMoney(gross) })

		return {
			id: code,
			code,
			recommended,
			icon: SCHEME_ICONS[code] || (recommended ? '⭐' : '💡'),
			title,
			total: formatDraftMoney(totalCost),
			avgCost: avgCostText,
			rows,
			breakdown,
			compliance: tags,
			raw: scheme
		}
	})
}

/**
 * 草稿详情 → 聊天气泡展示结构
 */
export function mapDraftDetailToCard(detail = {}) {
	const workerCount = detail.workerCount
	const workDays = detail.workDays
	let headcountText = '待补充'
	if (workerCount != null && workDays != null) {
		headcountText = `${workerCount}人 × ${workDays}天`
	} else if (workerCount != null) {
		headcountText = `${workerCount}人`
	} else if (workDays != null) {
		headcountText = `${workDays}天`
	}

	return {
		draftId: detail.id,
		draftNo: detail.draftNo,
		title: detail.title || '用工草稿',
		workType: detail.workType || '待补充',
		workLocation: detail.workLocation || '待补充',
		workerCount,
		workDays,
		headcountText,
		settlementMode: detail.settlementMode,
		settlementModeLabel: formatSettlementMode(detail.settlementMode),
		dailyWage: detail.dailyWage,
		estimatedTotal: detail.estimatedTotal,
		estimatedTotalText: formatDraftMoney(detail.estimatedTotal),
		estimatedPerCapita: detail.estimatedPerCapita,
		selectedPlanId: detail.selectedPlanId,
		selectedSchemeCode: detail.selectedSchemeCode || null,
		status: detail.status,
		missingFields: detail.missingFields || [],
		detail
	}
}

/**
 * 构造聊天气泡：用工草稿卡片
 */
export function buildDraftCardMessage(detail, msgKey) {
	return {
		type: 'draft',
		role: 'ai',
		msgKey,
		draftId: detail.id,
		draft: mapDraftDetailToCard(detail)
	}
}
