import { ref, computed } from 'vue'
import {
  createInitialProfessionalState,
  DEFECT_STATUS,
  BATCH_STATUS,
  REPORT_TEMPLATES,
} from '../mocks/professionalModulesMockData.js'

const STORAGE_KEY = 'dockscope_professional_v1'

function loadState() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    if (raw) return JSON.parse(raw)
  } catch (e) {
    console.warn('【专业模块】读取 localStorage 失败', e)
  }
  return createInitialProfessionalState()
}

function saveState(state) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(state))
}

const state = ref(loadState())

const gradeLabel = {
  MILD: '轻度',
  MODERATE: '中度',
  SEVERE: '重度',
  CRITICAL: '严重',
}

const defectStatusLabel = {
  discovered: '待复核',
  reviewing: '复核中',
  confirmed: '已确认',
  remediating: '处置中',
  closed: '已销项',
}

const batchStatusLabel = {
  pending: '待执行',
  running: '执行中',
  completed: '已完成',
  failed: '失败',
  cancelled: '已取消',
}

export function useProfessionalModulesStore() {
  const defects = computed(() => state.value.defects)
  const batchJobs = computed(() => state.value.batchJobs)
  const reports = computed(() => state.value.reports)

  function persist() {
    saveState(state.value)
  }

  function nextId(key) {
    const id = state.value.nextIds[key]
    state.value.nextIds[key] = id + 1
    return id
  }

  function listDefects(filters = {}) {
    let list = [...state.value.defects]
    const { keyword, status, grade } = filters
    if (keyword) {
      const k = keyword.toLowerCase()
      list = list.filter(
        (d) =>
          d.defect_code.toLowerCase().includes(k) ||
          d.bridge_section.toLowerCase().includes(k) ||
          d.disease_type.toLowerCase().includes(k) ||
          (d.media_name || '').toLowerCase().includes(k),
      )
    }
    if (status) list = list.filter((d) => d.status === status)
    if (grade) list = list.filter((d) => d.grade === grade)
    return list.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))
  }

  function updateDefectStatus(defectId, status, extra = {}) {
    const d = state.value.defects.find((x) => x.defect_id === defectId)
    if (!d) return { ok: false, message: '安全隐患记录不存在' }
    d.status = status
    d.updated_at = new Date().toISOString()
    Object.assign(d, extra)
    persist()
    return { ok: true, defect: d }
  }

  function reviewDefect(defectId, { reviewer, review_note, pass }) {
    const d = state.value.defects.find((x) => x.defect_id === defectId)
    if (!d) return { ok: false, message: '安全隐患记录不存在' }
    d.reviewer = reviewer
    d.review_note = review_note
    d.status = pass ? DEFECT_STATUS.CONFIRMED : DEFECT_STATUS.DISCOVERED
    d.updated_at = new Date().toISOString()
    persist()
    return { ok: true, defect: d }
  }

  function importDefectsFromDetections(detections) {
    let added = 0
    const existingIds = new Set(
      state.value.defects.map((d) => d.detection_id).filter(Boolean),
    )
    for (const det of detections) {
      if (det.status !== 'COMPLETED' || !det.disease_grade) continue
      if (existingIds.has(det.detection_id)) continue
      const id = nextId('defect')
      state.value.defects.unshift({
        defect_id: id,
        defect_code: `DEF-2026-${String(id).padStart(3, '0')}`,
        bridge_section: det.media_name?.split('_')[0] || '未分区',
        component: '—',
        disease_type: 'AI 检测隐患',
        grade: det.disease_grade,
        severity_score: det.disease_severity_score,
        status: DEFECT_STATUS.DISCOVERED,
        detection_id: det.detection_id,
        media_name: det.media_name,
        model_name: det.model_name,
        reviewer: '',
        review_note: '',
        discovered_at: det.updated_at || new Date().toISOString(),
        updated_at: new Date().toISOString(),
      })
      existingIds.add(det.detection_id)
      added++
    }
    persist()
    return { ok: true, added }
  }

  function listBatchJobs() {
    return [...state.value.batchJobs].sort(
      (a, b) => new Date(b.created_at) - new Date(a.created_at),
    )
  }

  function createBatchJob({ batch_name, model_id, model_name, mediaItems }) {
    if (!mediaItems?.length) return { ok: false, message: '请至少选择一条媒体' }
    const t = new Date().toISOString()
    const job = {
      batch_id: nextId('batch'),
      batch_name: batch_name || `批量检测_${new Date().toLocaleString('zh-CN')}`,
      model_id,
      model_name,
      status: BATCH_STATUS.PENDING,
      progress: 0,
      total_count: mediaItems.length,
      success_count: 0,
      fail_count: 0,
      items: mediaItems.map((m) => ({
        media_id: m.media_id,
        media_name: m.media_name,
        status: 'pending',
        detection_id: null,
        error: '',
      })),
      created_at: t,
      finished_at: null,
    }
    state.value.batchJobs.unshift(job)
    persist()
    return { ok: true, job }
  }

  function startBatchJob(batchId) {
    const job = state.value.batchJobs.find((j) => j.batch_id === batchId)
    if (!job) return { ok: false, message: '任务不存在' }
    if (job.status === BATCH_STATUS.RUNNING) {
      return { ok: false, message: '任务已在执行中' }
    }
    job.status = BATCH_STATUS.RUNNING
    job.progress = 0
    job.success_count = 0
    job.fail_count = 0
    persist()
    return { ok: true, job }
  }

  function advanceBatchJob(batchId) {
    const job = state.value.batchJobs.find((j) => j.batch_id === batchId)
    if (!job || job.status !== BATCH_STATUS.RUNNING) {
      return { ok: false, message: '任务未在执行' }
    }
    const pending = job.items.find((i) => i.status === 'pending')
    if (!pending) {
      job.status = BATCH_STATUS.COMPLETED
      job.progress = 100
      job.finished_at = new Date().toISOString()
      persist()
      return { ok: true, job, done: true }
    }
    const fail = Math.random() < 0.08
    if (fail) {
      pending.status = 'failed'
      pending.error = '推理超时或媒体不可读'
      job.fail_count += 1
    } else {
      pending.status = 'completed'
      pending.detection_id = 10000 + job.batch_id * 10 + job.success_count
      job.success_count += 1
      const detId = pending.detection_id
      importDefectsFromDetections([
        {
          detection_id: detId,
          status: 'COMPLETED',
          disease_grade: ['MILD', 'MODERATE', 'SEVERE'][job.success_count % 3],
          disease_severity_score: 0.2 + Math.random() * 0.6,
          media_name: pending.media_name,
          model_name: job.model_name,
          updated_at: new Date().toISOString(),
        },
      ])
    }
    const done = job.items.filter((i) => i.status !== 'pending').length
    job.progress = Math.round((done / job.total_count) * 100)
    if (done >= job.total_count) {
      job.status = job.fail_count === job.total_count ? BATCH_STATUS.FAILED : BATCH_STATUS.COMPLETED
      job.finished_at = new Date().toISOString()
    }
    persist()
    return { ok: true, job, done: job.status !== BATCH_STATUS.RUNNING }
  }

  function cancelBatchJob(batchId) {
    const job = state.value.batchJobs.find((j) => j.batch_id === batchId)
    if (!job) return { ok: false, message: '任务不存在' }
    if (job.status === BATCH_STATUS.COMPLETED) {
      return { ok: false, message: '已完成任务无法取消' }
    }
    job.status = BATCH_STATUS.CANCELLED
    job.finished_at = new Date().toISOString()
    persist()
    return { ok: true, job }
  }

  function generateReport({ template_id, title, bridge_name, period, created_by }) {
    const tpl = REPORT_TEMPLATES.find((t) => t.template_id === template_id)
    if (!tpl) return { ok: false, message: '模板不存在' }
    const t = new Date().toISOString()
    const report = {
      report_id: nextId('report'),
      template_id,
      template_name: tpl.name,
      title: title || `${tpl.name}_${new Date().toISOString().slice(0, 10)}`,
      bridge_name: bridge_name || '示例桥梁',
      period: period || '最近 7 日',
      status: 'generated',
      file_name: `${title || tpl.name}_${Date.now()}.xlsx`,
      created_at: t,
      created_by: created_by || 'admin',
      summary: {
        detection_count: state.value.batchJobs.reduce((s, j) => s + (j.success_count || 0), 0) + 12,
        defect_count: state.value.defects.length,
        open_defects: state.value.defects.filter((d) => d.status !== DEFECT_STATUS.CLOSED).length,
        alert_count: 3,
      },
    }
    state.value.reports.unshift(report)
    persist()
    return { ok: true, report }
  }

  function getReportExportRows(report) {
    const defects = state.value.defects
    return defects.map((d) => ({
      隐患编号: d.defect_code,
      桥区: d.bridge_section,
      构件: d.component,
      隐患类型: d.disease_type,
      等级: gradeLabel[d.grade] || d.grade,
      严重度: d.severity_score,
      状态: defectStatusLabel[d.status] || d.status,
      关联检测ID: d.detection_id || '',
      媒体: d.media_name || '',
    }))
  }

  return {
    defects,
    batchJobs,
    reports,
    REPORT_TEMPLATES,
    DEFECT_STATUS,
    BATCH_STATUS,
    gradeLabel,
    defectStatusLabel,
    batchStatusLabel,
    listDefects,
    updateDefectStatus,
    reviewDefect,
    importDefectsFromDetections,
    listBatchJobs,
    createBatchJob,
    startBatchJob,
    advanceBatchJob,
    cancelBatchJob,
    generateReport,
    getReportExportRows,
  }
}
