<template>
  <a-drawer v-model:open="drawerOpen" title="文档版本" placement="right" :width="520">
    <a-spin :spinning="loading">
      <a-empty v-if="!versions.length && !loading" description="暂无版本信息" />

      <a-timeline v-else>
        <a-timeline-item v-for="version in versions" :key="version.doc_id" :color="version.doc_id === currentDocId ? 'blue' : 'gray'">
          <div class="version-item">
            <div class="version-title-row">
              <strong>{{ version.title }}</strong>
              <a-tag v-if="version.doc_id === currentDocId" color="blue">当前版本</a-tag>
            </div>
            <div class="version-meta">
              <span v-if="version.doc_number">{{ version.doc_number }}</span>
              <span v-if="version.issuing_org">{{ version.issuing_org }}</span>
              <span v-if="version.publish_date">{{ version.publish_date }}</span>
            </div>
            <div class="version-actions">
              <a-button type="link" size="small" @click="emit('select', version.doc_id)">查看版本</a-button>
            </div>
          </div>
        </a-timeline-item>
      </a-timeline>
    </a-spin>
  </a-drawer>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { getDocumentVersions } from '@/api/document'
import type { DocumentVersion } from '@/types/document'

const props = defineProps<{
  open: boolean
  contentHash?: string
  currentDocId?: string
}>()

const emit = defineEmits<{
  (e: 'update:open', value: boolean): void
  (e: 'select', docId: string): void
}>()

const loading = ref(false)
const versions = ref<DocumentVersion[]>([])

const drawerOpen = computed({
  get: () => props.open,
  set: (value: boolean) => emit('update:open', value),
})

async function loadVersions() {
  if (!props.contentHash) {
    versions.value = []
    return
  }

  loading.value = true
  try {
    const data = await getDocumentVersions(props.contentHash)
    versions.value = data.versions || []
  } catch (error) {
    console.error('Failed to load document versions:', error)
    versions.value = []
  } finally {
    loading.value = false
  }
}

watch(
  () => [props.open, props.contentHash],
  ([open, contentHash]) => {
    if (open && contentHash) {
      loadVersions()
    }
  },
  { immediate: true },
)
</script>

<style scoped lang="less">
.version-item {
  .version-title-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    margin-bottom: 6px;
  }

  .version-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    color: #8c8c8c;
    font-size: 12px;
    margin-bottom: 4px;
  }

  .version-actions {
    margin-top: 4px;
  }
}
</style>