import { Typography } from 'antd'

import type { CollectField, WorkOrder } from '@/types/worker-platform'

import { asRecord, formatMoney } from './shared'

const SKIP_PUBLISH_CONFIRM_KEY = 'admin-work-order-skip-publish-confirm'

export function shouldSkipPublishConfirm() {
  try {
    return localStorage.getItem(SKIP_PUBLISH_CONFIRM_KEY) === '1'
  } catch {
    return false
  }
}

export function setSkipPublishConfirm() {
  try {
    localStorage.setItem(SKIP_PUBLISH_CONFIRM_KEY, '1')
  } catch {
    // 浏览器禁用本地存储时继续发布，但不记住本次选择。
  }
}

export function formatUserPaymentAmount(order: WorkOrder): string {
  const paymentFen = getUserPaymentFen(order)
  return paymentFen === null ? '-' : formatMoney(paymentFen)
}

/** 拼单母单没有单一 assigned worker，改为展示当前参与打手及其承接份数。 */
export function renderWorkOrderWorkers(order: WorkOrder) {
  if (order.worker) return order.worker.displayName || order.worker.username || '-'
  if (!order.sharing?.enabled || !order.sharingWorkers?.length) return '-'
  const names = order.sharingWorkers
    .map((worker) => worker.displayName || worker.username || `打手#${worker.workerId}`)
    .join('、')
  const quantity = order.sharingWorkers.reduce(
    (sum, worker) => sum + Number(worker.quantity || 0),
    0,
  )
  return (
    <div className="cell-stack">
      <Typography.Text ellipsis={{ tooltip: names }}>{names}</Typography.Text>
      <Typography.Text type="secondary" style={{ fontSize: 12 }}>
        {order.sharingWorkers.length} 人 · {quantity} 份
      </Typography.Text>
    </div>
  )
}

export function getDisplayOrderNo(
  order: Pick<WorkOrder, 'platformOrderId'> | null | undefined,
): string {
  return String(order?.platformOrderId || '').trim() || '-'
}

/** 用户付款金额（分）；未知返回 null（不参与超价提示） */
export function getUserPaymentFen(order: WorkOrder): number | null {
  const material = asRecord(order.material)
  const source = asRecord(material.source)
  const sendCode = asRecord(source.kuaishouSendCode)
  const paymentFen = Number(sendCode.paymentFen ?? source.orderAmountFen)
  return Number.isFinite(paymentFen) ? paymentFen : null
}

/** 解析客服粘贴文本（如「安卓还是苹果(必填)：安卓」），返回字段 key → 值 */
export function parseWorkerMaterialText(text: string): Record<string, string> {
  const result: Record<string, string> = {}
  const lines = String(text || '')
    .split(/\r?\n/)
    .map((line) => line.trim())
    .filter(Boolean)
  for (const line of lines) {
    const match = line.match(/^(.+?)[：:]\s*(.+)$/)
    if (!match) continue
    const label = match[1]
      .replace(/[（(](必填|选填)[)）]/g, '')
      .trim()
      .toLowerCase()
    const value = match[2].trim()
    if (!label || !value) continue

    if (/系统|安卓|苹果/.test(label)) {
      if (value.includes('苹果')) result.system = '苹果'
      else if (value.includes('安卓')) result.system = '安卓'
    } else if (/区/.test(label) || /服/.test(label)) {
      const zoneValue = value.toLowerCase()
      if (zoneValue.includes('微信') || /^v/.test(zoneValue)) result.serverZone = '微信区'
      else if (zoneValue.includes('q')) result.serverZone = 'QQ区'
    } else if (/角色|昵称|名称/.test(label)) {
      result.gameNickname = value
    } else if (/编号|游戏id|账号id|^id|uid/.test(label)) {
      result.gameId = value
    }
  }
  return result
}

export function formatRequirementFieldsText(fields: CollectField[]): string {
  return fields
    .map((field) => {
      const labelPart = `${field.key}:${field.label}`
      const options = (field.options || []).filter(Boolean)
      return options.length > 0 ? `${labelPart}#${options.join(',')}` : labelPart
    })
    .join('\n')
}
