/**
 * 结算单摘要映射（含多工种拆分）
 */
import { formatMoney } from '@/utils/progress-action.js'
import { normalizeWorkerGroups } from '@/utils/draft.js'

function num(v, fallback = 0) {
	if (v == null || v === '') return fallback
	const n = Number(v)
	return Number.isNaN(n) ? fallback : n
}

function buildSourceTitle(raw) {
	const no = raw.orderNo || raw.order_no || ''
	const settlementNo = raw.settlementNo || raw.settlement_no || ''
	const title = raw.title || raw.batchTitle || raw.batch_title || ''
	if (title && (no || settlementNo)) {
		return `${title} ${settlementNo || no}`.trim()
	}
	if (no && settlementNo) return `${no} · ${settlementNo}`
	return title || no || settlementNo || '结算单'
}

function mapFees(raw = {}) {
	const feesRaw = Array.isArray(raw.fees) ? raw.fees : []
	return feesRaw.map((f, i) => {
		const rate = f.rate != null ? Number(f.rate) : null
		const name = f.feeName || f.fee_name || '费用'
		const nameWithRate = rate != null && !Number.isNaN(rate) && rate > 0 && rate <= 1
			? `${name}(${Math.round(rate * 100)}%)`
			: (rate != null && !Number.isNaN(rate) && rate > 1 ? `${name}(${rate}%)` : name)
		return {
			msgKey: f.feeCode || f.fee_code || i,
			name: nameWithRate,
			amount: f.amount,
			amountText: `¥${formatMoney(f.amount)}`
		}
	})
}

/**
 * 按草稿工种组拆分：企业人均成本 / 员工人均到手 / 工种实发合计
 * 无工种组时退化为整体一条
 */
export function buildSettlementWorkTypeGroups(raw = {}, draftGroups = []) {
	const groups = Array.isArray(draftGroups) && draftGroups.length
		? draftGroups
		: normalizeWorkerGroups(raw)
	const totalOut = num(raw.totalOutflow != null ? raw.totalOutflow : raw.total_outflow)
	const netTotal = num(raw.netAmount != null ? raw.netAmount : raw.net_amount)
	const workerCount = num(raw.workerCount != null ? raw.workerCount : raw.worker_count)

	const weights = groups.map((g) => {
		const totalAmount = num(g.totalAmount)
		if (totalAmount > 0) return totalAmount
		const unit = num(g.unitAmount)
		const count = num(g.workerCount)
		const days = num(g.workDays, 1)
		const w = unit * count * days
		return w > 0 ? w : count
	})
	const weightSum = weights.reduce((a, b) => a + b, 0)

	if (!groups.length || weightSum <= 0) {
		const avgEnt = workerCount > 0 ? totalOut / workerCount : 0
		const avgNet = workerCount > 0 ? netTotal / workerCount : 0
		return [{
			msgKey: 'all',
			workType: '全部工种',
			workerCount,
			avgEnterprise: avgEnt,
			avgNet,
			netTotal,
			avgEnterpriseText: `¥${formatMoney(avgEnt)}`,
			avgNetText: `¥${formatMoney(avgNet)}`,
			netTotalText: `¥${formatMoney(netTotal)}`,
			workerCountText: `共${workerCount}人`
		}]
	}

	return groups.map((g, i) => {
		const count = num(g.workerCount)
		const share = weights[i] / weightSum
		const groupEnterprise = totalOut * share
		const groupNet = netTotal * share
		const avgEnt = count > 0 ? groupEnterprise / count : 0
		const avgNet = count > 0 ? groupNet / count : 0
		const workType = g.workType || `工种${i + 1}`
		return {
			msgKey: g.groupId || `wt_${i}`,
			workType,
			workerCount: count,
			avgEnterprise: avgEnt,
			avgNet,
			netTotal: groupNet,
			avgEnterpriseText: `¥${formatMoney(avgEnt)}`,
			avgNetText: `¥${formatMoney(avgNet)}`,
			netTotalText: `¥${formatMoney(groupNet)}`,
			workerCountText: `共${count}人`
		}
	})
}

/**
 * @param {object} raw 结算接口响应
 * @param {{ workerGroups?: Array, title?: string }} [ctx]
 */
export function mapSettlementSummary(raw = {}, ctx = {}) {
	const fees = mapFees(raw)
	const net = raw.netAmount != null ? raw.netAmount : raw.net_amount
	const deduction = raw.deductionAmount != null ? raw.deductionAmount : raw.deduction_amount
	const gross = raw.grossAmount != null ? raw.grossAmount : raw.gross_amount
	const total = raw.totalOutflow != null ? raw.totalOutflow : raw.total_outflow
	const status = raw.settlementStatus || raw.settlement_status || ''
	const workerCount = raw.workerCount != null ? raw.workerCount : raw.worker_count
	const workTypeGroups = buildSettlementWorkTypeGroups(
		Object.assign({}, raw, { title: ctx.title }),
		ctx.workerGroups || []
	)

	const enrichedRaw = Object.assign({}, raw, {
		title: ctx.title || raw.title,
		batchTitle: ctx.title
	})

	return {
		settlementId: raw.settlementId != null ? raw.settlementId : raw.settlement_id,
		settlementNo: raw.settlementNo || raw.settlement_no || '',
		orderId: raw.orderId != null ? raw.orderId : raw.order_id,
		orderNo: raw.orderNo || raw.order_no || '',
		currentStepCode: raw.currentStepCode || raw.current_step_code || '',
		settlementStatus: status,
		statusLabel: status === 'paid' ? '已支付' : '待支付',
		statusClass: status === 'paid' ? 'success' : 'danger',
		workerCount,
		netAmount: net,
		deductionAmount: deduction,
		grossAmount: gross,
		totalOutflow: total,
		enterpriseTotalText: `¥${formatMoney(total)}`,
		netText: `¥${formatMoney(net)}`,
		deductionText: `-¥${formatMoney(deduction)}`,
		grossText: `¥${formatMoney(gross)}`,
		totalText: `¥${formatMoney(total)}`,
		sourceTitle: buildSourceTitle(enrichedRaw),
		fees,
		workTypeGroups,
		multiWorkType: workTypeGroups.length > 1,
		complianceTags: [
			{ msgKey: 't1', text: '业务真实' },
			{ msgKey: 't2', text: '资金合规' },
			{ msgKey: 't3', text: '个税已申报' },
			{ msgKey: 't4', text: '五流合一' }
		],
		complianceRemark: '本单据符合五流合一，可全额税前扣除',
		canPay: status !== 'paid' && status !== 'cancelled',
		message: raw.message || ''
	}
}
