/**
 * SOP 步骤统一配置
 * 与后台 SopService / SopController 的 stepCode 对齐
 */

/** 单步配置 */
export interface SopStepConfig {
  /** 步骤序号 1-8 */
  step: number
  /** 后台 stepCode */
  code: string
  /** 移动端展示标题 */
  title: string
  /** 本步骤涉及的照片 phase 列表（与后台 PhotoUploadGroup 对齐） */
  phases?: string[]
  /** 本步骤是否需要输入文本 */
  input?: {
    label: string
    placeholder: string
    stateKey: 'blockageText' | 'feedbackText'
  }
}

/** 8 步 SOP（与后台顺序一致） */
export const SOP_STEPS: SopStepConfig[] = [
  { step: 1, code: 'confirm', title: '确认任务' },
  { step: 2, code: 'prepare', title: '出车准备', phases: ['departure_vehicle'] },
  { step: 3, code: 'arrive', title: '到达现场', phases: ['parking_sign', 'site_survey'] },
  { step: 4, code: 'work', title: '开始施工', phases: ['blockage', 'construction_process'], input: { label: '堵塞物', placeholder: '如：头发、纸巾、油污等', stateKey: 'blockageText' } },
  { step: 5, code: 'photo', title: '施工完成', phases: ['construction_complete'], input: { label: '设施反馈', placeholder: '设施状态、建议等', stateKey: 'feedbackText' } },
  { step: 6, code: 'clean', title: '现场清洗', phases: ['site_cleaning'] },
  { step: 7, code: 'accept', title: '验收签字', phases: ['acceptance'] },
  { step: 8, code: 'finish', title: '完工确认' },
]

/** 照片 phase 中文标签（与 admin 前端 PhotoUploadGroup 对齐） */
export const PHASE_LABELS: Record<string, string> = {
  departure_vehicle: '出车前车辆及设备',
  parking_sign: '停车警示牌',
  site_survey: '现场勘验',
  blockage: '堵塞物照片',
  construction_process: '施工过程',
  construction_complete: '施工完成',
  site_cleaning: '现场清洗',
  acceptance: '验收确认',
}

/** 照片 phase 描述（与 admin 前端 PhotoUploadGroup 对齐） */
export const PHASE_DESCRIPTIONS: Record<string, string> = {
  departure_vehicle: '拍摄车辆外观、设备状态照片',
  parking_sign: '拍摄现场停车警示牌摆放照片',
  site_survey: '拍摄现场环境、管道状况照片或视频',
  blockage: '拍摄堵塞物照片',
  construction_process: '拍摄施工过程照片或视频',
  construction_complete: '拍摄施工完成后的现场照片',
  site_cleaning: '拍摄清洗后的现场照片',
  acceptance: '拍摄验收签字或客户确认照片',
}

/** 照片 phase 最大数量（与 admin 前端 PhotoUploadGroup 对齐） */
export const PHASE_MAX_COUNTS: Record<string, number> = {
  departure_vehicle: 5,
  parking_sign: 3,
  site_survey: 10,
  blockage: 5,
  construction_process: 15,
  construction_complete: 5,
  site_cleaning: 5,
  acceptance: 5,
}

/** 获取 phase 中文标签 */
export function getPhaseLabel(phase: string): string {
  return PHASE_LABELS[phase] || phase
}

/** 获取 phase 描述 */
export function getPhaseDescription(phase: string): string {
  return PHASE_DESCRIPTIONS[phase] || ''
}

/** 获取 phase 最大上传数量 */
export function getPhaseMaxCount(phase: string): number {
  return PHASE_MAX_COUNTS[phase] || 6
}

/** step 1-8 -> stepCode */
export function getStepCode(step: number): string {
  return SOP_STEPS.find((s) => s.step === step)?.code || ''
}

/** stepCode -> step 1-8 */
export function getStepIndex(code: string): number {
  return SOP_STEPS.find((s) => s.code === code)?.step || 0
}

