/**
 * 临时工招聘弹层：本地模拟匹配（接口不可用时兜底）
 */

import { syncRecruitGroupMeta } from '@/utils/recruit.js'

const MOCK_NAMES = [
	'张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十',
	'郑十一', '王小明', '李小红', '陈强', '刘洋', '黄磊', '林娜', '何伟'
]

const MOCK_EXPS = ['1年经验', '2年经验', '3年经验', '5年经验', '半年经验']

function pick(list, i) {
	return list[i % list.length]
}

/**
 * 从草稿工种行构建招聘条件 + 模拟匹配分组
 * @param {Array} workerGroups normalizeWorkerGroups 结果
 */
export function buildRecruitMockFromGroups(workerGroups = []) {
	const groups = Array.isArray(workerGroups) ? workerGroups.filter((g) => g && g.workType) : []
	const seedGroups = groups.length
		? groups
		: [
			{ workType: '搬运工', workerCount: 10, workLocation: '浦东新区', workDays: 2, unitAmount: 500 },
			{ workType: '保洁', workerCount: 5, workLocation: '浦东新区', workDays: 2, unitAmount: 400 }
		]

	const criteriaTypes = seedGroups.map((g) => g.workType).filter(Boolean)
	const totalNeed = seedGroups.reduce((sum, g) => sum + (Number(g.workerCount) || 0), 0)
	const locations = []
	const daysSet = []
	seedGroups.forEach((g) => {
		if (g.workLocation && locations.indexOf(g.workLocation) < 0) locations.push(g.workLocation)
		if (g.workDays != null && g.workDays !== '') daysSet.push(Number(g.workDays))
	})
	const days = daysSet.length ? daysSet[0] : 2

	const matchGroups = seedGroups.map((g, gi) => {
		const need = Number(g.workerCount) > 0 ? Number(g.workerCount) : 5
		const matchCount = Math.min(Math.max(need, 3), need + 2)
		const rate = g.unitAmount != null && !Number.isNaN(Number(g.unitAmount))
			? Number(g.unitAmount)
			: (gi === 0 ? 500 : 400)
		const workers = []
		for (let i = 0; i < matchCount; i++) {
			const name = pick(MOCK_NAMES, gi * 7 + i)
			const selected = i < Math.min(need, matchCount)
			workers.push({
				msgKey: `w_${gi}_${i}`,
				name,
				avatarText: name.charAt(0) || '工',
				jobType: g.workType,
				experience: pick(MOCK_EXPS, gi + i),
				location: g.workLocation || '浦东新区',
				dailyRate: rate,
				metaText: `${g.workType} · ${pick(MOCK_EXPS, gi + i)} · ${g.workLocation || '浦东新区'} · ¥${rate}/天`,
				selected,
				checkClass: selected ? 'recruit-check recruit-check--on' : 'recruit-check'
			})
		}
		const selectedCount = workers.filter((w) => w.selected).length
		return {
			msgKey: `g_${gi}`,
			workType: g.workType,
			needCount: need,
			selectedCount,
			countText: `${selectedCount}/${need}`,
			expanded: true,
			chevronText: '▼',
			headClass: 'recruit-group__head',
			workers
		}
	})

	const matchedTotal = matchGroups.reduce((n, g) => n + (g.workers ? g.workers.length : 0), 0)

	return {
		criteria: {
			jobTypeText: criteriaTypes.join('，') || '—',
			needCountText: totalNeed > 0 ? `${totalNeed}人` : '—',
			locationText: locations.join('，') || '—',
			daysText: days != null && !Number.isNaN(days) ? `${days}天` : '—'
		},
		matchGroups,
		matchedTotal,
		resultTitle: `匹配结果（${matchedTotal}人）`
	}
}

export { syncRecruitGroupMeta }
