<template>
  <aside 
    v-if="visible && documentId"
    class="w-80 h-screen flex flex-col border-l border-slate-700 bg-slate-800 shrink-0"
  >
    <!-- 头部 -->
    <header class="p-4 border-b border-slate-700 flex items-center justify-between">
      <h2 class="font-bold text-white flex items-center gap-2">
        <IconLibrary name="clock" :size="18" /> 版本历史
      </h2>
      <button
        @click="$emit('close')"
        class="text-slate-400 hover:text-white transition"
      >
        <IconLibrary name="close" :size="18" />
      </button>
    </header>

    <!-- 加载状态 -->
    <div v-if="isLoading" class="flex-1 flex items-center justify-center">
      <span class="text-slate-500 animate-pulse">加载中...</span>
    </div>

    <!-- 版本列表 -->
    <div v-else-if="versions.length > 0" class="flex-1 overflow-y-auto p-4 space-y-3">
      <div 
        v-for="(version, idx) in versions" 
        :key="version.id"
        :class="[
          'p-3 rounded-lg border transition',
          idx === 0 
            ? 'bg-blue-900/30 border-blue-500' 
            : 'bg-slate-900/50 border-slate-700 hover:border-slate-500'
        ]"
      >
        <!-- 版本号和时间 -->
        <div class="flex items-center justify-between mb-2">
          <div class="flex items-center gap-2">
            <span class="font-bold text-white">v{{ version.version_number }}</span>
            <span v-if="idx === 0" class="text-xs px-1.5 py-0.5 rounded bg-blue-600 text-white">
              当前
            </span>
          </div>
          <span class="text-xs text-slate-500">{{ formatDate(version.created_at) }}</span>
        </div>
        
        <!-- 变更说明 -->
        <p class="text-xs text-slate-400 mb-3">
          {{ version.change_note || '无变更说明' }}
        </p>
        
        <!-- 操作按钮 -->
        <div v-if="idx > 0" class="flex gap-2">
          <button 
            @click="restoreVersion(version)"
            class="flex-1 text-xs py-1.5 rounded bg-amber-600 text-white hover:bg-amber-500 transition"
          >
            恢复
          </button>
          <button 
            @click="compareVersion(version)"
            class="flex-1 text-xs py-1.5 rounded bg-slate-600 text-white hover:bg-slate-500 transition"
          >
            对比
          </button>
        </div>
      </div>
    </div>

    <!-- 无版本记录 -->
    <div v-else class="flex-1 flex flex-col items-center justify-center text-slate-500">
      <div class="w-12 h-12 flex items-center justify-center mb-2">
        <IconLibrary name="clipboard" :size="32" />
      </div>
      <p class="text-sm">暂无版本记录</p>
      <p class="text-xs text-slate-600 mt-1">保存文稿后将自动记录版本</p>
    </div>

    <!-- 版本对比弹窗 -->
    <div 
      v-if="showCompareModal" 
      class="fixed inset-0 bg-black/70 flex items-center justify-center z-50"
      @click.self="showCompareModal = false"
    >
      <div class="bg-slate-800 rounded-lg w-[900px] max-h-[80vh] flex flex-col border border-slate-600">
        <header class="p-4 border-b border-slate-700 flex items-center justify-between">
          <div>
            <h3 class="font-bold text-white">
              版本对比：v{{ comparingVersion?.version_number }} → 当前版本
            </h3>
            <div class="text-xs text-slate-500 mt-1 flex gap-4">
              <span><span class="inline-block w-3 h-3 rounded bg-red-500/50 mr-1"></span>删除</span>
              <span><span class="inline-block w-3 h-3 rounded bg-green-500/50 mr-1"></span>新增</span>
              <span><span class="inline-block w-3 h-3 rounded bg-amber-500/50 mr-1"></span>修改</span>
            </div>
          </div>
          <button
            @click="showCompareModal = false"
            class="text-slate-400 hover:text-white"
          ><IconLibrary name="close" :size="18" /></button>
        </header>
        <div class="flex-1 overflow-y-auto p-4">
          <div class="flex gap-4">
            <!-- 旧版本（带高亮） -->
            <div class="flex-1">
              <div class="text-xs text-amber-400 mb-2 font-medium">
                v{{ comparingVersion?.version_number }} 版本
              </div>
              <div class="bg-slate-900 rounded-lg p-3 border border-slate-700 text-sm text-slate-300 max-h-[400px] overflow-y-auto leading-relaxed">
                <template v-for="(segment, idx) in diffSegments" :key="'old-' + idx">
                  <span 
                    v-if="segment.type === 'unchanged'"
                    class="text-slate-300"
                  >{{ segment.original }}</span>
                  <span 
                    v-else-if="segment.type === 'modified'"
                    class="bg-amber-500/30 text-amber-200 px-0.5 rounded"
                  >{{ segment.original }}</span>
                  <span 
                    v-else-if="segment.type === 'removed'"
                    class="bg-red-500/30 text-red-200 px-0.5 rounded line-through"
                  >{{ segment.original }}</span>
                  <!-- added 类型在旧版本中不显示 -->
                </template>
              </div>
            </div>
            <!-- 当前版本（带高亮） -->
            <div class="flex-1">
              <div class="text-xs text-blue-400 mb-2 font-medium">
                当前版本
              </div>
              <div class="bg-slate-900 rounded-lg p-3 border border-slate-700 text-sm text-slate-300 max-h-[400px] overflow-y-auto leading-relaxed">
                <template v-for="(segment, idx) in diffSegments" :key="'new-' + idx">
                  <span 
                    v-if="segment.type === 'unchanged'"
                    class="text-slate-300"
                  >{{ segment.rewritten }}</span>
                  <span 
                    v-else-if="segment.type === 'modified'"
                    class="bg-amber-500/30 text-amber-200 px-0.5 rounded"
                  >{{ segment.rewritten }}</span>
                  <span 
                    v-else-if="segment.type === 'added'"
                    class="bg-green-500/30 text-green-200 px-0.5 rounded"
                  >{{ segment.rewritten }}</span>
                  <!-- removed 类型在新版本中不显示 -->
                </template>
              </div>
            </div>
          </div>
        </div>
        <footer class="p-4 border-t border-slate-700 flex justify-between items-center">
          <div class="text-xs text-slate-500">
            共 {{ diffStats.total }} 处差异
            <span v-if="diffStats.modified > 0" class="text-amber-400 ml-2">{{ diffStats.modified }} 处修改</span>
            <span v-if="diffStats.added > 0" class="text-green-400 ml-2">{{ diffStats.added }} 处新增</span>
            <span v-if="diffStats.removed > 0" class="text-red-400 ml-2">{{ diffStats.removed }} 处删除</span>
          </div>
          <button 
            @click="showCompareModal = false"
            class="px-4 py-2 text-sm bg-slate-600 text-white rounded-lg hover:bg-slate-500"
          >
            关闭
          </button>
        </footer>
      </div>
    </div>
  </aside>
