/**
 * 乐跑记录展示：兼容旧版 result 与 JKES（useTime、distance、status 等）
 */

/** JKES 接口 distance 多为米；存库可能未换算，统一为千米用于展示 */
export function normalizeJkesDistanceToKm(raw) {
  const d = Number(raw)
  if (!Number.isFinite(d) || d <= 0) return 0
  if (d >= 50) return Math.round((d / 1000) * 1000) / 1000
  return Math.round(d * 1000) / 1000
}

function normalizeResult(record) {
  let r = record?.result
  if (r != null && typeof r !== 'object') {
    try {
      r = JSON.parse(r)
    } catch {
      r = {}
    }
  }
  return r && typeof r === 'object' && !Array.isArray(r) ? r : {}
}

function normalizeText(x) {
  if (x == null) return ''
  const s = String(x).trim()
  return s
}

function translateRunStatus(raw) {
  const s = normalizeText(raw)
  if (!s) return '—'
  const k = s.toLowerCase()

  // 常见状态（尽量宽松匹配）
  if (/(running|in[_\s-]?progress|processing|doing)/i.test(s)) return '进行中'
  if (/(pending|to[_\s-]?sync|syncing|await)/i.test(s)) return '待同步'
  // JKES 常见：END/ENDED（跑步成功结束）
  if (/(^end$|ended|finish|finished|done)/i.test(s)) return '自动确认有效'
  if (/(valid|success|passed|pass|complete|completed|ok|normal)/i.test(s)) return '自动确认有效'
  if (/(invalid|fail|failed|error|abnormal|exception|reject)/i.test(s)) return '失败'

  // 兜底：常见单词替换后展示
  return s
}

function isCampusOk(raw) {
  const s = normalizeText(raw)
  if (!s) return true
  const k = s.toLowerCase()
  if (/(invalid|fail|failed|error|abnormal|exception|reject)/i.test(s)) return false
  if (/(valid|success|passed|pass|ok|normal)/i.test(s)) return true
  return true
}

/**
 * 列表/表格用：从单行记录解析展示字段
 */
