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

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

export const NEXT_ACTION_SHOW_ORDER_QRCODE = 'show_order_qrcode'

/**
 * 从 SSE 事件 JSON 提取卡片元数据（camelCase / snake_case 兼容）
 * - content_type=card_draft|card_order|card_cost
 * - 或 next_action=show_order_qrcode（对话写入确认文案 + 二维码卡）
 */
export function extractChatCardMeta(data) {
	if (!data || typeof data !== 'object') return null

	const contentType = data.content_type || data.contentType || null
	const nextAction = data.next_action || data.nextAction || null
	const isOrderQrAction = nextAction === NEXT_ACTION_SHOW_ORDER_QRCODE
	const isKnownCardType = contentType === 'card_draft'
		|| contentType === 'card_order'
		|| contentType === 'card_cost'

	if (!isKnownCardType && !isOrderQrAction) return null
	if (contentType === 'text' && !isOrderQrAction) return null

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

	return {
		contentType: isKnownCardType ? contentType : (isOrderQrAction ? 'card_order' : 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
	}
}

/**
 * 会触发拉取用工草稿并展示聊天气泡的 content_type
 * card_draft：待确认草稿；card_order：已确认订单（related_draft_id 仍为草稿 id）
 */
export function isDraftCardContentType(contentType) {
	return contentType === 'card_draft' || contentType === 'card_order'
}

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

/**
 * AI 对话：下一步为展示订单二维码（对话内确认文案 + 二维码卡）
 */
export function shouldShowOrderQrcode(meta) {
	if (!meta) return false
	const action = meta.nextAction || meta.next_action || ''
	return action === NEXT_ACTION_SHOW_ORDER_QRCODE
}

/**
 * 解析 SSE / 消息中的 card_payload（对象或 JSON 字符串）
 */
export function parseChatCardPayload(raw) {
	if (!raw) return null
	if (typeof raw === 'object') return raw
	if (typeof raw !== 'string') return null
	const text = raw.trim()
	if (!text) return null
	try {
		const parsed = JSON.parse(text)
		return parsed && typeof parsed === 'object' ? parsed : null
	} catch (e) {
		return null
	}
}

/**
 * 草稿状态
 */
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
		}
	})
}

/**
 * 从草稿详情 / 卡片结构读取登记小程序码 URL（优先小驼峰 qrCodeUrl）
 */
export function pickDraftQrCodeUrl(source) {
	if (!source || typeof source !== 'object') return ''
	const nested = source.detail && typeof source.detail === 'object' ? source.detail : null
	return source.qrCodeUrl
		|| source.qr_code_url
		|| (nested && (nested.qrCodeUrl || nested.qr_code_url))
		|| ''
}

/**
 * 从草稿详情 / 确认响应读取登记 token（优先小驼峰 qrToken）
 * 与公开查询 / 小程序码 scene 值一致
 */
export function pickDraftQrToken(source) {
	if (!source || typeof source !== 'object') return ''
	const nested = source.detail && typeof source.detail === 'object' ? source.detail : null
	const raw = source.qrToken
		|| source.qr_token
		|| (nested && (nested.qrToken || nested.qr_token))
		|| ''
	return raw == null ? '' : String(raw).trim()
}

/**
 * 草稿详情 → 聊天气泡展示结构
 */
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
			|| detail.selected_scheme_code
			|| null,
		status: detail.status,
		orderId: detail.orderId || detail.order_id || '',
		missingFields: detail.missingFields || [],
		qrCodeUrl: pickDraftQrCodeUrl(detail),
		qrToken: pickDraftQrToken(detail),
		detail
	}
}

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

/**
 * 同步草稿卡展示字段（供小程序模板直接绑定，避免 :class 调方法）
 */
export function syncDraftCardViewMeta(msg) {
	if (!msg || msg.type !== 'draft') return msg
	const voided = !!msg.voided
	const confirmed = !voided && !!msg.draft && getDraftStatus(msg.draft) === 'confirmed'
	msg.draftRootClass = voided
		? 'fe-biz-card--draft-voided'
		: (confirmed ? 'fe-biz-card--draft-confirmed' : '')
	msg.draftStatusClass = voided
		? 'fe-draft-card-status--cancelled'
		: (confirmed ? 'fe-draft-card-status--confirmed' : 'fe-draft-card-status--pending')
	msg.draftStatusLabel = voided ? '已作废' : (confirmed ? '已确认' : '未确认')
	return msg
}
