const STATUS_LABELS = {
  complete: '完整',
  available: '可用',
  partial: '部分可用',
  unavailable: '不可用',
  active: '生效中',
  trialing: '试用中',
  past_due: '逾期待处理',
  suspended: '已暂停',
  canceled: '已取消',
  expired: '已过期',
  draft: '草稿',
  retired: '已退役',
  approaching: '接近配额',
  exhausted: '配额耗尽',
  unlimited: '不限量',
  inactive: '当前不可用',
  feasible: '区间可行',
  insufficient_value: '价值不足',
  cost_only: '仅成本可用'
}

const PRICING_MODEL_LABELS = {
  hybrid: '混合定价（基础订阅 + 封顶成功费）',
  subscription: '订阅制',
  pilot_collecting: '试点采集证据',
  optimize_unit_economics: '先优化单位经济性'
}

export const COMMERCIAL_ACTIONS = Object.freeze({
  createPlan: { label: '创建套餐版本', family: 'configuration', confirm: '确认创建套餐版本' },
  activatePlan: { label: '激活套餐版本', family: 'activation', confirm: '确认激活套餐版本' },
  createSubscription: { label: '创建订阅快照', family: 'configuration', confirm: '确认创建并启用订阅' },
  activateSubscription: { label: '重新激活订阅', family: 'activation', confirm: '确认重新激活订阅' },
  transitionSubscription: { label: '变更订阅状态', family: 'activation', confirm: '确认变更订阅状态' },
  upsertEntitlement: { label: '配置权益版本', family: 'configuration', confirm: '确认保存权益版本' },
  activateEntitlement: { label: '激活权益版本', family: 'activation', confirm: '确认激活权益版本' },
  recordUsage: { label: '记录用量事件', family: 'metering', confirm: '确认写入不可变用量事件' },
  recordCost: { label: '记录成本事件', family: 'metering', confirm: '确认写入不可变成本事件' }
})

export function statusLabel(status) {
  const normalized = String(status || '').trim()
  return STATUS_LABELS[normalized] || normalized || '未知'
}

export function classifyCommercialAccountState({ loading = false, error = null, account = null } = {}) {
  if (loading && !account) return 'loading'
  if (error?.status === 401 || error?.status === 403) return 'permission'
  if (error && !account) return 'error'
  if (!account || account.dataStatus === 'unavailable') return 'unavailable'
  if (account.dataStatus === 'partial') return 'partial'
  return 'ready'
}

function normalizeCurrency(value) {
  const currency = String(value || '').trim().toUpperCase()
  return /^[A-Z]{3}$/u.test(currency) ? currency : ''
}

function finiteNumber(value) {
  if (value === null || value === undefined || value === '') return null
  const parsed = Number(value)
  return Number.isFinite(parsed) ? parsed : null
}

export function formatCurrencyAmount(value, currency, locale = 'zh-CN') {
  const amount = finiteNumber(value)
  const normalizedCurrency = normalizeCurrency(currency)
  if (amount === null || !normalizedCurrency) return '—'
  try {
    return new Intl.NumberFormat(locale, {
      style: 'currency',
      currency: normalizedCurrency,
      minimumFractionDigits: 0,
      maximumFractionDigits: 4
    }).format(amount)
  } catch {
    return `${normalizedCurrency} ${amount.toLocaleString(locale)}`
  }
}

export function formatRatio(value, locale = 'zh-CN') {
  const ratio = finiteNumber(value)
  if (ratio === null) return '—'
  return new Intl.NumberFormat(locale, {
    style: 'percent',
    minimumFractionDigits: 1,
    maximumFractionDigits: 2
  }).format(ratio)
}

export function formatMetricValues(metric = {}) {
  if (metric.status === 'unavailable') return []
  return (Array.isArray(metric.values) ? metric.values : [])
    .map((item) => ({
      currency: normalizeCurrency(item.currency),
      amount: finiteNumber(item.amount),
      displayValue: formatCurrencyAmount(item.amount, item.currency),
      basis: String(item.basis || '')
    }))
    .filter((item) => item.currency && item.amount !== null)
}