</template>

<script setup>
import { ref, watch, computed, defineProps, defineEmits } from 'vue'
import { getDocumentVersions, getDocumentById, saveDocumentVersion, updateDocument } from '../db/index.js'
import { computeDiff, getDiffStats } from '../utils/textDiff.js'
import IconLibrary from './icons/IconLibrary.vue'

const props = defineProps({
  visible: Boolean,
  documentId: String,
  currentContent: String
})

const emit = defineEmits(['close', 'restore'])

// 状态
const isLoading = ref(false)
const versions = ref([])
const showCompareModal = ref(false)
const comparingVersion = ref(null)
const diffSegments = ref([])

// 差异统计
const diffStats = computed(() => {
  return getDiffStats(diffSegments.value)
})

// 加载版本历史
const loadVersions = async () => {
  if (!props.documentId) {
    versions.value = []
    return
  }
  
  isLoading.value = true
  try {
    versions.value = getDocumentVersions(props.documentId)
  } catch (error) {
    console.error('加载版本历史失败:', error)
    versions.value = []
  } finally {
    isLoading.value = false
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', { 
    month: 'numeric', 
    day: 'numeric',
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

// 恢复版本
const restoreVersion = async (version) => {
  if (!confirm(`确定要恢复到 v${version.version_number} 版本吗？\n当前内容将保存为新版本。`)) {
    return
  }
  
  try {
    // 先保存当前内容为新版本
    saveDocumentVersion(props.documentId, props.currentContent, '恢复前自动保存')
    
    // 更新文稿内容为旧版本
    updateDocument(props.documentId, { content: version.content })
    
    // 触发恢复事件，通知父组件刷新
    emit('restore', version.content)
    
    // 重新加载版本列表
    await loadVersions()
    
    alert(`已恢复到 v${version.version_number} 版本`)
  } catch (error) {
    console.error('恢复版本失败:', error)
    alert('恢复失败，请重试')
  }
}

// 对比版本
const compareVersion = (version) => {
  comparingVersion.value = version
  // 计算差异
  diffSegments.value = computeDiff(version.content || '', props.currentContent || '')
  showCompareModal.value = true
}

// 监听文稿ID变化
watch(() => props.documentId, () => {
  loadVersions()
}, { immediate: true })

// 监听面板显示
watch(() => props.visible, (newVal) => {
  if (newVal) {
    loadVersions()
  }
})
</script>