/** stepCode -> 配置 */
export function getStepConfig(code: string): SopStepConfig | undefined {
  return SOP_STEPS.find((s) => s.code === code)
}

/** step 1-8 -> 配置 */
export function getStepConfigByIndex(step: number): SopStepConfig | undefined {
  return SOP_STEPS.find((s) => s.step === step)
}

/** 步骤中文标题列表（用于流程条展示） */
export const SOP_STEP_TITLES = SOP_STEPS.map((s) => s.title)

// ==================== 与 admin 前端对齐的施工流程进度计算（任务详情页 + 任务卡片共享） ====================

/** 顶部流程条 UI 步骤（与 admin FLOW_STEPS 对齐） */
export const FLOW_STEPS = [
  { uiStep: 1, title: '确认', backendCode: 'confirm' },
  { uiStep: 2, title: '出车', backendCode: 'prepare' },
  { uiStep: 3, title: '到达', backendCode: 'arrive' },
  { uiStep: 4, title: '勘验', backendCode: 'arrive' },
  { uiStep: 5, title: '施工', backendCode: 'work' },
  { uiStep: 6, title: '完成', backendCode: 'photo' },
  { uiStep: 7, title: '清洗', backendCode: 'clean' },
  { uiStep: 8, title: '验收', backendCode: 'accept' },
]

/** 单 phase 配置 */
export interface PhotoPhaseConfig {
  phase: string
  title: string
  description: string
  maxCount: number
}

/** 施工流程记录卡片配置（与 admin RECORD_STEPS 对齐） */
export interface RecordStepDef {
  uiStep: number
  backendCode: string
  title: string
  description: string
  phases: PhotoPhaseConfig[]
  input?: {
    label: string
    placeholder: string
    stateKey: 'blockageText' | 'feedbackText'
  }
}

/** 7 张记录卡定义 */
export const RECORD_STEPS: RecordStepDef[] = [
  {
    uiStep: 2,
    backendCode: 'prepare',
    title: '出车',
    description: '出车前车辆及设备照片',
    phases: [{ phase: 'departure_vehicle', title: '出车前车辆及设备', description: '拍摄车辆外观、设备状态照片', maxCount: getPhaseMaxCount('departure_vehicle') }],
  },
  {
    uiStep: 3,
    backendCode: 'arrive',
    title: '到达现场',
    description: '到达现场后停车警示牌照片',
    phases: [{ phase: 'parking_sign', title: '停车警示牌', description: '到达现场后停车警示牌摆放照片', maxCount: getPhaseMaxCount('parking_sign') }],
  },
  {
    uiStep: 4,
    backendCode: 'arrive',
    title: '现场勘验',
    description: '现场勘验照片或视频',
    phases: [{ phase: 'site_survey', title: '现场勘验', description: '拍摄现场环境、管道状况照片或视频', maxCount: getPhaseMaxCount('site_survey') }],
  },
  {
    uiStep: 5,
    backendCode: 'work',
    title: '施工',
    description: '施工过程照片或视频',
    phases: [
      { phase: 'blockage', title: '堵塞物照片', description: '拍摄堵塞物照片', maxCount: getPhaseMaxCount('blockage') },
      { phase: 'construction_process', title: '施工过程', description: '拍摄施工过程照片或视频', maxCount: getPhaseMaxCount('construction_process') },
    ],
    input: { label: '堵塞物', placeholder: '如：头发、纸巾、油污等', stateKey: 'blockageText' },
  },
  {
    uiStep: 6,
    backendCode: 'photo',
    title: '完成',
    description: '施工完成后的现场照片',
    phases: [{ phase: 'construction_complete', title: '施工完成', description: '拍摄施工完成后的现场照片', maxCount: getPhaseMaxCount('construction_complete') }],
    input: { label: '设施反馈', placeholder: '设施状态、建议等', stateKey: 'feedbackText' },
  },
  {
    uiStep: 7,
    backendCode: 'clean',
    title: '清洗',
    description: '清洗后的现场照片',
    phases: [{ phase: 'site_cleaning', title: '现场清洗', description: '拍摄清洗后的现场照片', maxCount: getPhaseMaxCount('site_cleaning') }],
  },
  {
    uiStep: 8,
    backendCode: 'accept',
    title: '验收',
    description: '验收签字或客户确认照片',
    phases: [{ phase: 'acceptance', title: '验收确认', description: '拍摄验收签字或客户确认照片', maxCount: getPhaseMaxCount('acceptance') }],
  },
]

