import {
	formatDraftMoney,
	formatSettlementMode,
	formatWorkerGroupHeadcount,
	mapDraftDetailToCard,
	normalizeWorkerGroups
} from '@/utils/draft.js'

const OFFER_STORAGE_PREFIX = 'fe_job_offer_'

/**
 * 从确认方案中提取工人到手金额
 */
export function pickWorkerNetPay(scheme) {
	if (!scheme) return null
	const rows = Array.isArray(scheme.rows) ? scheme.rows : []
	for (let i = 0; i < rows.length; i++) {
		const row = rows[i]
		if (row && row.label && String(row.label).indexOf('到手') >= 0) {
			return row.value
		}
	}
	const income = (scheme.raw && (scheme.raw.workerIncome || scheme.raw.worker_income)) || {}
	const net = income.net
	if (net != null && net !== '') return formatDraftMoney(net)
	return null
}

function estimateNetFromDraft(draftLike) {
	const dailyWage = draftLike && draftLike.dailyWage != null ? Number(draftLike.dailyWage) : null
	const workDays = draftLike && draftLike.workDays != null ? Number(draftLike.workDays) : null
	if (dailyWage != null && !Number.isNaN(dailyWage) && workDays != null && !Number.isNaN(workDays)) {
		return formatDraftMoney(dailyWage * workDays)
	}
	return null
}

/**
 * 草稿用工组 → 邀请页可选工种
 * @returns {Array<object>}
 */
export function buildWorkTypeOptions(groups = [], fallback = {}) {
	const list = Array.isArray(groups) ? groups : []
	const options = []
	for (let i = 0; i < list.length; i++) {
		const g = list[i]
		if (!g) continue
		const workType = String(g.workType || '').trim()
		if (!workType) continue
		const unitAmount = g.unitAmount != null ? Number(g.unitAmount) : null
		const workDays = g.workDays != null ? Number(g.workDays) : null
		const workerCount = g.workerCount != null ? Number(g.workerCount) : null
		const settlementMode = g.settlementMode || ''
		const dailyWage = unitAmount != null && !Number.isNaN(unitAmount)
			? unitAmount
			: (fallback.dailyWage != null ? Number(fallback.dailyWage) : null)
		let netPayText = estimateNetFromDraft({ dailyWage, workDays }) || ''
		if (!netPayText && g.totalAmount != null && workerCount > 0) {
			netPayText = formatDraftMoney(Number(g.totalAmount) / workerCount)
		}
		options.push({
			optKey: g.groupId || `wt_${i}`,
			workType,
			workLocation: g.workLocation || fallback.workLocation || '',
			workerCount: workerCount != null && !Number.isNaN(workerCount) ? workerCount : null,
			workDays: workDays != null && !Number.isNaN(workDays) ? workDays : null,
			dailyWage: dailyWage != null && !Number.isNaN(dailyWage) ? dailyWage : null,
			settlementMode,
			settlementModeLabel: formatSettlementMode(settlementMode),
			headcountText: formatWorkerGroupHeadcount(g) || '',
			wageText: dailyWage != null && !Number.isNaN(dailyWage) ? `${dailyWage} 元` : '待确认',
			netPayText: netPayText || '',
			selected: false,
			optionClass: 'offer-type-opt'
		})
	}
	// 无分组时，用扁平工种兜底成 1 项（仍可展示，无需选手动）
	if (!options.length) {
		const flat = String(fallback.workType || '').trim()
		if (flat && flat !== '待确认' && flat !== '待补充' && flat.indexOf('、') < 0) {
			options.push({
				optKey: 'flat_0',
				workType: flat,
				workLocation: fallback.workLocation || '',
				workerCount: fallback.workerCount != null ? Number(fallback.workerCount) : null,
				workDays: fallback.workDays != null ? Number(fallback.workDays) : null,
				dailyWage: fallback.dailyWage != null ? Number(fallback.dailyWage) : null,
				settlementMode: fallback.settlementMode || '',
				settlementModeLabel: formatSettlementMode(fallback.settlementMode),
				headcountText: '',
				wageText: fallback.dailyWage != null ? `${fallback.dailyWage} 元` : '待确认',
				netPayText: fallback.netPayText || '',
				selected: false,
				optionClass: 'offer-type-opt'
			})
		}
	}
	return options
}

/**
 * 用工草稿 + 确认结果 → 扫码落地页展示数据
 */
