/**
 * 办理流程引导面板：状态徽标（当前 / 待开始 / 已完成 / 已跳过）
 * 嵌在进度卡 swiper 步骤内，后续其他流程步骤可复用
 */

export const PROCESS_STATUS = {
	CURRENT: 'current',
	PENDING: 'pending',
	DONE: 'done',
	SKIPPED: 'skipped'
}

const PROCESS_STATUS_LABEL = {
	current: '当前',
	pending: '待开始',
	done: '已完成',
	skipped: '已跳过'
}

const CERT_SKIP_STORAGE_KEY = 'fe_enterprise_cert_skipped'

export function isEnterpriseCertSkipped() {
	try {
		return !!uni.getStorageSync(CERT_SKIP_STORAGE_KEY)
	} catch (e) {
		return false
	}
}

export function markEnterpriseCertSkipped() {
	try {
		uni.setStorageSync(CERT_SKIP_STORAGE_KEY, '1')
	} catch (e) {
		// ignore
	}
}

export function clearEnterpriseCertSkipped() {
	try {
		uni.removeStorageSync(CERT_SKIP_STORAGE_KEY)
	} catch (e) {
		// ignore
	}
}

/**
 * 步骤 status → 流程卡状态徽标
 * active→当前，pending→待开始，done→已完成
 */
export function mapStepStatusToProcessStatus(stepStatus, options = {}) {
	if (options.skipped) return PROCESS_STATUS.SKIPPED
	const s = stepStatus || 'pending'
	if (s === 'done') return PROCESS_STATUS.DONE
	if (s === 'active') return PROCESS_STATUS.CURRENT
	return PROCESS_STATUS.PENDING
}

/**
 * @param {string} status current | pending | done | skipped
 */
export function buildProcessStatusMeta(status) {
	const key = PROCESS_STATUS_LABEL[status] ? status : PROCESS_STATUS.PENDING
	return {
		processStatus: key,
		processStatusLabel: PROCESS_STATUS_LABEL[key],
		processStatusClass: `fe-process-status fe-process-status--${key}`
	}
}

/** 主按钮 class（禁用态预计算，供小程序 :class 绑定） */
function buildPrimaryBtnClass(disabled) {
	return disabled
		? 'fe-biz-btn fe-biz-btn--primary fe-biz-btn--disabled'
		: 'fe-biz-btn fe-biz-btn--primary'
}

function buildSecondaryBtnClass(disabled) {
	return disabled ? 'fe-biz-btn fe-biz-btn--disabled' : 'fe-biz-btn'
}

/**
 * 串行步骤入口：锁定或待开始不可点；「当前 / 已完成」可进弹层（完成态弹层内再禁操作）
 */
function isSequentialActionDisabled(processStatus, actionLocked) {
	if (actionLocked) return true
	if (processStatus === PROCESS_STATUS.PENDING) return true
	return false
}

export function isEnterpriseAuthStep(step) {
	if (!step) return false
	const key = String(step.key || step.stepCode || step.step_code || '').toLowerCase()
	const title = String(step.title || '')
	if (key === 'enterprise_auth' || key === 'enterprise_cert') return true
	if (title.indexOf('企业认证') >= 0) return true
	return false
}

/** 临时工招聘（第三方匹配，非扫码登记） */
export function isWorkerRecruitmentStep(step) {
	if (!step) return false
	const key = String(step.key || step.stepCode || step.step_code || '').toLowerCase()
	const title = String(step.title || '')
	if (key === 'worker_recruitment' || key === 'recruitment' || key === 'recruit') return true
	if (title.indexOf('临时工招聘') >= 0 || title.indexOf('工人招聘') >= 0) return true
	// 标题含「招聘」但不含「登记」
	if (title.indexOf('招聘') >= 0 && title.indexOf('登记') < 0) return true
	return false
}

/** 人员登记 / 扫码登记（二维码分享） */
export function isRegistrationStep(step) {
	if (!step) return false
	if (isWorkerRecruitmentStep(step)) return false
	const key = String(step.key || step.stepCode || step.step_code || '').toLowerCase()
	const title = String(step.title || '')
	if (
		key === 'registration'
		|| key === 'worker_registration'
		|| key === 'scan_register'
	) return true
	if (title.indexOf('人员登记') >= 0 || title.indexOf('扫码登记') >= 0) return true
	return false
}

