/**
 * 研究报告导出工具模块
 * 提供 Markdown 导出、Word 兼容版导出、汇报版导出的 HTML 构建逻辑。
 */
import type MarkdownIt from 'markdown-it'
import type { ResearchTaskDraft, ResearchPlan, ResearchReport } from '@/types/research'
import type { ResearchReference } from '@/types/document'

/** 导出所需的研究数据快照 */
export interface ResearchExportData {
  sessionTitle: string
  task: ResearchTaskDraft
  plan: ResearchPlan | undefined
  report: ResearchReport
  references: ResearchReference[]
}

function escapeHtml(value: string): string {
  return value
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;')
}

function renderTextList(items: string[], ordered = false): string {
  if (!items.length) return '<p class="empty">暂无</p>'
  const tag = ordered ? 'ol' : 'ul'
  return `<${tag}>${items.map((item) => `<li>${escapeHtml(item)}</li>`).join('')}</${tag}>`
}

export function sanitizeFileName(value: string): string {
  return value.replace(/[\\/:*?"<>|]/g, '_').trim() || 'research-report'
}

export function buildReportBaseName(sessionTitle: string, suffix: string): string {
  return `${sanitizeFileName(sessionTitle)}-${suffix}`
}

export function triggerBlobDownload(blob: Blob, filename: string): void {
  const url = window.URL.createObjectURL(blob)
  const link = window.document.createElement('a')
  link.href = url
  link.download = filename
  link.click()
  window.URL.revokeObjectURL(url)
}

/** 构建 Markdown 格式的完整研究报告 */
export function buildExportMarkdown(data: ResearchExportData): string {
  const { sessionTitle, task, plan, report, references } = data
  const lines: string[] = []
  lines.push(`# ${sessionTitle}`)
  lines.push('')
  lines.push('## 研究任务')
  lines.push(`- 主题：${task.topic || '未填写'}`)
  lines.push(`- 问题：${task.question || '未填写'}`)
  if (task.goal) lines.push(`- 目标：${task.goal}`)
  if (task.timeRange) lines.push(`- 时间范围：${task.timeRange}`)
  if (task.regionScope) lines.push(`- 地域范围：${task.regionScope}`)
  if (task.orgScope) lines.push(`- 部门范围：${task.orgScope}`)
  lines.push('')

  if (plan) {
    lines.push('## 研究计划')
    lines.push(plan.summary)
    lines.push('')
    if (plan.subQuestions.length) {
      lines.push('### 子问题')
      plan.subQuestions.forEach((item) => lines.push(`1. ${item}`))
      lines.push('')
    }
  }

  if (report.executiveSummary) {
    lines.push('## 执行摘要')
    lines.push(report.executiveSummary)
    lines.push('')
  }

  if (report.findings.length) {
    lines.push('## 关键发现')
    report.findings.forEach((item) => {
      lines.push(`### ${item.title}`)
      lines.push(item.content)
      lines.push('')
    })
  }

  if (report.sections.length) {
    lines.push('## 章节化报告')
    report.sections.forEach((item) => {
      lines.push(`### ${item.title}`)
      if (item.summary) lines.push(item.summary)
      lines.push(item.content)
      lines.push('')
    })
  }

  if (report.conflicts.length) {
    lines.push('## 冲突与缺口')
    report.conflicts.forEach((item) => {
      lines.push(`### ${item.title}`)
      lines.push(item.content)
      lines.push('')
    })
  }

  if (report.openQuestions.length) {
    lines.push('## 待确认问题')
    report.openQuestions.forEach((item) => {
      lines.push(`- ${item.question}`)
      if (item.reason) lines.push(`  原因：${item.reason}`)
    })
    lines.push('')
  }

  if (report.onePageSummary) {
    lines.push('## 一页式摘要')
    lines.push(report.onePageSummary)
    lines.push('')
  }

  if (report.recommendedNextSteps.length) {
    lines.push('## 建议后续方向')
    report.recommendedNextSteps.forEach((item) => lines.push(`1. ${item}`))
    lines.push('')
  }

  if (references.length) {
    lines.push('## 引用材料')
    references.forEach((item, index) => {
      lines.push(`- [${index + 1}] ${item.title}${item.doc_number ? `（${item.doc_number}）` : ''}`)
    })
  }

  return lines.join('\n')
}

/** 构建 Word 兼容 HTML 格式的完整研究报告 */
export function buildWordReportHtml(data: ResearchExportData, markdown: MarkdownIt): string {
  const { sessionTitle, task, plan, report, references } = data
  const renderMarkdownHtml = (content: string) => markdown.render(content || '')
  const generatedAt = new Date().toLocaleString('zh-CN', { hour12: false })
  const taskMeta: [string, string][] = [
    ['研究主题', task.topic || '未填写'],
    ['核心问题', task.question || '未填写'],
    ['研究目标', task.goal || '未填写'],
    ['时间范围', task.timeRange || '未填写'],
    ['地域范围', task.regionScope || '未填写'],
    ['部门范围', task.orgScope || '未填写'],
  ]

  const planHtml = plan
    ? `
      <section class="panel">
        <h2>研究计划</h2>
        <p>${escapeHtml(plan.summary)}</p>
        <div class="grid two-col">
          <div>
            <h3>子问题</h3>
            ${renderTextList(plan.subQuestions)}
          </div>
          <div>
            <h3>检索重点</h3>
            ${renderTextList(plan.retrievalFocus)}
          </div>
        </div>
      </section>
    `
    : ''

  const findingsHtml = report.findings.length
    ? `
      <section class="panel">
        <h2>关键发现</h2>
        ${report.findings
          .map((item) => `
            <article class="block">
              <h3>${escapeHtml(item.title)}</h3>
              ${renderMarkdownHtml(item.content)}
            </article>
          `)
          .join('')}
      </section>
    `
    : ''

  const sectionHtml = report.sections.length
    ? `
      <section class="panel">
        <h2>章节化报告</h2>
        ${report.sections
          .map((item) => `
            <article class="block">
              <h3>${escapeHtml(item.title)}</h3>
              ${item.summary ? `<p class="section-summary">${escapeHtml(item.summary)}</p>` : ''}
              ${renderMarkdownHtml(item.content)}
            </article>
          `)
          .join('')}
      </section>
    `
    : ''

  const conflictHtml = report.conflicts.length
    ? `
      <section class="panel">
        <h2>冲突与缺口</h2>
        ${report.conflicts
          .map((item) => `
            <article class="block">
              <h3>${escapeHtml(item.title)}</h3>
              ${renderMarkdownHtml(item.content)}
            </article>
          `)
          .join('')}
      </section>
    `
    : ''

  const questionHtml = report.openQuestions.length
    ? `
      <section class="panel">
        <h2>待确认问题</h2>
        ${renderTextList(report.openQuestions.map((item) => `${item.question}${item.reason ? `：${item.reason}` : ''}`))}
      </section>
    `
    : ''

  const referencesHtml = references.length
    ? `
      <section class="panel">
        <h2>引用材料</h2>
        <ol>
          ${references
            .map((item) => `<li>${escapeHtml(item.title)}${item.doc_number ? `（${escapeHtml(item.doc_number)}）` : ''}</li>`)
            .join('')}
        </ol>
      </section>
    `
    : ''

  return `<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>${escapeHtml(sessionTitle)}</title>
    <style>
      @page { margin: 20mm 16mm 22mm; }
      @page :first { margin-top: 18mm; }
      body { margin: 0; font-family: "Microsoft YaHei", "PingFang SC", sans-serif; color: #1f2937; background: #eef2f7; }
      .page { width: 210mm; min-height: 297mm; margin: 0 auto; padding: 18mm 16mm 22mm; background: #ffffff; box-sizing: border-box; }
      .page-header { position: running(header); font-size: 10px; color: #94a3b8; border-bottom: 1px solid #e2e8f0; padding-bottom: 4px; }
      .page-footer { position: running(footer); font-size: 10px; color: #94a3b8; text-align: center; border-top: 1px solid #e2e8f0; padding-top: 4px; }
      .cover { border-bottom: 2px solid #1d4ed8; padding-bottom: 12px; margin-bottom: 20px; }
      .eyebrow { color: #1d4ed8; font-size: 12px; letter-spacing: 1px; text-transform: uppercase; }
      h1 { margin: 10px 0 8px; font-size: 28px; line-height: 1.3; }
      .meta-line { color: #475569; font-size: 13px; }
      .grid { display: grid; gap: 14px; }
      .two-col { grid-template-columns: repeat(2, minmax(0, 1fr)); }
      .meta-grid { margin-top: 18px; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px 18px; }
      .meta-item { padding: 10px 12px; background: #f8fafc; border: 1px solid #dbe4f0; border-radius: 10px; }
      .meta-item strong { display: block; margin-bottom: 6px; color: #0f172a; font-size: 12px; }
      .panel { margin-top: 18px; padding: 16px 18px; border: 1px solid #dbe4f0; border-radius: 14px; background: #ffffff; }
      h2 { margin: 0 0 12px; font-size: 18px; color: #0f172a; }
      h3 { margin: 0 0 8px; font-size: 15px; color: #1e293b; }
      p { margin: 0 0 10px; line-height: 1.72; }
      ul, ol { margin: 0; padding-left: 20px; }
      li { margin-bottom: 6px; line-height: 1.68; }
      .block + .block { margin-top: 14px; padding-top: 14px; border-top: 1px dashed #dbe4f0; }
      .section-summary { color: #475569; font-size: 13px; }
      .empty { color: #94a3b8; }
    </style>
  </head>
  <body>
    <div class="page-header">${escapeHtml(sessionTitle)} &mdash; 研究报告</div>
    <div class="page-footer">由政务文档智能检索系统生成</div>
    <main class="page">
      <header class="cover">
        <div class="eyebrow">Deep Research Report</div>
        <h1>${escapeHtml(sessionTitle)}</h1>
        <div class="meta-line">生成时间：${escapeHtml(generatedAt)}</div>
      </header>

      <nav class="panel" style="margin-bottom: 18px">
        <h2>目录</h2>
        <ol style="line-height: 2">
          <li>研究任务</li>
          ${plan ? '<li>研究计划</li>' : ''}
          ${report.executiveSummary ? '<li>执行摘要</li>' : ''}
          ${report.findings.length ? '<li>关键发现</li>' : ''}
          ${report.sections.length ? report.sections.map((s, i) => `<li>第${i + 1}节 ${escapeHtml(s.title)}</li>`).join('') : ''}
          ${report.conflicts.length ? '<li>冲突与缺口</li>' : ''}
          ${report.openQuestions.length ? '<li>待确认问题</li>' : ''}
          ${report.onePageSummary ? '<li>一页式摘要</li>' : ''}
          ${report.recommendedNextSteps.length ? '<li>建议后续方向</li>' : ''}
          ${references.length ? '<li>引用材料</li>' : ''}
        </ol>
      </nav>

      <section class="panel">
        <h2>研究任务</h2>
        <div class="meta-grid">
          ${taskMeta
            .map(([label, value]) => `
              <div class="meta-item">
                <strong>${escapeHtml(label)}</strong>
                <span>${escapeHtml(value)}</span>
              </div>
            `)
            .join('')}
        </div>
      </section>

      ${planHtml}

      ${report.executiveSummary
        ? `
          <section class="panel">
            <h2>执行摘要</h2>
            ${renderMarkdownHtml(report.executiveSummary)}
          </section>
        `
        : ''}

      ${findingsHtml}
      ${sectionHtml}
      ${conflictHtml}
      ${questionHtml}

      ${report.onePageSummary
        ? `
          <section class="panel">
            <h2>一页式摘要</h2>
            ${renderMarkdownHtml(report.onePageSummary)}
          </section>
        `
        : ''}

      ${report.recommendedNextSteps.length
        ? `
          <section class="panel">
            <h2>建议后续方向</h2>
            ${renderTextList(report.recommendedNextSteps, true)}
          </section>
        `
        : ''}

      ${referencesHtml}
    </main>
  </body>
</html>`
}

/** 构建汇报版 HTML（一页式摘要 + 关键发现 + 风险 + 建议动作） */
export function buildBriefingReportHtml(data: ResearchExportData, markdown: MarkdownIt): string {
  const { sessionTitle, task, report, references } = data
  const renderMarkdownHtml = (content: string) => markdown.render(content || '')
  const generatedAt = new Date().toLocaleString('zh-CN', { hour12: false })
  const summary = report.onePageSummary || report.executiveSummary || '暂无可导出的摘要内容。'
  const findings = report.findings.slice(0, 3).map((item) => item.title)
  const conflicts = report.conflicts.slice(0, 3).map((item) => item.title)
  const nextSteps = report.recommendedNextSteps.slice(0, 4)
  const referenceItems = references.slice(0, 6).map((item) => item.doc_number
    ? `${item.title}（${item.doc_number}）`
    : item.title)

  return `<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>${escapeHtml(sessionTitle)}-汇报版</title>
    <style>
      body { margin: 0; background: #dce7f3; font-family: "Microsoft YaHei", "PingFang SC", sans-serif; color: #0f172a; }
      .sheet { width: 210mm; min-height: 297mm; margin: 0 auto; padding: 14mm; box-sizing: border-box; background: linear-gradient(180deg, #f8fbff 0%, #ffffff 28%); }
      .hero { padding: 18px 22px; border-radius: 20px; background: linear-gradient(135deg, #123d72 0%, #1d4ed8 65%, #60a5fa 100%); color: #ffffff; }
      .hero h1 { margin: 8px 0 10px; font-size: 30px; line-height: 1.24; }
      .hero .meta { display: flex; gap: 16px; flex-wrap: wrap; font-size: 13px; color: rgba(255,255,255,0.88); }
      .hero .eyebrow { font-size: 12px; letter-spacing: 1.4px; text-transform: uppercase; color: rgba(255,255,255,0.8); }
      .hero .summary { margin-top: 18px; padding: 16px 18px; border-radius: 16px; background: rgba(255,255,255,0.14); }
      .hero .summary h2 { margin: 0 0 10px; font-size: 16px; }
      .hero .summary p { margin: 0; line-height: 1.72; }
      .grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; margin-top: 14px; }
      .panel { padding: 16px 18px; border-radius: 18px; background: rgba(255,255,255,0.94); box-shadow: 0 10px 30px rgba(15, 23, 42, 0.08); }
      .panel h2 { margin: 0 0 12px; font-size: 16px; color: #123d72; }
      .panel p { margin: 0 0 10px; line-height: 1.68; }
      ul, ol { margin: 0; padding-left: 20px; }
      li { margin-bottom: 8px; line-height: 1.62; }
      .kpi-row { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; margin-top: 14px; }
      .kpi { padding: 14px 16px; border-radius: 16px; background: rgba(255,255,255,0.14); }
      .kpi strong { display: block; font-size: 24px; margin-bottom: 4px; }
      .footnote { margin-top: 14px; font-size: 12px; color: #475569; }
      .empty { color: #94a3b8; }
    </style>
  </head>
  <body>
    <main class="sheet">
      <section class="hero">
        <div class="eyebrow">One Page Briefing</div>
        <h1>${escapeHtml(sessionTitle)}</h1>
        <div class="meta">
          <span>生成时间：${escapeHtml(generatedAt)}</span>
          <span>研究主题：${escapeHtml(task.topic || '未填写')}</span>
          <span>核心问题：${escapeHtml(task.question || '未填写')}</span>
        </div>
        <div class="summary">
          <h2>核心判断</h2>
          ${renderMarkdownHtml(summary)}
        </div>
        <div class="kpi-row">
          <div class="kpi"><strong>${report.findings.length}</strong><span>关键发现</span></div>
          <div class="kpi"><strong>${report.conflicts.length}</strong><span>风险/缺口</span></div>
          <div class="kpi"><strong>${references.length}</strong><span>已纳入材料</span></div>
        </div>
      </section>

      <section class="grid">
        <article class="panel">
          <h2>关键发现</h2>
          ${renderTextList(findings)}
        </article>
        <article class="panel">
          <h2>风险与缺口</h2>
          ${renderTextList(conflicts)}
        </article>
        <article class="panel">
          <h2>建议动作</h2>
          ${renderTextList(nextSteps, true)}
        </article>
        <article class="panel">
          <h2>主要依据</h2>
          ${renderTextList(referenceItems)}
        </article>
      </section>

      <div class="footnote">提示：该汇报版优先提炼一页式摘要、关键发现、风险与建议动作，适合领导汇报和会议材料快速成稿。</div>
    </main>
  </body>
</html>`
}
