/** 企业认证提交表单本地缓存（明文，覆盖写） */
const STORAGE_KEY = 'fe_enterprise_cert_form'

/**
 * @param {object} form
 * @returns {object|null}
 */
export function normalizeEnterpriseCertForm(form = {}) {
	const name = String(form.name || '').trim()
	const creditCode = String(form.creditCode || form.credit_code || '').trim().toUpperCase()
	const legalPersonName = String(
		form.legalPersonName || form.legalPerson || form.legal_person || form.contactName || ''
	).trim()
	const legalPersonIdCard = String(
		form.legalPersonIdCard || form.legal_person_id_card || ''
	).trim().toUpperCase()
	const legalPersonMobile = String(
		form.legalPersonMobile || form.contactMobile || form.contact_mobile || ''
	).trim()
	const businessAddress = String(
		form.businessAddress || form.registeredAddress || form.registered_address || ''
	).trim()
	const hasAny = !!(
		name || creditCode || legalPersonName || legalPersonIdCard || legalPersonMobile || businessAddress
	)
	if (!hasAny) return null
	return {
		name,
		creditCode,
		legalPersonName,
		legalPersonIdCard,
		legalPersonMobile,
		businessAddress
	}
}

/** 保存（整份替换） */
export function saveEnterpriseCertForm(form) {
	const data = normalizeEnterpriseCertForm(form)
	if (!data) return false
	try {
		uni.setStorageSync(STORAGE_KEY, {
			...data,
			savedAt: Date.now()
		})
		return true
	} catch (e) {
		return false
	}
}

/** 读取上次提交的认证表单 */
export function loadEnterpriseCertForm() {
	try {
		const raw = uni.getStorageSync(STORAGE_KEY)
		if (!raw || typeof raw !== 'object') return null
		return normalizeEnterpriseCertForm(raw)
	} catch (e) {
		return null
	}
}

export function clearEnterpriseCertForm() {
	try {
		uni.removeStorageSync(STORAGE_KEY)
	} catch (e) {}
}