/** 用工到位节点：人员登记 或 临时工招聘（门禁共用） */
export function isStaffingStep(step) {
	return isRegistrationStep(step) || isWorkerRecruitmentStep(step)
}

/** 任务发布（兼容开始用工 / task_publish） */
export function isTaskPublishStep(step) {
	if (!step) return false
	const key = String(step.key || step.stepCode || step.step_code || '').toLowerCase()
	const title = String(step.title || '')
	if (key === 'task_publish' || key === 'work_started' || key === 'work') return true
	if (title.indexOf('任务发布') >= 0 || title.indexOf('开始用工') >= 0) return true
	return false
}

/**
 * 结算打款引导面板节点（优先待结算；已支付单独节点不重复出卡）
 */
export function isSettlementStep(step) {
	if (!step) return false
	const key = String(step.key || step.stepCode || step.step_code || '').toLowerCase()
	const title = String(step.title || '')
	if (key === 'settlement_paid') return false
	if (title.indexOf('已支付') >= 0) return false
	if (key === 'settlement' || key === 'settlement_pending' || key === 'settle') return true
	if (title.indexOf('结算打款') >= 0 || title.indexOf('待结算') >= 0) return true
	return false
}

/** 开票归档（办结 / invoice_archive / completed） */
export function isInvoiceArchiveStep(step) {
	if (!step) return false
	const key = String(step.key || step.stepCode || step.step_code || '').toLowerCase()
	const title = String(step.title || '')
	if (
		key === 'invoice_archive'
		|| key === 'completed'
		|| key === 'invoice'
		|| key === 'archive'
	) return true
	if (
		title.indexOf('开票归档') >= 0
		|| title.indexOf('开票') >= 0
		|| title.indexOf('办结') >= 0
	) return true
	return false
}

/**
 * 企业认证步骤面板（嵌在进度卡 swiper 内）
 * @param {string} stepStatus done|active|pending
 * @param {{ skipped?: boolean }} [options]
 */
export function buildEnterpriseCertProcessPanel(stepStatus, options = {}) {
	const processStatus = mapStepStatusToProcessStatus(stepStatus, options)
	const statusMeta = buildProcessStatusMeta(processStatus)
	const isDone = processStatus === PROCESS_STATUS.DONE
	// 可与人员登记并行：未完成即可认证；已完成只读查看；已跳过仍可回来认证
	const showActions = true
	return {
		cardType: 'enterprise_cert',
		title: '企业认证',
		subtitle: '上传营业执照，完成实名认证',
		iconText: '🏢',
		bullets: [
			{ msgKey: 'b1', text: '上传营业执照照片（自动识别）' },
			{ msgKey: 'b2', text: '或输入统一社会信用代码查询' },
			{ msgKey: 'b3', text: '法人身份验证' }
		],
		showActions,
		showSkip: !isDone && processStatus !== PROCESS_STATUS.SKIPPED,
		primaryLabel: isDone ? '查看认证' : '去认证',
		secondaryLabel: '跳过',
		readonly: isDone,
		actionLocked: false,
		actionDisabled: false,
		primaryBtnClass: buildPrimaryBtnClass(false),
		secondaryBtnClass: buildSecondaryBtnClass(false),
		...statusMeta
	}
}

/**
 * 任务发布步骤面板
 * @param {string} stepStatus done|active|pending
 * @param {{ actionLocked?: boolean }} [options]
 */
export function buildTaskPublishProcessPanel(stepStatus, options = {}) {
	const processStatus = mapStepStatusToProcessStatus(stepStatus)
	const statusMeta = buildProcessStatusMeta(processStatus)
	const actionLocked = options.actionLocked === true
	const actionDisabled = isSequentialActionDisabled(processStatus, actionLocked)
	const viewOnly = processStatus === PROCESS_STATUS.DONE
	return {
		cardType: 'task_publish',
		title: '任务发布',
		subtitle: '确认人员到位后发布用工任务',
		iconText: '✈',
		bullets: [
			{ msgKey: 'b1', text: '确认登记人数达标' },
			{ msgKey: 'b2', text: '发布任务要求和时间' },
			{ msgKey: 'b3', text: '开启考勤打卡' }
		],
		showActions: true,
		actionLocked,
		actionDisabled,
		viewOnly,
		lockHint: '请先完成企业认证与人员登记',
		primaryLabel: viewOnly ? '查看发布' : '去发布',
		primaryIcon: '✈',
		primaryBtnClass: buildPrimaryBtnClass(actionDisabled),
		...statusMeta
	}
}