export function buildJobOfferFromDraft(draft, options = {}) {
	const detail = (draft && draft.detail) || {}
	const draftId = options.draftId
		|| (draft && (draft.draftId != null ? draft.draftId : draft.id))
		|| (detail && detail.id)
		|| null
	const batchId = (draft && draft.draftNo) || options.batchId || (draftId != null ? `draft_${draftId}` : '')
	const groups = (draft && Array.isArray(draft.workerGroups) && draft.workerGroups.length)
		? draft.workerGroups
		: normalizeWorkerGroups(detail)
	let workType = (draft && draft.workType) || detail.workType || ''
	let workLocation = (draft && draft.workLocation) || detail.workLocation || ''
	let workDays = draft && draft.workDays != null ? draft.workDays : detail.workDays
	let workerCount = draft && draft.workerCount != null ? draft.workerCount : detail.workerCount
	let dailyWage = draft && draft.dailyWage != null ? draft.dailyWage : detail.dailyWage
	let settlementMode = (draft && draft.settlementMode) || detail.settlementMode || ''
	const title = (draft && draft.title && draft.title !== '用工草稿')
		? draft.title
		: ([
			workLocation && workLocation !== '待补充' ? workLocation : '',
			workType && workType !== '待补充' && String(workType).indexOf('、') < 0 ? workType : ''
		].join('') || options.schemeTitle || '临时用工邀请')

	const scheme = options.scheme || (draft && draft.confirmedPlan) || null
	let netPayText = pickWorkerNetPay(scheme) || options.netPayText || ''
	if (!netPayText && options.netPay != null && options.netPay !== '') {
		netPayText = formatDraftMoney(options.netPay)
	}
	if (!netPayText) {
		netPayText = estimateNetFromDraft({ dailyWage, workDays }) || ''
	}
	if (!netPayText) {
		const capita = draft && draft.estimatedPerCapita != null
			? draft.estimatedPerCapita
			: detail.estimatedPerCapita
		if (capita != null && capita !== '') netPayText = formatDraftMoney(capita)
	}

	const workTypeOptions = buildWorkTypeOptions(groups, {
		workType: workType && workType !== '待补充' ? workType : '',
		workLocation: workLocation && workLocation !== '待补充' ? workLocation : '',
		workDays,
		workerCount,
		dailyWage,
		settlementMode,
		netPayText
	})
	const needSelectWorkType = workTypeOptions.length > 1
	// 多工种时汇总文案不直接当作已选工种
	if (needSelectWorkType) {
		workType = '请选择工种'
	} else if (workTypeOptions.length === 1) {
		workType = workTypeOptions[0].workType
	} else {
		workType = workType && workType !== '待补充' ? workType : '待确认'
	}

	return {
		draftId,
		orderId: options.orderId
			|| (draft && draft.orderId)
			|| detail.orderId
			|| null,
		qrToken: options.qrToken
			|| (draft && draft.qrToken)
			|| detail.qrToken
			|| detail.qr_token
			|| null,
		scene: options.scene
			|| options.qrToken
			|| (draft && (draft.qrToken || draft.scene))
			|| detail.qrToken
			|| detail.qr_token
			|| null,
		batchId,
		title,
		workType,
		workLocation: workLocation && workLocation !== '待补充' ? workLocation : '待确认',
		workDays: workDays != null ? Number(workDays) : null,
		workerCount: workerCount != null ? Number(workerCount) : null,
		dailyWage: dailyWage != null ? Number(dailyWage) : null,
		settlementMode,
		settlementModeLabel: formatSettlementMode(settlementMode),
		enterpriseName: options.enterpriseName || '',
		schemeTitle: (scheme && scheme.title) || options.schemeTitle || '',
		netPayText: netPayText || '—',
		hint: '最终到手以实际出勤与结算为准',
		workTypeOptions,
		needSelectWorkType,
		selectedWorkType: needSelectWorkType ? '' : (workTypeOptions[0] ? workTypeOptions[0].workType : (workType !== '请选择工种' && workType !== '待确认' ? workType : ''))
	}
}

/**
 * GET /drafts/{id} 详情 → 落地页展示
 */
export function buildJobOfferFromDraftDetail(detail, options = {}) {
	if (!detail) return null
	const card = mapDraftDetailToCard(detail)
	return buildJobOfferFromDraft(card, {
		draftId: detail.id,
		batchId: options.batchId || card.draftNo || '',
		scheme: options.scheme,
		schemeTitle: options.schemeTitle,
		enterpriseName: options.enterpriseName,
		netPayText: options.netPayText,
		netPay: options.netPay,
		orderId: options.orderId || '',
		qrToken: options.qrToken || card.qrToken || '',
		scene: options.scene || options.qrToken || card.qrToken || options.orderId || ''
	})
}