export function parseLepaoRecordRow(record) {
  const jkes = record?.jkes_record
  const r = normalizeResult(record)
  const routeRunZoneName =
    record?.path_run_zone_name ?? record?.run_zone_name ?? record?.path?.run_zone_name ?? null
  const pathDistanceKm =
    record?.path_distance != null ? normalizeJkesDistanceToKm(record.path_distance) : null
  const plannedKm = r?.planned_km != null ? Number(r.planned_km) : null
  const deductedKm = r?.deducted_km != null ? Number(r.deducted_km) : null
  const officialKm = r?.official_km != null ? Number(r.official_km) : null
  const refundedKm = r?.refunded_km != null ? Number(r.refunded_km) : null
  const expectedKm =
    plannedKm != null && Number.isFinite(plannedKm)
      ? plannedKm
      : pathDistanceKm != null && Number.isFinite(pathDistanceKm)
        ? pathDistanceKm
        : null

  // 后端新增：0进行中 1待同步 2完成 3异常
  const runState = Number(record?.state)
  if (Number.isFinite(runState) && runState !== 2) {
    const stateText =
      runState === 0 ? '正在进行中' : runState === 1 ? '已结束待同步' : runState === 3 ? '乐跑失败，乐跑里程已返还' : '未知状态'
    return {
      isJkes: true,
      statusText: stateText,
      passTit: '—',
      campusStatusText: '—',
      routeRunZoneName,
      pathDistanceKm,
      plannedKm,
      deductedKm,
      officialKm,
      refundedKm,
      expectedKm,
      distance: 0,
      timeSec: 0,
      pointList: Array.isArray(r.point_list) ? r.point_list : [],
      ok: false,
      statusLevel: runState === 0 ? 'running' : runState === 1 ? 'sync' : 'fail'
    }
  }

  const useTime = jkes?.use_time_sec ?? r.useTime ?? r.time
  const distanceRaw = jkes?.distance_km ?? r.distance
  const distance = normalizeJkesDistanceToKm(distanceRaw)

  const looksJkes =
    jkes != null ||
    (r.useTime != null &&
      r.record_failed_reason === undefined &&
      r.pass_tit === undefined)

  if (looksJkes && (useTime != null || distance != null)) {
    const runStatus = jkes?.run_status ?? r.status?.value ?? r.status ?? ''
    const campus = jkes?.campus_status ?? r.dataStatus?.value ?? r.dataStatus ?? ''
    const runText = translateRunStatus(runStatus)
    const campusOk = isCampusOk(campus)
    const ok = runText === '自动确认有效' && campusOk

    return {
      isJkes: true,
      statusText: runText,
      passTit: campus ? String(campus) : '—',
      campusStatusText: campus ? String(campus) : '—',
      routeRunZoneName,
      pathDistanceKm,
      plannedKm,
      deductedKm,
      officialKm,
      refundedKm,
      expectedKm,
      distance: distance || 0,
      timeSec: Number(useTime) || 0,
      pointList: Array.isArray(r.point_list) ? r.point_list : [],
      ok,
      statusLevel: ok ? 'success' : 'fail'
    }
  }

  const reason = r.record_failed_reason != null ? String(r.record_failed_reason) : '—'
  const okText = reason === '自动确认有效'
  return {
    isJkes: false,
    statusText: reason,
    passTit: r.pass_tit != null ? String(r.pass_tit) : '—',
    campusStatusText: r.pass_tit != null ? String(r.pass_tit) : '—',
    routeRunZoneName,
    pathDistanceKm,
    plannedKm,
    deductedKm,
    officialKm,
    refundedKm,
    expectedKm,
    distance: Number(r.distance) || 0,
    timeSec: Number(r.time) || 0,
    pointList: Array.isArray(r.point_list) ? r.point_list : [],
    ok: okText,
    statusLevel: okText ? 'success' : 'fail'
  }
}

export function formatKm(n) {
  const x = Number(n)
  if (!Number.isFinite(x)) return '—'
  return `${x.toFixed(2)} km`
}

export function formatPace(seconds, km) {
  const s = Number(seconds)
  const d = Number(km)
  if (!Number.isFinite(s) || !Number.isFinite(d) || d <= 0) return '—'
  const paceInSeconds = s / d
  const minutes = Math.floor(paceInSeconds / 60)
  const remainingSeconds = Math.round(paceInSeconds % 60)
  return `${minutes}'${String(remainingSeconds).padStart(2, '0')}''`
}

export function formatSecondsToMinSec(totalSeconds) {
  const t = Math.floor(Number(totalSeconds) || 0)
  const minutes = Math.floor(t / 60)
  const seconds = t % 60
  return `${minutes}分${String(seconds).padStart(2, '0')}秒`
}