export function formatMetricRatios(metric = {}) {
  if (metric.status === 'unavailable') return []
  return (Array.isArray(metric.ratios) ? metric.ratios : [])
    .map((item) => ({
      currency: normalizeCurrency(item.currency),
      ratio: finiteNumber(item.ratio),
      displayValue: formatRatio(item.ratio),
      numeratorLabel: formatCurrencyAmount(item.numerator, item.currency),
      denominatorLabel: formatCurrencyAmount(item.denominator, item.currency)
    }))
    .filter((item) => item.currency && item.ratio !== null)
}

function metricCard(metric, category) {
  const normalized = metric && typeof metric === 'object' ? metric : {}
  const values = formatMetricValues(normalized)
  const ratios = formatMetricRatios(normalized)
  const status = ['available', 'partial', 'unavailable'].includes(normalized.status)
    ? normalized.status
    : 'unavailable'
  return {
    key: String(normalized.key || category),
    label: String(normalized.label || '数据不可用'),
    category,
    status,
    statusLabel: statusLabel(status),
    values,
    ratios,
    displayValue: ratios[0]?.displayValue || values[0]?.displayValue || '不可用',
    multiCurrency: new Set([...values, ...ratios].map((item) => item.currency)).size > 1,
    reason: String(normalized.reason || '后端未返回该指标的事实口径。'),
    requiredInputs: Array.isArray(normalized.requiredInputs) ? normalized.requiredInputs : [],
    notes: Array.isArray(normalized.notes) ? normalized.notes : []
  }
}

export function buildCommercialValueLedgers(analytics = null) {
  if (!analytics) {
    return { customer: [], platform: [] }
  }
  return {
    customer: [
      metricCard(analytics.verifiedCashSavings, 'verifiedCashSavings'),
      metricCard(analytics.customerCharges, 'customerCharges'),
      metricCard(analytics.customerRoi, 'customerRoi'),
      metricCard(analytics.customerLaborValue, 'customerLaborValue')
    ],
    platform: [
      metricCard(analytics.internalCosts, 'internalCosts'),
      metricCard(analytics.contributionMargin, 'contributionMargin')
    ]
  }
}

export function buildQuotaRows(account = null) {
  return (Array.isArray(account?.quotas) ? account.quotas : []).map((quota) => {
    const entitlement = quota.entitlement || {}
    const used = finiteNumber(quota.usedQuantity)
    const hardRemaining = finiteNumber(quota.hardLimitRemaining)
    return {
      id: String(entitlement.id || ''),
      key: String(entitlement.entitlementKey || entitlement.metricKey || ''),
      metricKey: String(entitlement.metricKey || ''),
      unit: String(entitlement.unit || '次'),
      type: String(entitlement.entitlementType || ''),
      status: String(quota.status || 'inactive'),
      statusLabel: statusLabel(quota.status),
      usedLabel: used === null ? '不可用' : used.toLocaleString('zh-CN'),
      remainingLabel: quota.status === 'unlimited'
        ? '不限量'
        : hardRemaining === null
          ? '未配置硬上限'
          : hardRemaining.toLocaleString('zh-CN'),
      commerciallyAllowed: quota.commerciallyAllowed === true,
      reason: String(quota.reason || ''),
      version: Number(entitlement.version || 0)
    }
  })
}

export function createDefaultCommercialRange(now = new Date()) {
  const end = new Date(now)
  const start = new Date(now)
  start.setUTCDate(start.getUTCDate() - 90)
  const toInputDate = (value) => value.toISOString().slice(0, 10)
  return { start: toInputDate(start), end: toInputDate(end) }
}

export function buildAnalyticsWindow(range = {}) {
  const startText = String(range.start || '').trim()
  const endText = String(range.end || '').trim()
  if (!startText || !endText) throw new Error('请选择完整的分析开始与结束日期。')
  const start = new Date(`${startText}T00:00:00`)
  const end = new Date(`${endText}T23:59:59.999`)
  if (!Number.isFinite(start.getTime()) || !Number.isFinite(end.getTime()) || start >= end) {
    throw new Error('分析开始日期必须早于结束日期。')
  }
  if (end.getTime() - start.getTime() > 731 * 86_400_000) {
    throw new Error('单次商业分析时间范围不能超过 731 天。')
  }
  return { start: start.toISOString(), end: end.toISOString(), asOf: new Date().toISOString() }
}