export function saveJobOffer(offer) {
	if (!offer || offer.draftId == null) return
	try {
		uni.setStorageSync(OFFER_STORAGE_PREFIX + 'draft_' + offer.draftId, offer)
		uni.setStorageSync(OFFER_STORAGE_PREFIX + 'latest', offer)
	} catch (e) {
		// ignore storage quota
	}
}

export function loadJobOffer(draftId) {
	try {
		if (draftId != null && draftId !== '') {
			const byDraft = uni.getStorageSync(OFFER_STORAGE_PREFIX + 'draft_' + draftId)
			if (byDraft) return byDraft
		}
		return uni.getStorageSync(OFFER_STORAGE_PREFIX + 'latest') || null
	} catch (e) {
		return null
	}
}

/**
 * 解析落地页 / 分享用的 scene（优先 URL scene，其次确认后的订单号）
 */
export function resolveSceneFromQuery(query = {}) {
	if (query.scene != null && query.scene !== '') {
		let raw = String(query.scene).trim()
		try {
			raw = decodeURIComponent(raw)
		} catch (e) {
			// ignore
		}
		return raw
	}
	if (query.orderId != null && query.orderId !== '') {
		const oid = String(query.orderId).trim()
		if (oid.indexOf(JOB_OFFER_SCENE_PREFIX) === 0) return oid
		if (/^\d+$/.test(oid)) return buildJobOfferScene(oid)
		return oid
	}
	if (query.draftId != null && query.draftId !== '') {
		return buildJobOfferScene(query.draftId)
	}
	return ''
}

/**
 * 解析落地页 query 中的草稿 ID
 * 优先 scene=ord_{id}，兼容旧 draftId=
 */
export function resolveDraftIdFromQuery(query = {}) {
	if (query.scene != null && query.scene !== '') {
		const fromScene = parseDraftIdFromScene(query.scene)
		if (fromScene != null) return fromScene
	}
	if (query.draftId == null || query.draftId === '') return null
	const n = Number(query.draftId)
	return Number.isNaN(n) ? null : n
}

/**
 * 从页面 query 解析
 */
export function parseJobOfferQuery(query = {}) {
	const draftId = resolveDraftIdFromQuery(query)
	if (draftId == null && !query.title) return null

	return {
		draftId,
		title: query.title ? decodeURIComponent(query.title) : '',
		workType: query.workType ? decodeURIComponent(query.workType) : '',
		workLocation: query.workLocation ? decodeURIComponent(query.workLocation) : '',
		workDays: query.workDays != null && query.workDays !== '' ? Number(query.workDays) : null,
		workerCount: query.workerCount != null && query.workerCount !== '' ? Number(query.workerCount) : null,
		dailyWage: query.dailyWage != null && query.dailyWage !== '' ? Number(query.dailyWage) : null,
		settlementMode: query.settlementMode || '',
		settlementModeLabel: formatSettlementMode(query.settlementMode),
		enterpriseName: query.enterpriseName ? decodeURIComponent(query.enterpriseName) : '',
		schemeTitle: query.schemeTitle ? decodeURIComponent(query.schemeTitle) : '',
		netPayText: query.netPayText
			? decodeURIComponent(query.netPayText)
			: (query.netPay ? formatDraftMoney(query.netPay) : ''),
		hint: '最终到手以实际出勤与结算为准'
	}
}

export function mergeJobOffer(...parts) {
	const base = {
		draftId: null,
		orderId: null,
		qrToken: '',
		scene: '',
		batchId: '',
		title: '临时用工邀请',
		workType: '待确认',
		workLocation: '待确认',
		workDays: null,
		workerCount: null,
		dailyWage: null,
		settlementMode: '',
		settlementModeLabel: '待确认',
		enterpriseName: '',
		schemeTitle: '',
		netPayText: '—',
		hint: '最终到手以实际出勤与结算为准',
		workTypeOptions: [],
		needSelectWorkType: false,
		selectedWorkType: ''
	}
	for (let i = 0; i < parts.length; i++) {
		const part = parts[i]
		if (!part || typeof part !== 'object') continue
		Object.keys(part).forEach((key) => {
			const val = part[key]
			if (key === 'workTypeOptions') {
				if (Array.isArray(val) && val.length) base[key] = val
				return
			}
			if (key === 'needSelectWorkType') {
				base[key] = !!val
				return
			}
			if (val != null && val !== '') base[key] = val
		})
	}
	if (!Array.isArray(base.workTypeOptions)) base.workTypeOptions = []
	if (base.needSelectWorkType && base.workTypeOptions.length <= 1) {
		base.needSelectWorkType = base.workTypeOptions.length > 1
	}
	return base
}

