/**
 * 电子合同字段映射（兼容 snake_case / camelCase）
 */

export function mapContractItem(raw = {}, index = 0) {
	const contractId = raw.contractId != null ? raw.contractId : raw.contract_id
	const signStatus = raw.signStatus || raw.sign_status || ''
	const signedAt = raw.signedAt || raw.signed_at || ''
	const createTime = raw.createTime || raw.create_time || ''
	const title = raw.contractTitle || raw.contract_title || raw.orderTitle || raw.order_title || '电子合同'
	const enterpriseName = raw.enterpriseName || raw.enterprise_name || ''
	const statusMeta = mapSignStatus(signStatus)

	return {
		msgKey: contractId != null ? contractId : index,
		contractId,
		contractNo: raw.contractNo || raw.contract_no || '',
		registrationId: raw.registrationId != null ? raw.registrationId : raw.registration_id,
		orderId: raw.orderId != null ? raw.orderId : raw.order_id,
		orderTitle: raw.orderTitle || raw.order_title || '',
		enterpriseId: raw.enterpriseId != null ? raw.enterpriseId : raw.enterprise_id,
		enterpriseName,
		contractType: raw.contractType || raw.contract_type || '',
		contractTitle: title,
		signStatus,
		signStatusText: statusMeta.text,
		signStatusClass: statusMeta.cls,
		canSign: signStatus === 'pending' || signStatus === 'signing',
		signProvider: raw.signProvider || raw.sign_provider || '',
		signUrl: raw.signUrl || raw.sign_url || '',
		fileUrl: raw.fileUrl || raw.file_url || '',
		signedAt,
		signedAtText: formatDateTime(signedAt),
		createTime,
		createTimeText: formatDateTime(createTime),
		subtitle: enterpriseName || (raw.orderTitle || raw.order_title) || ''
	}
}

export function mapContractList(list) {
	const arr = Array.isArray(list) ? list : []
	return arr.map((item, i) => mapContractItem(item, i))
}

export function summarizeContracts(list) {
	const items = mapContractList(list)
	let signed = 0
	let pending = 0
	for (let i = 0; i < items.length; i++) {
		if (items[i].signStatus === 'signed') signed++
		else if (items[i].canSign) pending++
	}
	return {
		items,
		total: items.length,
		signed,
		pending
	}
}

function mapSignStatus(status) {
	const s = status == null ? '' : String(status)
	if (s === 'signed') return { text: '已签署', cls: 'done' }
	if (s === 'signing') return { text: '签署中', cls: 'review' }
	if (s === 'pending') return { text: '待签署', cls: 'pending' }
	if (s === 'rejected') return { text: '已拒签', cls: 'fail' }
	if (s === 'voided' || s === 'expired') return { text: '已失效', cls: 'fail' }
	return { text: s || '未知', cls: 'pending' }
}

function formatDateTime(value) {
	if (value == null || value === '') return ''
	const s = String(value).replace('T', ' ')
	return s.length >= 16 ? s.slice(0, 16) : s
}
