<template>
  <div class="outline-result-panel">
    <!-- 头部 -->
    <header class="result-header">
      <h2 class="result-title">生成结果预览</h2>
      <div v-if="hasContent" class="header-actions">
        <button @click="copyAll" class="action-btn">
          <IconLibrary name="copy" :size="14" />
          <span>复制全文</span>
        </button>
        <button @click="exportToWord" class="action-btn primary">
          <IconLibrary name="download" :size="14" />
          <span>导出 Word</span>
        </button>
      </div>
    </header>

    <!-- 内容区 -->
    <div class="result-content">
      <!-- 空状态 -->
      <div v-if="!hasContent" class="empty-state">
        <div class="empty-icon">
          <IconLibrary name="document" :size="48" />
        </div>
        <p>输入大纲并点击生成</p>
        <p class="empty-hint">生成的内容将在这里实时预览</p>
      </div>

      <!-- 生成的内容 -->
      <div v-else class="generated-sections">
        <div
          v-for="(section, index) in flatSections"
          :key="index"
          v-show="section.content"
          class="section-block"
        >
          <div class="section-heading" :class="'level-' + section.level">
            {{ getHeadingPrefix(section.level) }}{{ section.title }}
          </div>
          <div class="section-content" v-html="renderMarkdown(section.content)"></div>
        </div>
      </div>
    </div>

    <!-- 统计信息 -->
    <footer v-if="hasContent" class="result-footer">
      <span>总计 {{ totalWords }} 字</span>
      <span>{{ generatedCount }}/{{ flatSections.length }} 章节已生成</span>
    </footer>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { storeToRefs } from 'pinia'
import { useAppStore } from '../../stores/app'
import { marked } from 'marked'
import IconLibrary from '../icons/IconLibrary.vue'

const appStore = useAppStore()
const { outlineWriterState } = storeToRefs(appStore)

const parsedSections = computed(() => outlineWriterState.value.parsedSections)

// 扁平化章节列表
const flatSections = computed(() => {
  const result = []
  const flatten = (sections) => {
    sections.forEach(s => {
      result.push(s)
      if (s.children && s.children.length > 0) {
        flatten(s.children)
      }
    })
  }
  flatten(parsedSections.value)
  return result
})

const hasContent = computed(() => 
  flatSections.value.some(s => s.content)
)

const generatedCount = computed(() => 
  flatSections.value.filter(s => s.content).length
)

const totalWords = computed(() => 
  flatSections.value.reduce((sum, s) => sum + (s.content?.length || 0), 0)
)

// 获取标题前缀
const getHeadingPrefix = (level) => {
  if (level === 1) return ''
  if (level === 2) return ''
  return ''
}

// 渲染 Markdown
const renderMarkdown = (content) => {
  if (!content) return ''
  return marked.parse(content)
}

// 复制全文
const copyAll = async () => {
  const fullText = flatSections.value
    .filter(s => s.content)
    .map(s => {
      const prefix = '#'.repeat(s.level) + ' '
      return `${prefix}${s.title}\n\n${s.content}`
    })
    .join('\n\n')
  
  try {
    await navigator.clipboard.writeText(fullText)
    alert('已复制到剪贴板')
  } catch (e) {
    console.error('复制失败:', e)
  }
}

// 导出 Word
const exportToWord = async () => {
  try {
    const { Document, Paragraph, TextRun, Packer, HeadingLevel } = await import('docx')
    const { saveAs } = await import('file-saver')
    
    const children = []
    flatSections.value.forEach(section => {
      if (section.content) {
        const headingLevel = section.level === 1 ? HeadingLevel.HEADING_1 
          : section.level === 2 ? HeadingLevel.HEADING_2 
          : HeadingLevel.HEADING_3
        
        children.push(
          new Paragraph({
            text: section.title,
            heading: headingLevel
          }),
          new Paragraph({
            children: [new TextRun(section.content)]
          })
        )
      }
    })
    
    const doc = new Document({
      sections: [{ properties: {}, children }]
    })
    
    const blob = await Packer.toBlob(doc)
    saveAs(blob, `提纲写作_${new Date().toLocaleDateString()}.docx`)
  } catch (error) {
    console.error('导出失败:', error)
    alert('导出失败')
  }
}
</script>

<style scoped>
.outline-result-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: var(--bg-primary);
  overflow: hidden;
}

.result-header {
  padding: var(--space-4) var(--space-6);
  border-bottom: 1px solid var(--border-default);
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: var(--bg-secondary);
}

.result-title {
  font-size: var(--text-lg);
  font-weight: var(--font-semibold);
  color: var(--text-primary);
}

.header-actions {
  display: flex;
  gap: var(--space-2);
}

.action-btn {
  display: flex;
  align-items: center;
  gap: var(--space-1);
  padding: var(--space-2) var(--space-3);
  font-size: var(--text-xs);
  border-radius: var(--radius-md);
  background: var(--bg-elevated);
  color: var(--text-secondary);
  border: 1px solid var(--border-default);
  cursor: pointer;
  transition: all 0.15s;
}

.action-btn:hover {
  background: var(--bg-primary);
  color: var(--text-primary);
}

.action-btn.primary {
  background: var(--accent-primary);
  color: white;
  border: none;
}

.action-btn.primary:hover {
  background: var(--accent-primary-hover);
}

.result-content {
  flex: 1;
  overflow-y: auto;
  padding: var(--space-6);
}

.empty-state {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--text-muted);
}

.empty-icon {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--bg-secondary);
  border: 1px solid var(--border-default);
  border-radius: var(--radius-xl);
  margin-bottom: var(--space-4);
  opacity: 0.5;
}

.empty-hint {
  font-size: var(--text-xs);
  margin-top: var(--space-1);
}

.generated-sections {
  max-width: 800px;
  margin: 0 auto;
}

.section-block {
  margin-bottom: var(--space-6);
}

.section-heading {
  font-weight: var(--font-bold);
  color: var(--text-primary);
  margin-bottom: var(--space-3);
}

.section-heading.level-1 {
  font-size: var(--text-xl);
  border-bottom: 2px solid var(--accent-primary);
  padding-bottom: var(--space-2);
}

.section-heading.level-2 {
  font-size: var(--text-lg);
  color: var(--accent-primary);
}

.section-heading.level-3 {
  font-size: var(--text-base);
  color: var(--text-secondary);
}

.section-content {
  font-size: var(--text-sm);
  line-height: 1.8;
  color: var(--text-primary);
}

.section-content :deep(p) {
  margin-bottom: var(--space-3);
}

.result-footer {
  padding: var(--space-3) var(--space-6);
  border-top: 1px solid var(--border-default);
  background: var(--bg-secondary);
  display: flex;
  justify-content: space-between;
  font-size: var(--text-xs);
  color: var(--text-muted);
}
</style>