/** 演示数据：无缓存/无参数时兜底 */
export function getDemoJobOffer(draftId) {
	const workTypeOptions = buildWorkTypeOptions([
		{
			groupId: 'grp_01',
			workType: '仓库搬运',
			workLocation: '浦东新区某某仓库',
			workerCount: 6,
			workDays: 3,
			settlementMode: 'daily',
			unitAmount: 350
		},
		{
			groupId: 'grp_02',
			workType: '分拣打包',
			workLocation: '浦东新区某某仓库',
			workerCount: 4,
			workDays: 3,
			settlementMode: 'daily',
			unitAmount: 320
		}
	], {})
	return {
		draftId: draftId != null ? draftId : null,
		batchId: draftId != null ? `draft_${draftId}` : 'draft_demo',
		title: '仓库短驳搬运',
		workType: '请选择工种',
		workLocation: '浦东新区某某仓库',
		workDays: 3,
		workerCount: 10,
		dailyWage: null,
		settlementMode: 'daily',
		settlementModeLabel: '日结',
		enterpriseName: '某某科技有限公司',
		schemeTitle: '灵活用工模式',
		netPayText: '—',
		hint: '最终到手以实际出勤与结算为准',
		workTypeOptions,
		needSelectWorkType: true,
		selectedWorkType: ''
	}
}

export function buildJobOfferPageUrl(offer) {
	const scene = resolveJobOfferScene(offer)
	if (!scene) return '/pages/worker/job-offer'
	// 参数名仍为 scene，值为 qrToken
	return `/pages/worker/job-offer?scene=${encodeURIComponent(scene)}`
}

/** 微信分享用工邀请卡片封面 */
export const JOB_OFFER_SHARE_IMAGE = '/static/images/job.jpg'

/** 分享 scene 前缀：ord_{id}（仅兜底） */
export const JOB_OFFER_SCENE_PREFIX = 'ord_'

/**
 * 生成分享 scene，如 id=7 → ord_7
 */
export function buildJobOfferScene(id) {
	if (id === '' || id == null) return ''
	return `${JOB_OFFER_SCENE_PREFIX}${id}`
}

/**
 * 从 scene 解析数字 ID：ord_7 → 7（仅用于兼容缓存键）
 */
export function parseDraftIdFromScene(scene) {
	if (scene == null || scene === '') return null
	let raw = String(scene)
	try {
		raw = decodeURIComponent(raw)
	} catch (e) {
		// ignore
	}
	raw = raw.trim()
	if (!raw) return null
	if (raw.indexOf(JOB_OFFER_SCENE_PREFIX) === 0) {
		const n = Number(raw.slice(JOB_OFFER_SCENE_PREFIX.length))
		return Number.isNaN(n) ? null : n
	}
	const n = Number(raw)
	return Number.isNaN(n) ? null : n
}

/**
 * 组装分享 / 公开查询用的 scene 值
 * 优先 qrToken（与小程序码 / 公开接口一致）；参数名仍为 scene
 */
export function resolveJobOfferScene(offer) {
	if (!offer || typeof offer !== 'object') return ''
	const candidates = [
		offer.qrToken,
		offer.qr_token,
		offer.scene,
		offer.orderNo,
		offer.orderId
	]
	for (let i = 0; i < candidates.length; i++) {
		const c = candidates[i]
		if (c == null || c === '') continue
		const s = String(c).trim()
		if (!s) continue
		if (/^\d+$/.test(s)) return buildJobOfferScene(s)
		return s
	}
	if (offer.draftId != null && offer.draftId !== '') {
		return buildJobOfferScene(offer.draftId)
	}
	return ''
}

/**
 * 用工邀请分享给好友的卡片配置
 * @param {{ draftId?: string|number, orderId?: string, scene?: string, qrToken?: string }} [offer]
 */
export function buildJobOfferShareMessage(offer) {
	return {
		title: '用工邀请',
		path: buildJobOfferPageUrl(offer),
		imageUrl: JOB_OFFER_SHARE_IMAGE
	}
}