/**
 * 结算打款步骤面板
 * @param {string} stepStatus done|active|pending
 * @param {{ actionLocked?: boolean }} [options]
 */
export function buildSettlementProcessPanel(stepStatus, options = {}) {
	const processStatus = mapStepStatusToProcessStatus(stepStatus)
	const statusMeta = buildProcessStatusMeta(processStatus)
	const actionLocked = options.actionLocked === true
	const actionDisabled = isSequentialActionDisabled(processStatus, actionLocked)
	const viewOnly = processStatus === PROCESS_STATUS.DONE
	return {
		cardType: 'settlement',
		title: '结算打款',
		subtitle: '用工结束后确认考勤并结算',
		iconText: '▤',
		bullets: [
			{ msgKey: 'b1', text: '核对考勤数据' },
			{ msgKey: 'b2', text: '确认结算金额' },
			{ msgKey: 'b3', text: '一键打款到工人账户' }
		],
		showActions: true,
		actionLocked,
		actionDisabled,
		viewOnly,
		lockHint: '请先完成任务发布',
		primaryLabel: '查看结算单',
		primaryIcon: '◎',
		primaryBtnClass: buildPrimaryBtnClass(actionDisabled),
		...statusMeta
	}
}

/**
 * 开票归档步骤面板
 * @param {string} stepStatus done|active|pending
 * @param {{ actionLocked?: boolean }} [options]
 */
export function buildInvoiceArchiveProcessPanel(stepStatus, options = {}) {
	const processStatus = mapStepStatusToProcessStatus(stepStatus)
	const statusMeta = buildProcessStatusMeta(processStatus)
	const actionLocked = options.actionLocked === true
	const actionDisabled = isSequentialActionDisabled(processStatus, actionLocked)
	const viewOnly = processStatus === PROCESS_STATUS.DONE
	return {
		cardType: 'invoice_archive',
		title: '开票归档',
		subtitle: '申请发票，下载完税证明',
		iconText: '📄',
		bullets: [
			{ msgKey: 'b1', text: '申请增值税专用发票' },
			{ msgKey: 'b2', text: '下载完税证明' },
			{ msgKey: 'b3', text: '导出合规证据链' }
		],
		showActions: true,
		actionLocked,
		actionDisabled,
		viewOnly,
		lockHint: '请先完成结算打款',
		primaryLabel: viewOnly ? '查看开票' : '去开票',
		primaryIcon: '📄',
		primaryBtnClass: buildPrimaryBtnClass(actionDisabled),
		...statusMeta
	}
}

/**
 * 人员登记二维码面板（对应原独立二维码卡）
 * @param {string} stepStatus
 * @param {{
 *   subtitle?: string,
 *   hint?: string,
 *   qrCodeUrl?: string,
 *   qrImageUrl?: string,
 *   qrToken?: string,
 *   registered?: number,
 *   total?: number,
 *   highlight?: string,
 *   actionLocked?: boolean
 * }} [qr]
 */
export function buildRegistrationQrProcessPanel(stepStatus, qr = {}) {
	const processStatus = mapStepStatusToProcessStatus(stepStatus)
	const statusMeta = buildProcessStatusMeta(processStatus)
	const registered = qr.registered != null ? Number(qr.registered) : 0
	const total = qr.total != null ? Number(qr.total) : 0
	let progressText = qr.highlight || ''
	if (!progressText && total > 0) progressText = `已登记 ${registered}/${total}`
	// 以门禁 actionLocked 为准：方案确认后即使接口 pending 也可操作
	const actionLocked = qr.actionLocked === true
	const actionDisabled = actionLocked
	return {
		cardType: 'registration_qr',
		title: '人员登记',
		subtitle: qr.subtitle || '分享给临时工扫码即可登记',
		iconText: '▦',
		hint: qr.hint || '分享给临时工扫码即可登记',
		qrCodeUrl: qr.qrCodeUrl || '',
		qrImageUrl: qr.qrImageUrl || '',
		qrToken: qr.qrToken || '',
		registered,
		total,
		progressText,
		showActions: true,
		actionLocked,
		actionDisabled,
		lockHint: '请先完成方案确认',
		primaryLabel: '查看 / 分享',
		secondaryLabel: '查看进度',
		primaryBtnClass: buildPrimaryBtnClass(actionDisabled),
		secondaryBtnClass: buildSecondaryBtnClass(actionDisabled),
		...statusMeta
	}
}

