/**
 * 登记批次详情 → 进度弹层展示结构
 * 兼容后端 snake_case（@JsonProperty）与小驼峰
 */
export function mapRegistrationBatchDetail(raw = {}) {
	const stats = raw.stats || {}
	const progress = raw.progress || {}
	const steps = Array.isArray(raw.steps) ? raw.steps : []
	const workers = Array.isArray(raw.workers) ? raw.workers : []

	const pending = num(stats.pendingCount, stats.pending_count, 0)
	const inProgress = num(stats.inProgressCount, stats.in_progress_count, 0)
	const completed = num(stats.completedCount, stats.completed_count, 0)
	const expected = num(stats.expectedCount, stats.expected_count, 0)
	const registered = num(stats.registeredCount, stats.registered_count, progress.current)

	const current = num(progress.current, null, registered)
	const total = num(progress.total, null, expected)
	const percent = num(progress.percent, null, total > 0 ? Math.round((current / total) * 100) : 0)

	return {
		draftId: raw.draftId != null ? raw.draftId : (raw.draft_id != null ? raw.draft_id : null),
		batchId: raw.batchId != null ? raw.batchId : raw.batch_id,
		batchNo: raw.batchNo || raw.batch_no || '',
		title: raw.title || '用工批次',
		subtitle: raw.subtitle || '',
		orderId: raw.orderId != null ? raw.orderId : raw.order_id,
		orderNo: raw.orderNo || raw.order_no || '',
		status: raw.status || '',
		qrToken: raw.qrToken || raw.qr_token || '',
		qrCodeUrl: raw.qrCodeUrl || raw.qr_code_url || '',
		stats: {
			pending,
			inProgress,
			completed,
			expected,
			registered
		},
		progress: {
			current,
			total,
			percent: Math.max(0, Math.min(100, percent)),
			text: `${current}/${total}`
		},
		steps: steps.map((s, i) => ({
			key: s.stepCode || s.step_code || `step-${i}`,
			title: s.title || '',
			status: s.status || 'pending',
			time: s.time || '',
			highlight: s.highlight || ''
		})),
		workers: workers.map((w, i) => {
			const name = w.realName || w.real_name || '—'
			return {
				msgKey: w.registrationId != null
					? w.registrationId
					: (w.registration_id != null ? w.registration_id : i),
				name,
				avatarText: String(name).charAt(0) || '工',
				phone: w.mobileMask || w.mobile_mask || '',
				status: mapWorkerStatusTag(w.statusTag || w.status_tag || w.regStatus || w.reg_status),
				statusText: w.statusText || w.status_text || '',
				failReason: w.failReason || w.fail_reason || ''
			}
		})
	}
}

function num(a, b, fallback) {
	if (a != null && a !== '' && !Number.isNaN(Number(a))) return Number(a)
	if (b != null && b !== '' && !Number.isNaN(Number(b))) return Number(b)
	if (fallback != null && fallback !== '' && !Number.isNaN(Number(fallback))) return Number(fallback)
	return 0
}

function mapWorkerStatusTag(tag) {
	const t = tag == null ? '' : String(tag)
	if (t === 'done' || t === 'completed') return 'done'
	if (t === 'fail' || t === 'verify_failed') return 'fail'
	if (t === 'review' || t === 'under_review') return 'review'
	if (t === 'registering' || t === 'in_progress') return 'review'
	return 'pending'
}

/**
 * 会话内草稿进度合集（接口未就绪时的 mock）
 * @param {Array<{ draftId?: number|string, title?: string, batchNo?: string }>} [seeds]
 */
export function buildMockConversationProgressList(seeds = []) {
	const list = Array.isArray(seeds) && seeds.length
		? seeds
		: [
			{ draftId: 101, title: '浦东仓库搬运', batchNo: 'bat_1' },
			{ draftId: 102, title: '商场促销推广', batchNo: 'bat_2' },
			{ draftId: 103, title: '展会驻场接待', batchNo: 'bat_3' }
		]

	return list.map((seed, idx) => {
		const total = 8 + (idx % 3) * 2
		const current = Math.min(total, 3 + idx * 2)
		const pending = Math.max(0, total - current)
		const inProgress = Math.min(current, 2 + (idx % 2))
		const completed = Math.max(0, current - inProgress)
		const title = seed.title || `用工批次 ${idx + 1}`
		const batchNo = seed.batchNo || `bat_${idx + 1}`
		const draftId = seed.draftId != null ? seed.draftId : (100 + idx)
		return mapRegistrationBatchDetail({
			draft_id: draftId,
			batch_id: draftId,
			batch_no: batchNo,
			title,
			subtitle: `${title} ${batchNo}`,
			order_no: `ord_${draftId}`,
			status: 'active',
			stats: {
				pending_count: pending,
				in_progress_count: inProgress,
				completed_count: completed,
				expected_count: total,
				registered_count: current
			},
			progress: {
				current,
				total,
				percent: Math.round((current / total) * 100)
			},
			steps: [
				{ step_code: 'draft', title: '草稿创建', status: 'done', time: '01-15 14:30' },
				{ step_code: 'plan', title: '方案确认', status: 'done', time: '01-15 14:35' },
				{
					step_code: 'registration',
					title: '扫码登记',
					status: 'active',
					highlight: `进行中 ${current}/${total}`
				},
				{ step_code: 'review', title: '企业审核', status: 'pending' },
				{ step_code: 'work', title: '开始用工', status: 'pending' }
			],
			workers: [
				{ registration_id: idx * 10 + 1, real_name: '张三', mobile_mask: '138****1234', status_tag: 'done', status_text: '已完成' },
				{ registration_id: idx * 10 + 2, real_name: '李四', mobile_mask: '139****5678', status_tag: 'done', status_text: '已完成' },
				{ registration_id: idx * 10 + 3, real_name: '王五', mobile_mask: '137****9012', status_tag: 'fail', status_text: '核验失败' },
				{ registration_id: idx * 10 + 4, real_name: '赵六', mobile_mask: '136****3456', status_tag: 'pending', status_text: '待登记' },
				{ registration_id: idx * 10 + 5, real_name: '钱七', mobile_mask: '135****7890', status_tag: 'review', status_text: '审核中' }
			]
		})
	})
}
