import { formatDraftMoney, formatSettlementMode, mapDraftDetailToCard } 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
}

/**
 * 用工草稿 + 确认结果 → 扫码落地页展示数据
 */
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 workType = (draft && draft.workType) || detail.workType || ''
	const workLocation = (draft && draft.workLocation) || detail.workLocation || ''
	const workDays = draft && draft.workDays != null ? draft.workDays : detail.workDays
	const workerCount = draft && draft.workerCount != null ? draft.workerCount : detail.workerCount
	const dailyWage = draft && draft.dailyWage != null ? draft.dailyWage : detail.dailyWage
	const settlementMode = (draft && draft.settlementMode) || detail.settlementMode || ''
	const title = (draft && draft.title && draft.title !== '用工草稿')
		? draft.title
		: ([
			workLocation && workLocation !== '待补充' ? workLocation : '',
			workType && workType !== '待补充' ? 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)
	}

	return {
		draftId,
		batchId,
		title,
		workType: workType && workType !== '待补充' ? 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: '最终到手以实际出勤与结算为准'
	}
}

/**
 * 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
	})
}

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
	}
}

/**
 * 解析落地页 query 中的草稿 ID
 */
export function resolveDraftIdFromQuery(query = {}) {
	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,
		batchId: '',
		title: '临时用工邀请',
		workType: '待确认',
		workLocation: '待确认',
		workDays: null,
		workerCount: null,
		dailyWage: null,
		settlementMode: '',
		settlementModeLabel: '待确认',
		enterpriseName: '',
		schemeTitle: '',
		netPayText: '—',
		hint: '最终到手以实际出勤与结算为准'
	}
	for (let i = 0; i < parts.length; i++) {
		const part = parts[i]
		if (!part || typeof part !== 'object') continue
		Object.keys(part).forEach((key) => {
			if (key === 'orderId') return
			const val = part[key]
			if (val != null && val !== '') base[key] = val
		})
	}
	return base
}

/** 演示数据：无缓存/无参数时兜底 */
export function getDemoJobOffer(draftId) {
	return {
		draftId: draftId != null ? draftId : null,
		batchId: draftId != null ? `draft_${draftId}` : 'draft_demo',
		title: '仓库短驳搬运',
		workType: '仓库搬运',
		workLocation: '浦东新区某某仓库',
		workDays: 3,
		workerCount: 10,
		dailyWage: 350,
		settlementMode: 'daily',
		settlementModeLabel: '日结',
		enterpriseName: '某某科技有限公司',
		schemeTitle: '灵活用工模式',
		netPayText: '¥1,050.00',
		hint: '最终到手以实际出勤与结算为准'
	}
}

export function buildJobOfferPageUrl(offer) {
	const draftId = offer && offer.draftId != null ? offer.draftId : ''
	if (draftId === '' || draftId == null) return '/pages/worker/job-offer'
	return `/pages/worker/job-offer?draftId=${encodeURIComponent(draftId)}`
}

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

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