/** 详情页 descriptions + 地图 */
export function buildRecordDetailInfo(data, options = {}) {
  const { isAdmin = false } = options || {}
  const row = parseLepaoRecordRow({
    result: data?.result,
    jkes_record: data?.jkes_record,
    run_zone_name: data?.run_zone_name,
    path_run_zone_name: data?.path_run_zone_name,
    path_distance: data?.path_distance
  })
  const lines = [
    { label: '账号名称', value: data?.name ?? '—' },
    { label: '乐跑账号', value: data?.lepao_account ?? '—' },
    { label: '路线跑区', value: row.routeRunZoneName ?? '—' },
    { label: '记录时间', value: data?.time != null ? new Date(data.time).toLocaleString('zh-CN') : '—' }
  ]

  if (row.isJkes) {
    const begin = data?.jkes_record?.begin_time ?? normalizeResult(data).beginTime
    const end = data?.jkes_record?.end_time ?? normalizeResult(data).endTime
    if (begin) {
      lines.push({
        label: '开始时间',
        value: new Date(begin).toLocaleString('zh-CN')
      })
    }
    if (end) {
      lines.push({
        label: '结束时间',
        value: new Date(end).toLocaleString('zh-CN')
      })
    }
    lines.push({ label: '跑步状态', value: row.statusText })
  } else {
    const r = normalizeResult(data)
    if (r.start_time) {
      lines.push({
        label: '开始时间',
        value: new Date(r.start_time * 1000).toLocaleString('zh-CN')
      })
    }
    lines.push({ label: '乐跑状态', value: row.statusText })
  }

  lines.push({ label: '跑步距离', value: formatKm(row.distance) })
  if (row.expectedKm != null) {
    lines.push({ label: '预计距离', value: formatKm(row.expectedKm) })
  }
  if (row.deductedKm != null && Number.isFinite(row.deductedKm)) {
    lines.push({ label: '扣费里程', value: formatKm(row.deductedKm) })
  }
  if (row.refundedKm != null && Number.isFinite(row.refundedKm) && row.refundedKm > 0) {
    lines.push({ label: '退还里程', value: formatKm(row.refundedKm) })
  }
  if (row.officialKm != null && Number.isFinite(row.officialKm)) {
    lines.push({ label: '实际扣费里程', value: formatKm(row.officialKm) })
  }
  lines.push({ label: '跑步时长', value: formatSecondsToMinSec(row.timeSec) })
  lines.push({
    label: '平均配速',
    value: formatPace(row.timeSec, row.distance)
  })

  if (isAdmin && data?.path_id != null) {
    lines.push({ label: '路线ID', value: String(data.path_id) })
  }

  return lines
}

export function normalizePointData(pd) {
  if (!pd) return []
  if (Array.isArray(pd)) return pd
  if (typeof pd === 'string') {
    try {
      const p = JSON.parse(pd)
      return Array.isArray(p) ? p : []
    } catch {
      return []
    }
  }
  return []
}

/** 每公里秒数 → 分:秒 展示（如 3:00、10:00），不含单位 */
export function formatSecPerKmAsMinSec(sec) {
  const n = Math.round(Number(sec))
  if (!Number.isFinite(n) || n <= 0) return '—'
  const m = Math.floor(n / 60)
  const s = n % 60
  return `${m}:${String(s).padStart(2, '0')}`
}

/**
 * 自动乐跑配速区间展示：3:00–10:00（每公里）
 */
export function formatAutoPaceRangeLabel(minSec, maxSec) {
  return `${formatSecPerKmAsMinSec(minSec)}–${formatSecPerKmAsMinSec(maxSec)}`
}

/**
 * 解析配速输入为「每公里秒数」：支持 5:30、5：30；或 ≥60 的纯数字（视为秒/公里，如 330）
 * @returns {number | null}
 */
export function parsePaceMinSecInput(input) {
  const raw = String(input ?? '').trim()
  if (!raw) return null

  if (/^\d+(\.\d+)?$/.test(raw)) {
    const n = parseFloat(raw)
    if (!Number.isFinite(n) || n < 60) return null
    return Math.round(n)
  }

  const colon = raw.match(/^(\d+)[:：](\d{1,2}(?:\.\d+)?)$/)
  if (colon) {
    const minutes = parseInt(colon[1], 10)
    const seconds = parseFloat(colon[2])
    if (!Number.isFinite(minutes) || !Number.isFinite(seconds) || seconds >= 60) return null
    return Math.round(minutes * 60 + seconds)
  }

  return null
}

/** 自动乐跑距离区间（km）展示 */
export function formatAutoDistanceRangeLabel(minKm, maxKm) {
  const a = formatKm(minKm ?? 2)
  const b = formatKm(maxKm ?? 2)
  return a === b ? a : `${a} ~ ${b}`
}
