import { formatMoney } from '@/utils/progress-action.js'

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

function pick(raw, camel, snake) {
	if (!raw || typeof raw !== 'object') return null
	if (raw[camel] != null && raw[camel] !== '') return raw[camel]
	if (raw[snake] != null && raw[snake] !== '') return raw[snake]
	return null
}

/** 税率展示：0.06 → 6% */
export function formatTaxRate(rate) {
	if (rate == null || rate === '') return '—'
	const n = Number(rate)
	if (Number.isNaN(n)) return String(rate)
	if (n > 0 && n <= 1) return `${Math.round(n * 10000) / 100}%`
	return `${n}%`
}

/**
 * GET /orders/{id}/invoice → 开票弹层展示结构
 * @param {object} raw
 * @param {{ sourceTitle?: string }} [options]
 */
export function mapOrderInvoice(raw = {}, options = {}) {
	const billable = num(pick(raw, 'billableAmount', 'billable_amount'))
	const invoiced = num(pick(raw, 'invoicedAmount', 'invoiced_amount'))
	const pending = num(pick(raw, 'pendingAmount', 'pending_amount'), Math.max(0, billable - invoiced))
	const invoiceAmount = num(pick(raw, 'invoiceAmount', 'invoice_amount'), pending || billable)
	const taxAmount = num(pick(raw, 'taxAmount', 'tax_amount'))
	const totalWithTax = num(pick(raw, 'totalWithTax', 'total_with_tax'), invoiceAmount + taxAmount)
	const taxRate = pick(raw, 'taxRate', 'tax_rate')
	const invoiceType = pick(raw, 'invoiceType', 'invoice_type') || 'vat_special'
	const invoiceTypeText = pick(raw, 'invoiceTypeText', 'invoice_type_text')
		|| (invoiceType === 'vat_normal' ? '增值税普通发票' : '增值税专用发票')
	const invoiceStatus = String(pick(raw, 'invoiceStatus', 'invoice_status') || '').toLowerCase()
	const archived = invoiceStatus === 'archived'
		|| invoiceStatus === 'completed'
		|| !!pick(raw, 'archivedAt', 'archived_at')
	const orderNo = pick(raw, 'orderNo', 'order_no') || ''
	const sourceTitle = options.sourceTitle
		|| (orderNo ? `订单 ${orderNo}` : '开票归档')

	return {
		orderId: pick(raw, 'orderId', 'order_id'),
		orderNo,
		sourceTitle,
		billableText: `¥${formatMoney(billable)}`,
		invoicedText: `¥${formatMoney(invoiced)}`,
		pendingText: `¥${formatMoney(pending)}`,
		invoiceType,
		invoiceTypeText,
		taxRate,
		taxRateText: formatTaxRate(taxRate),
		invoiceAmount,
		invoiceAmountText: `¥${formatMoney(invoiceAmount)}`,
		taxAmount,
		taxAmountText: `¥${formatMoney(taxAmount)}`,
		totalWithTax,
		totalWithTaxText: `¥${formatMoney(totalWithTax)}`,
		companyName: pick(raw, 'companyName', 'company_name') || '',
		creditCode: pick(raw, 'creditCode', 'credit_code') || '',
		bankAccountInfo: pick(raw, 'bankAccountInfo', 'bank_account_info') || '',
		invoiceNo: pick(raw, 'invoiceNo', 'invoice_no') || '',
		archived,
		canSubmit: !archived,
		complianceTip: pick(raw, 'complianceTip', 'compliance_tip') || '',
		raw
	}
}