function toLocalDateTimeInput(value) {
  const date = value instanceof Date ? value : new Date(value)
  if (!Number.isFinite(date.getTime())) return ''
  const pad = (item) => String(item).padStart(2, '0')
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`
}

export function createDefaultPricingScenarioForm(range = {}, now = new Date()) {
  const fallback = createDefaultCommercialRange(now)
  return {
    start: String(range.start || fallback.start),
    end: String(range.end || fallback.end),
    asOf: toLocalDateTimeInput(now),
    targetContributionMarginPercent: '65',
    maxVerifiedSavingsSharePercent: '25'
  }
}

function percentageRate(value, label, { allowZero = false, upperExclusive = false } = {}) {
  const percent = Number(value)
  const validLower = allowZero ? percent >= 0 : percent > 0
  const roundedRate = Number((percent / 100).toFixed(6))
  const validUpper = upperExclusive ? roundedRate < 0.95 : roundedRate <= 1
  if (!Number.isFinite(percent) || !validLower || !validUpper) {
    const range = upperExclusive ? '大于等于 0 且小于 95' : '大于 0 且不超过 100'
    throw new Error(`${label}必须${range}。`)
  }
  return roundedRate.toFixed(6).replace(/(?:\.0+|(?<decimal>\.\d*?)0+)$/u, '$<decimal>')
}

export function buildPricingScenarioPayload(form = {}) {
  const window = buildAnalyticsWindow({ start: form.start, end: form.end })
  const asOf = toExplicitTimezone(form.asOf, '证据截止时间')
  if (new Date(asOf).getTime() < new Date(window.start).getTime()) {
    throw new Error('证据截止时间不能早于定价分析开始时间。')
  }
  return {
    start: window.start,
    end: window.end,
    asOf,
    targetContributionMarginRate: percentageRate(
      form.targetContributionMarginPercent,
      '目标贡献毛利率',
      { allowZero: true, upperExclusive: true }
    ),
    maxVerifiedSavingsShare: percentageRate(
      form.maxVerifiedSavingsSharePercent,
      '最大价值分享比例'
    )
  }
}

function pricingMoneyLabel(value, currency) {
  return value === null || value === undefined
    ? '不可用'
    : formatCurrencyAmount(value, currency)
}

export function buildPricingScenarioView(result = null) {
  if (!result || typeof result !== 'object') return null
  const rows = (Array.isArray(result.scenarios) ? result.scenarios : []).map((item, index) => {
    const currency = normalizeCurrency(item.currency)
    const status = ['feasible', 'insufficient_value', 'cost_only', 'unavailable'].includes(item.status)
      ? item.status
      : 'unavailable'
    const missingInputs = []
    if (item.internalCost === null || item.internalCost === undefined) {
      missingInputs.push('同币种内部成本事实')
    }
    if (item.verifiedCashSavings === null || item.verifiedCashSavings === undefined) {
      missingInputs.push('同币种财务确认现金节省')
    }
    return {
      key: `${currency || 'unknown'}-${index}`,
      currency: currency || '未知币种',
      status,
      statusLabel: statusLabel(status),
      internalCostLabel: pricingMoneyLabel(item.internalCost, currency),
      verifiedCashSavingsLabel: pricingMoneyLabel(item.verifiedCashSavings, currency),
      minimumSustainableChargeLabel: pricingMoneyLabel(item.minimumSustainableCharge, currency),
      maximumValueAlignedChargeLabel: pricingMoneyLabel(item.maximumValueAlignedCharge, currency),
      maximumSuccessFeeLabel: pricingMoneyLabel(item.maximumSuccessFee, currency),
      customerRoiLabel: formatRatio(item.customerRoiAtMinimumCharge),
      contributionMarginLabel: formatRatio(item.contributionMarginAtValueCeiling),
      missingInputs,
      reason: String(item.reason || '后端未返回该币种定价结论。')
    }
  })
  const evidenceStatus = ['complete', 'partial', 'unavailable'].includes(result.evidenceStatus)
    ? result.evidenceStatus
    : 'unavailable'
  return {
    tenantId: String(result.tenantId || ''),
    start: String(result.start || ''),
    end: String(result.end || ''),
    asOf: String(result.asOf || ''),
    targetMarginLabel: formatRatio(result.targetContributionMarginRate),
    maxValueShareLabel: formatRatio(result.maxVerifiedSavingsShare),
    recommendedModel: String(result.recommendedModel || 'pilot_collecting'),
    recommendedModelLabel: PRICING_MODEL_LABELS[result.recommendedModel] || '继续采集证据',
    evidenceStatus,
    evidenceStatusLabel: statusLabel(evidenceStatus),
    rows,
    multiCurrency: new Set(rows.map((item) => item.currency)).size > 1,
    notes: Array.isArray(result.notes) ? result.notes.map((item) => String(item)) : []
  }
}

export function toExplicitTimezone(value, fieldLabel) {
  const normalized = String(value || '').trim()
  if (!normalized) throw new Error(`请填写${fieldLabel}。`)
  const parsed = new Date(normalized)
  if (!Number.isFinite(parsed.getTime())) throw new Error(`${fieldLabel}格式无效。`)
  return parsed.toISOString()
}

function requiredText(form, key, label) {
  const value = String(form?.[key] ?? '').trim()
  if (!value) throw new Error(`请填写${label}。`)
  return value
}

function positiveInteger(value, label, minimum = 1) {
  const number = Number(value)
  if (!Number.isInteger(number) || number < minimum) {
    throw new Error(`${label}必须是不小于 ${minimum} 的整数。`)
  }
  return number
}

function nonNegativeNumber(value, label, optional = false) {
  if (optional && (value === '' || value === null || value === undefined)) return null
  const number = Number(value)
  if (!Number.isFinite(number) || number < 0) throw new Error(`${label}必须是非负数。`)
  return String(value)
}

function positiveNumber(value, label) {
  const number = Number(value)
  if (!Number.isFinite(number) || number <= 0) throw new Error(`${label}必须大于 0。`)
  return String(value)
}

function ensureAscendingWindow(start, end, label) {
  if (end && new Date(end).getTime() <= new Date(start).getTime()) {
    throw new Error(`${label}结束时间必须晚于开始时间。`)
  }
}

function parseJsonObject(value, label) {
  const normalized = String(value || '').trim()
  if (!normalized) return {}
  let parsed
  try {
    parsed = JSON.parse(normalized)
  } catch {
    throw new Error(`${label}必须是有效 JSON。`)
  }
  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
    throw new Error(`${label}必须是 JSON 对象。`)
  }
  return parsed
}

function optionalText(value) {
  const normalized = String(value || '').trim()
  return normalized || null
}

function createPlanPayload(form) {
  const currency = normalizeCurrency(requiredText(form, 'currency', '套餐币种'))
  if (!currency) throw new Error('套餐币种必须是三位英文字母。')
  const payload = {
    planCode: requiredText(form, 'planCode', '套餐编码'),
    name: requiredText(form, 'name', '套餐名称'),
    pricingModel: requiredText(form, 'pricingModel', '计价模式'),
    billingInterval: requiredText(form, 'billingInterval', '计费周期'),
    currency,
    baseFee: nonNegativeNumber(form.baseFee, '基础费用'),
    includedSeats: positiveInteger(form.includedSeats, '包含席位', 0),
    overageEnabled: Boolean(form.overageEnabled),
    effectiveFrom: toExplicitTimezone(form.effectiveFrom, '套餐生效时间'),
    effectiveTo: form.effectiveTo ? toExplicitTimezone(form.effectiveTo, '套餐失效时间') : null,
    contractTermsJson: parseJsonObject(form.contractTermsJson, '合同条款')
  }
  ensureAscendingWindow(payload.effectiveFrom, payload.effectiveTo, '套餐生效窗口')
  return payload
}

function createSubscriptionPayload(form, account) {
  const provider = optionalText(form.externalProvider)
  const externalId = optionalText(form.externalSubscriptionId)
  if (Boolean(provider) !== Boolean(externalId)) {
    throw new Error('外部订阅提供商和订阅编号必须同时填写或同时留空。')
  }
  const payload = {
    subscriptionKey: requiredText(form, 'subscriptionKey', '订阅键'),
    planId: requiredText({ planId: form.planId || account?.plan?.id }, 'planId', '套餐 ID'),
    status: String(form.status || 'active'),
    startsAt: toExplicitTimezone(form.startsAt, '订阅开始时间'),
    endsAt: form.endsAt ? toExplicitTimezone(form.endsAt, '订阅结束时间') : null,
    currentPeriodStart: toExplicitTimezone(form.currentPeriodStart, '当前周期开始时间'),
    currentPeriodEnd: toExplicitTimezone(form.currentPeriodEnd, '当前周期结束时间'),
    seats: positiveInteger(form.seats, '席位数'),
    autoRenew: Boolean(form.autoRenew),
    externalProvider: provider,
    externalSubscriptionId: externalId,
    metadataJson: parseJsonObject(form.metadataJson, '订阅元数据')
  }
  ensureAscendingWindow(payload.startsAt, payload.endsAt, '订阅')
  ensureAscendingWindow(payload.currentPeriodStart, payload.currentPeriodEnd, '当前订阅周期')
  return payload
}

function entitlementPayload(form, account) {
  const entitlementType = requiredText(form, 'entitlementType', '权益类型')
  let includedQuantity = nonNegativeNumber(form.includedQuantity, '包含量', true)
  let hardLimitQuantity = nonNegativeNumber(form.hardLimitQuantity, '硬配额', true)
  if (entitlementType === 'unlimited') {
    includedQuantity = null
    hardLimitQuantity = null
  } else if (entitlementType === 'metered' && includedQuantity === null) {
    throw new Error('计量权益必须填写包含量。')
  }
  if (entitlementType === 'feature') {
    const allowed = new Set([null, '0', '1'])
    if (!allowed.has(includedQuantity) || !allowed.has(hardLimitQuantity)) {
      throw new Error('功能权益的包含量和硬配额只能是 0 或 1。')
    }
  }
  if (includedQuantity !== null && hardLimitQuantity !== null && Number(hardLimitQuantity) < Number(includedQuantity)) {
    throw new Error('硬配额不能小于包含量。')
  }
  const payload = {
    subscriptionId: requiredText(
      { subscriptionId: form.subscriptionId || account?.subscription?.id },
      'subscriptionId',
      '订阅 ID'
    ),
    entitlementKey: requiredText(form, 'entitlementKey', '权益键'),
    metricKey: requiredText(form, 'metricKey', '计量指标键'),
    entitlementType,
    unit: requiredText(form, 'unit', '计量单位'),
    includedQuantity,
    hardLimitQuantity,
    resetInterval: requiredText(form, 'resetInterval', '重置周期'),
    overagePolicy: requiredText(form, 'overagePolicy', '超额策略'),
    status: String(form.status || 'active'),
    effectiveFrom: toExplicitTimezone(form.effectiveFrom, '权益生效时间'),
    effectiveTo: form.effectiveTo ? toExplicitTimezone(form.effectiveTo, '权益失效时间') : null,
    configJson: parseJsonObject(form.configJson, '权益配置')
  }
  ensureAscendingWindow(payload.effectiveFrom, payload.effectiveTo, '权益生效窗口')
  return payload
}

function activationPayload(form, account, kind) {
  const defaults = {
    activatePlan: account?.plan,
    activateSubscription: account?.subscription,
    activateEntitlement: null
  }
  const current = defaults[kind]
  const reason = requiredText(form, 'reason', '激活原因')
  if (reason.length < 2) throw new Error('激活原因至少填写 2 个字符。')
  return {
    resourceId: requiredText({ resourceId: form.resourceId || current?.id }, 'resourceId', '资源 ID'),
    expectedVersion: positiveInteger(form.expectedVersion || current?.version, '期望版本'),
    reason
  }
}

function subscriptionTransitionPayload(form, account) {
  const activation = activationPayload(form, account, 'activateSubscription')
  const targetStatus = requiredText(form, 'targetStatus', '目标状态')
  if (!['past_due', 'suspended', 'canceled', 'expired'].includes(targetStatus)) {
    throw new Error('目标订阅状态无效。')
  }
  const reason = requiredText(form, 'reason', '状态变更原因')
  if (reason.length < 2) throw new Error('状态变更原因至少填写 2 个字符。')
  return { ...activation, targetStatus, reason }
}

function usagePayload(form, account) {
  const eventType = String(form.eventType || 'usage')
  const quantity = Number(requiredText(form, 'quantity', '用量数量'))
  if (!Number.isFinite(quantity)) throw new Error('用量数量必须是有效数字。')
  if (eventType === 'usage' && quantity <= 0) throw new Error('用量事件数量必须大于 0。')
  if (eventType === 'credit' && quantity >= 0) throw new Error('抵扣事件数量必须小于 0。')
  if (['adjustment', 'reversal'].includes(eventType) && quantity === 0) throw new Error('调整或冲回事件数量不能为 0。')
  const reversalOfEventId = optionalText(form.reversalOfEventId)
  if ((eventType === 'reversal') !== Boolean(reversalOfEventId)) {
    throw new Error('只有冲回事件必须且只能填写被冲回事件 ID。')
  }
  const subjectType = optionalText(form.subjectType)
  const subjectId = optionalText(form.subjectId)
  if (Boolean(subjectType) !== Boolean(subjectId)) throw new Error('主体类型和主体 ID 必须同时填写或同时留空。')
  return {
    subscriptionId: requiredText(
      { subscriptionId: form.subscriptionId || account?.subscription?.id },
      'subscriptionId',
      '订阅 ID'
    ),
    entitlementId: requiredText(form, 'entitlementId', '权益 ID'),
    eventType,
    quantity: String(form.quantity),
    occurredAt: toExplicitTimezone(form.occurredAt, '用量发生时间'),
    sourceSystem: requiredText(form, 'sourceSystem', '来源系统'),
    idempotencyKey: requiredText(form, 'idempotencyKey', '幂等键'),
    reversalOfEventId,
    subjectType,
    subjectId,
    correlationId: optionalText(form.correlationId),
    metadataJson: parseJsonObject(form.metadataJson, '用量元数据')
  }
}

function costPayload(form, account) {
  const originalCurrency = normalizeCurrency(requiredText(form, 'originalCurrency', '原始币种'))
  const reportingCurrency = normalizeCurrency(requiredText(form, 'reportingCurrency', '报告币种'))
  if (!originalCurrency || !reportingCurrency) throw new Error('成本币种必须是三位英文字母。')
  const subscriptionId = optionalText(form.subscriptionId || account?.subscription?.id)
  const usageEventId = optionalText(form.usageEventId)
  if (usageEventId && !subscriptionId) throw new Error('关联用量事件时必须填写订阅 ID。')
  const eventType = String(form.eventType || 'incurred')
  const reversalOfCostEventId = optionalText(form.reversalOfCostEventId)
  if ((eventType === 'reversal') !== Boolean(reversalOfCostEventId)) {
    throw new Error('只有冲回成本事件必须且只能填写被冲回成本事件 ID。')
  }
  return {
    subscriptionId,
    usageEventId,
    eventType,
    costCategory: requiredText(form, 'costCategory', '成本类别'),
    quantity: positiveNumber(form.quantity, '成本数量'),
    unit: requiredText(form, 'unit', '成本单位'),
    unitCost: nonNegativeNumber(form.unitCost, '单位成本'),
    originalCurrency,
    reportingCurrency,
    fxRate: positiveNumber(form.fxRate, '汇率'),
    provider: optionalText(form.provider),
    sku: optionalText(form.sku),
    modelName: optionalText(form.modelName),
    allocationKey: requiredText(form, 'allocationKey', '归集键'),
    occurredAt: toExplicitTimezone(form.occurredAt, '成本发生时间'),
    sourceSystem: requiredText(form, 'sourceSystem', '来源系统'),
    idempotencyKey: requiredText(form, 'idempotencyKey', '幂等键'),
    reversalOfCostEventId,
    correlationId: optionalText(form.correlationId),
    metadataJson: parseJsonObject(form.metadataJson, '成本元数据')
  }
}

export function buildCommercialMutation(kind, form = {}, account = null) {
  if (!COMMERCIAL_ACTIONS[kind]) throw new Error('不支持的商业管理操作。')
  if (kind === 'createPlan') return createPlanPayload(form)
  if (kind === 'createSubscription') return createSubscriptionPayload(form, account)
  if (kind === 'upsertEntitlement') return entitlementPayload(form, account)
  if (kind === 'transitionSubscription') return subscriptionTransitionPayload(form, account)
  if (kind.startsWith('activate')) return activationPayload(form, account, kind)
  if (kind === 'recordUsage') return usagePayload(form, account)
  return costPayload(form, account)
}