/** 判断某记录步骤是否已完成：任一阶段上传了照片即视为完成（与 admin 对齐） */
export function isRecordStepComplete(photos: { phase?: string; photoUrl?: string }[], uiStep: number): boolean {
  const def = RECORD_STEPS.find((r) => r.uiStep === uiStep)
  if (!def) return false
  return def.phases.some((phaseConfig) =>
    photos.some((p) => p.phase === phaseConfig.phase && p.photoUrl)
  )
}

/** 已完成的记录步骤数量 */
export function completedRecordStepCount(photos: { phase?: string; photoUrl?: string }[]): number {
  return RECORD_STEPS.filter((r) => isRecordStepComplete(photos, r.uiStep)).length
}

/** 是否所有记录步骤都已完成 */
export function isAllRecordStepsComplete(photos: { phase?: string; photoUrl?: string }[]): boolean {
  return completedRecordStepCount(photos) === RECORD_STEPS.length
}

/** 判断流程步骤状态（与 admin TaskDetailPage getFlowStepState 对齐） */
export function getFlowStepState(
  task: { status?: string } | null | undefined,
  photos: { phase?: string; photoUrl?: string }[],
  uiStep: number
): 'completed' | 'current' | 'pending' {
  if (task?.status === 'completed') return 'completed'

  if (uiStep === 1) {
    return task?.status !== 'assigned' ? 'completed' : 'current'
  }

  const recordDef = RECORD_STEPS.find((r) => r.uiStep === uiStep)
  if (recordDef && isRecordStepComplete(photos, recordDef.uiStep)) {
    return 'completed'
  }

  const firstPendingIndex = FLOW_STEPS.findIndex((s) => {
    if (s.uiStep === 1) return task?.status === 'assigned'
    const rd = RECORD_STEPS.find((r) => r.uiStep === s.uiStep)
    return rd ? !isRecordStepComplete(photos, rd.uiStep) : false
  })
  const isCurrent = firstPendingIndex >= 0 && FLOW_STEPS[firstPendingIndex].uiStep === uiStep
  return isCurrent ? 'current' : 'pending'
}

/** 计算当前进行到的步骤索引（1-based，与 FLOW_STEPS 对齐） */
export function computeCurrentStepIndex(
  task: { status?: string; currentStep?: number } | null | undefined,
  photos: { phase?: string; photoUrl?: string }[]
): number {
  if (task?.status === 'completed') return FLOW_STEPS.length
  if (task?.status === 'cancelled' || task?.status === 'rejected') return 0

  // 已确认/进行中任务：按照片记录卡完成情况推进
  if (task?.status === 'in_progress' || task?.status === 'assigned') {
    const completed = completedRecordStepCount(photos)
    return Math.min(completed + 1, FLOW_STEPS.length)
  }

  // 其他状态回退到后台 currentStep 映射
  const step = Number(task?.currentStep)
  if (step > 0) {
    return Math.min(step, FLOW_STEPS.length)
  }
  return 1
}

/** 流程条进度百分比（0-100） */
export function computeFlowProgress(
  task: { status?: string } | null | undefined,
  photos: { phase?: string; photoUrl?: string }[]
): number {
  if (task?.status === 'completed') return 100
  const completedCount = FLOW_STEPS.filter((s) => getFlowStepState(task, photos, s.uiStep) === 'completed').length - 1
  return Math.max(0, (completedCount / (FLOW_STEPS.length - 1)) * 100)
}