/**
 * 临时工招聘引导面板（第三方匹配，非二维码）
 * @param {string} stepStatus done|active|pending
 * @param {{
 *   registered?: number,
 *   total?: number,
 *   highlight?: string,
 *   actionLocked?: boolean
 * }} [options]
 */
export function buildWorkerRecruitmentProcessPanel(stepStatus, options = {}) {
	const processStatus = mapStepStatusToProcessStatus(stepStatus)
	const statusMeta = buildProcessStatusMeta(processStatus)
	const registered = options.registered != null ? Number(options.registered) : 0
	const total = options.total != null ? Number(options.total) : 0
	const progressText = `已登记 ${registered}/${total || 0}`
	// 以门禁 actionLocked 为准：方案确认后即使接口 pending 也可操作
	const actionLocked = options.actionLocked === true
	const actionDisabled = actionLocked
	const viewOnly = processStatus === PROCESS_STATUS.DONE
	return {
		cardType: 'worker_recruitment',
		title: '临时工招聘',
		subtitle: '从第三方平台匹配临时工',
		iconText: '🔍',
		bullets: [
			{ msgKey: 'b1', text: '调用第三方人力资源接口' },
			{ msgKey: 'b2', text: '匹配符合条件的临时工' },
			{ msgKey: 'b3', text: '选择并确认临时工' }
		],
		registered,
		total,
		progressText,
		showActions: true,
		actionLocked,
		actionDisabled,
		viewOnly,
		lockHint: '请先完成方案确认',
		primaryLabel: viewOnly ? '查看招聘' : '去招聘',
		primaryIcon: '🔍',
		primaryBtnClass: buildPrimaryBtnClass(actionDisabled),
		...statusMeta
	}
}

/**
 * 同步步骤上的流程面板状态（保留二维码等业务字段）
 */
export function syncStepProcessPanel(step, stepStatus, options = {}) {
	if (!step || !step.processPanel) return
	const prev = step.processPanel
	const type = prev.cardType
	let panel = null
	if (type === 'registration_qr') {
		panel = buildRegistrationQrProcessPanel(stepStatus || step.status, {
			subtitle: prev.subtitle,
			hint: prev.hint,
			qrCodeUrl: prev.qrCodeUrl,
			qrImageUrl: prev.qrImageUrl,
			qrToken: prev.qrToken,
			registered: prev.registered,
			total: prev.total,
			highlight: prev.progressText,
			actionLocked: prev.actionLocked === true
		})
	} else if (type === 'worker_recruitment') {
		panel = buildWorkerRecruitmentProcessPanel(stepStatus || step.status, {
			registered: prev.registered,
			total: prev.total,
			highlight: prev.progressText,
			actionLocked: prev.actionLocked === true
		})
	} else if (type === 'task_publish') {
		panel = buildTaskPublishProcessPanel(stepStatus || step.status, {
			actionLocked: prev.actionLocked === true
		})
	} else if (type === 'settlement') {
		panel = buildSettlementProcessPanel(stepStatus || step.status, {
			actionLocked: prev.actionLocked === true
		})
	} else if (type === 'invoice_archive') {
		panel = buildInvoiceArchiveProcessPanel(stepStatus || step.status, {
			actionLocked: prev.actionLocked === true
		})
	} else {
		panel = buildEnterpriseCertProcessPanel(stepStatus || step.status, options)
	}
	Object.keys(panel).forEach((k) => {
		step.processPanel[k] = panel[k]
	})
	step.hasProcessPanel = true
}
