<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import PageCard from '@/components/PageCard.vue'
import {
  getDataset,
  previewDatasetFile,
  deleteDataset,
  downloadDatasetUrl,
  downloadFileUrl,
} from '@/api/modules/dataset'
import { DATASET_TYPE_MAP, STORAGE_MAP } from '@/constants'
import type { DatasetItem, DatasetFile } from '@/types'

const route = useRoute()
const router = useRouter()
const datasetId = route.params.id as string

const loading = ref(false)
const dataset = ref<DatasetItem | null>(null)
const selectedFileId = ref<string>('')
const previewContent = ref('')

const files = computed<DatasetFile[]>(() => dataset.value?.files || [])

const previewLines = computed(() => previewContent.value.split('\n').slice(0, 100))
const totalLines = computed(() => previewContent.value.split('\n').length)

async function loadDataset() {
  loading.value = true
  try {
    dataset.value = await getDataset(datasetId)
    if (files.value.length > 0) {
      selectedFileId.value = String(files.value[0].id || files.value[0].name)
      loadPreview()
    }
  } catch {
    // ignore
  } finally {
    loading.value = false
  }
}

async function loadPreview() {
  if (!selectedFileId.value) return
  try {
    const res = await previewDatasetFile(selectedFileId.value)
    previewContent.value = res.content || ''
  } catch {
    previewContent.value = '加载失败'
  }
}

function handleDownloadFile(file: any) {
  const fid = file.id || file.name
  window.open(downloadFileUrl(datasetId, fid), '_blank')
}

function handleDownloadAll() {
  window.open(downloadDatasetUrl(datasetId), '_blank')
}

async function handleDelete() {
  await ElMessageBox.confirm('确定要删除这个数据集吗？', '确认删除', { type: 'warning' })
  await deleteDataset(datasetId)
  ElMessage.success('删除成功')
  router.push('/dataset')
}

onMounted(loadDataset)
</script>

<template>
  <PageCard title="数据集预览" v-loading="loading">
    <template #extra>
      <el-button @click="handleDownloadAll"><i class="fa fa-download" /> 打包下载</el-button>
      <el-button type="danger" @click="handleDelete"><i class="fa fa-trash" /> 删除</el-button>
      <el-button @click="router.back()">返回</el-button>
    </template>

    <!-- 数据集信息 -->
    <el-descriptions :column="3" border style="margin-bottom: 20px">
      <el-descriptions-item label="名称">{{ dataset?.name }}</el-descriptions-item>
      <el-descriptions-item label="类型">
        {{ DATASET_TYPE_MAP[String(dataset?.type).toLowerCase()] || dataset?.type }}
      </el-descriptions-item>
      <el-descriptions-item label="存储位置">
        {{ STORAGE_MAP[dataset?.storage_type || ''] || dataset?.storage_type }}
      </el-descriptions-item>
      <el-descriptions-item label="数据条数">{{ dataset?.count || 0 }}</el-descriptions-item>
      <el-descriptions-item label="创建时间">
        {{ dataset?.create_time ? new Date(dataset.create_time).toLocaleString('zh-CN') : '-' }}
      </el-descriptions-item>
      <el-descriptions-item label="描述">{{ dataset?.description || '-' }}</el-descriptions-item>
    </el-descriptions>

    <!-- 文件列表 -->
    <div class="file-section">
      <h3 class="section-title">文件列表</h3>
      <el-table :data="files" style="width: 100%">
        <el-table-column label="文件名" prop="name" />
        <el-table-column label="大小" prop="size" width="120" />
        <el-table-column label="操作" width="200" align="center">
          <template #default="{ row }">
            <el-button link type="primary" @click="selectedFileId = String(row.id || row.name); loadPreview()">预览</el-button>
            <el-button link type="success" @click="handleDownloadFile(row)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 预览内容 -->
    <div class="preview-section">
      <h3 class="section-title">内容预览</h3>
      <pre class="preview-pre">{{ previewLines.join('\n') }}</pre>
      <div v-if="totalLines > 100" class="preview-footer">
        ... 共 {{ totalLines }} 条记录，已显示前 100 条 ...
      </div>
    </div>
  </PageCard>
</template>

<style scoped>
.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #606266;
  margin: 0 0 12px;
}

.file-section {
  margin-bottom: 24px;
}

.preview-pre {
  margin: 0;
  padding: 12px 16px;
  background: #f5f7fa;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  font-family: 'SFMono-Regular', Consolas, monospace;
  font-size: 12px;
  line-height: 1.6;
  max-height: 500px;
  overflow: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.preview-footer {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  text-align: center;
}
</style>
