/**
 * 根据办理流程步骤 / 当前步骤码，决定进度弹层底部主按钮
 *
 * 优先使用 current_step_code（与订单状态机一致）：
 * - contract_signing → 开始用工
 * - work_started / settlement_pending → 发起结算
 * - settlement_paid → 开票办结
 * - completed → 已办结
 *
 * 兜底再用 steps 状态：
 * - 企业审核 done 且尚未到开始用工 → 开始用工
 */

const STEP_ORDER = [
	'draft_created',
	'plan_confirmed',
	'registration',
	'enterprise_audit',
	'contract_signing',
	'work_started',
	'settlement_pending',
	'settlement_paid',
	'completed'
]

const AUDIT_CODES = ['enterprise_audit', 'review']
const AUDIT_TITLES = ['企业审核']
const WORK_CODES = ['work_started', 'work']
const WORK_TITLES = ['开始用工']
const CONTRACT_CODES = ['contract_signing']
const CONTRACT_TITLES = ['合同签署', '合同', '签约']
const SETTLE_PENDING_CODES = ['settlement_pending']
const SETTLE_PENDING_TITLES = ['待结算']
const SETTLE_PAID_CODES = ['settlement_paid']
const SETTLE_PAID_TITLES = ['已支付']
const COMPLETED_CODES = ['completed']
const COMPLETED_TITLES = ['已完成', '办结', '完税']

function matchStep(steps, codes, titles) {
	const list = Array.isArray(steps) ? steps : []
	for (let i = 0; i < list.length; i++) {
		const s = list[i] || {}
		const key = s.key == null ? '' : String(s.key)
		const title = s.title == null ? '' : String(s.title)
		if (codes.indexOf(key) >= 0) return s
		for (let j = 0; j < titles.length; j++) {
			if (title.indexOf(titles[j]) >= 0) return s
		}
	}
	return null
}

function isDone(step) {
	return !!(step && step.status === 'done')
}

function isActive(step) {
	return !!(step && step.status === 'active')
}

function isPending(step) {
	return !!(step && step.status === 'pending')
}

function stepIndex(code) {
	if (!code) return -1
	return STEP_ORDER.indexOf(String(code))
}

function findActiveStepCode(steps) {
	const list = Array.isArray(steps) ? steps : []
	for (let i = 0; i < list.length; i++) {
		const s = list[i]
		if (s && s.status === 'active' && s.key) return String(s.key)
	}
	return ''
}

/**
 * @param {Array} steps
 * @param {string} [currentStepCode] 订单当前步骤（优先）
 * @returns {{ key: string, label: string, disabled?: boolean }}
 */
export function resolveProgressFooterAction(steps, currentStepCode) {
	const code = (currentStepCode && String(currentStepCode)) || findActiveStepCode(steps)
	const idx = stepIndex(code)

	// —— 优先按订单当前步骤 ——
	if (code === 'completed' || idx === stepIndex('completed')) {
		return { key: 'done', label: '已办结', disabled: true }
	}
	if (code === 'settlement_paid') {
		return { key: 'complete', label: '开票办结' }
	}
	if (code === 'settlement_pending' || code === 'work_started') {
		return { key: 'settle', label: '发起结算' }
	}
	// 企业审核已过后进入合同签署：应显示开始用工
	if (code === 'contract_signing') {
		return { key: 'startWork', label: '开始用工' }
	}

	// —— steps 兜底（无 current_step_code 或编码不在标准列表时）——
	const audit = matchStep(steps, AUDIT_CODES, AUDIT_TITLES)
	const work = matchStep(steps, WORK_CODES, WORK_TITLES)
	const contract = matchStep(steps, CONTRACT_CODES, CONTRACT_TITLES)
	const settlePending = matchStep(steps, SETTLE_PENDING_CODES, SETTLE_PENDING_TITLES)
	const settlePaid = matchStep(steps, SETTLE_PAID_CODES, SETTLE_PAID_TITLES)
	const completed = matchStep(steps, COMPLETED_CODES, COMPLETED_TITLES)

	if (isDone(completed) || isActive(completed)) {
		return { key: 'done', label: '已办结', disabled: true }
	}
	if (isActive(settlePaid)) {
		return { key: 'complete', label: '开票办结' }
	}
	if (isActive(settlePending) || isActive(work)) {
		return { key: 'settle', label: '发起结算' }
	}
	if (isDone(work)) {
		return { key: 'settle', label: '发起结算' }
	}

	// 合同签署进行中 / 已完成但未开工 → 开始用工
	if (isActive(contract) || isDone(contract)) {
		if (!work || isPending(work)) {
			return { key: 'startWork', label: '开始用工' }
		}
	}

	// 企业审核已完成，且尚未进入开始用工 → 开始用工
	if (isDone(audit)) {
		if (!work || isPending(work)) {
			return { key: 'startWork', label: '开始用工' }
		}
		return { key: 'startWork', label: '开始用工' }
	}

	// 已过企业审核节点（current 编码在其后）但上面未命中
	if (idx > stepIndex('enterprise_audit') && idx < stepIndex('work_started')) {
		return { key: 'startWork', label: '开始用工' }
	}

	return { key: 'urge', label: '催办未登记' }
}

export function formatMoney(value) {
	if (value == null || value === '') return '0.00'
	const n = Number(value)
	if (Number.isNaN(n)) return String(value)
	return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

export function pickSettlementAmount(summary) {
	if (!summary || typeof summary !== 'object') return null
	const total = summary.totalOutflow != null
		? summary.totalOutflow
		: (summary.total_outflow != null ? summary.total_outflow : summary.netAmount || summary.net_amount)
	return total
}
