<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import DataTablePage from '@/components/DataTablePage.vue'
import { getDatasetList, deleteDataset, downloadDatasetUrl } from '@/api/modules/dataset'
import { DATASET_TYPE_MAP, STORAGE_MAP } from '@/constants'
import { formatMegabytes } from '@/utils/fileSize'
import type { DatasetItem, DatasetSource } from '@/types'

const router = useRouter()
const route = useRoute()

const loading = ref(false)
const dataList = ref<DatasetItem[]>([])
const activeTab = ref<DatasetSource>(route.query.tab === 'task' ? 'task' : 'upload')
const batchMode = ref(false)
const selectedCount = ref(0)
const batchDeleting = ref(false)
const deletingId = ref<string | number | null>(null)
const tablePageRef = ref<{
  handleBatchDelete: () => Promise<boolean>
  clearSelection: () => void
} | null>(null)

const filteredDataList = computed(() => {
  if (activeTab.value === 'task') {
    return dataList.value.filter((item) => item.source === 'task')
  }

  return dataList.value.filter((item) => item.source !== 'task')
})

async function loadData() {
  loading.value = true
  try {
    dataList.value = (await getDatasetList()) || []
  } catch {
    // ignore
  } finally {
    loading.value = false
  }
}

async function deleteDatasetItem(row: DatasetItem) {
  await deleteDataset(row.id)
}

async function handleDelete(row: DatasetItem) {
  try {
    await ElMessageBox.confirm(
      `确定删除数据集“${row.name}”吗？删除后无法恢复。`,
      '确认删除',
      {
        type: 'warning',
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        confirmButtonClass: 'el-button--danger',
      },
    )
  } catch {
    return
  }

  deletingId.value = row.id
  try {
    await deleteDatasetItem(row)
    await loadData()
    ElMessage.success('数据集已删除')
  } catch {
    // 统一请求层已展示后端返回的失败原因。
  } finally {
    deletingId.value = null
  }
}

function enterBatchMode() {
  batchMode.value = true
  selectedCount.value = 0
}

function exitBatchMode() {
  batchMode.value = false
  selectedCount.value = 0
  tablePageRef.value?.clearSelection()
}

function handleSelectionChange(rows: DatasetItem[]) {
  selectedCount.value = rows.length
}

async function handleBatchDelete() {
  if (!selectedCount.value || batchDeleting.value) return
  batchDeleting.value = true
  try {
    const completed = await tablePageRef.value?.handleBatchDelete()
    if (completed) exitBatchMode()
  } finally {
    batchDeleting.value = false
  }
}

function handlePreview(row: any) {
  router.push(`/dataset/${row.id}/preview`)
}

function handleDownload(row: any) {
  window.open(downloadDatasetUrl(row.id), '_blank')
}

function formatSizeMb(row: DatasetItem) {
  return formatMegabytes(row.size_bytes, row.size)
}

function currentVersionNumbers(row: DatasetItem) {
  const values = row.current_version_nos?.length
    ? row.current_version_nos
    : [
        row.current_version_no,
        ...(row.files || []).map((file) => file.current_version_no),
      ]
  return [...new Set(
    values
      .map((value) => Number(value))
      .filter((value) => Number.isInteger(value) && value > 0),
  )].sort((a, b) => a - b)
}

function versionLabel(row: DatasetItem) {
  const versions = currentVersionNumbers(row)
  return versions.length ? versions.map((value) => `V${value}`).join(' / ') : '-'
}

function versionDescription(row: DatasetItem) {
  const fileCount = row.files?.length || 0
  const historyCount = Number(row.version_count || 0)
  if (!fileCount) return '当前数据集没有文件版本'
  return `${fileCount} 个文件，共 ${historyCount || fileCount} 个版本记录`
}

watch(activeTab, exitBatchMode)
onMounted(loadData)
</script>

<template>
  <DataTablePage
    ref="tablePageRef"
    title="数据集管理"
    :data="filteredDataList"
    :loading="loading"
    searchable
    :search-fields="activeTab === 'task' ? ['task_id', 'task_name'] : ['name']"
    :multi-select="activeTab === 'task' && batchMode"
    :show-batch-bar="false"
    :create-text="activeTab === 'upload' ? '上传数据集' : ''"
    create-to="/dataset/create"
    :delete-fn="deleteDatasetItem"
    row-key="id"
    @refresh="loadData"
    @selection-change="handleSelectionChange"
  >
    <template #title>
      <div class="capsule-tabs">
        <button 
          class="capsule-tab-item" 
          :class="{ active: activeTab === 'upload' }" 
          @click="activeTab = 'upload'"
        >
          上传任务
        </button>
        <button 
          class="capsule-tab-item" 
          :class="{ active: activeTab === 'task' }" 
          @click="activeTab = 'task'"
        >
          数据任务
        </button>
      </div>
    </template>

    <template #toolbar-extra>
      <template v-if="activeTab === 'task'">
        <el-button v-if="!batchMode" type="danger" plain @click="enterBatchMode">
          <i class="fa fa-trash-o" style="margin-right: 4px" />批量删除
        </el-button>
        <template v-else>
          <el-button :disabled="batchDeleting" @click="exitBatchMode">取消</el-button>
          <el-button
            v-if="selectedCount > 0"
            type="danger"
            :loading="batchDeleting"
            @click="handleBatchDelete"
          >
            <i class="fa fa-trash-o" style="margin-right: 4px" />删除（{{ selectedCount }}）
          </el-button>
        </template>
      </template>
    </template>

    <template #columns>
      <el-table-column v-if="activeTab === 'task'" label="任务ID" prop="task_id" align="center" width="100" />
      <el-table-column
        :label="activeTab === 'task' ? '训练任务名称' : '数据集名称'"
        align="center"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          {{ activeTab === 'task' ? (row.task_name || '-') : row.name }}
        </template>
      </el-table-column>
      <el-table-column label="数据类型" align="center" width="110">
        <template #default="{ row }">
          <el-tag type="primary" size="small">{{ DATASET_TYPE_MAP[String(row.type).toLowerCase()] || row.type || '-' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="存储位置" align="center" width="110">
        <template #default="{ row }">
          <el-tag type="success" size="small">
            {{ STORAGE_MAP[row.storage_type] || row.storage_type || '-' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="大小" align="center" width="120">
        <template #default="{ row }">
          <span class="numeric-cell">{{ formatSizeMb(row as DatasetItem) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="数据条数" align="center" width="100">
        <template #default="{ row }">{{ row.count || 0 }}</template>
      </el-table-column>
      <el-table-column label="版本" align="center" width="120">
        <template #default="{ row }">
          <el-tooltip
            :content="versionDescription(row as DatasetItem)"
            placement="top"
            :show-after="350"
          >
            <el-tag size="small" type="info" effect="plain">
              {{ versionLabel(row as DatasetItem) }}
            </el-tag>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" width="180">
        <template #default="{ row }">
          {{ row.create_time ? new Date(row.create_time).toLocaleString('zh-CN') : '-' }}
        </template>
      </el-table-column>
    </template>

    <template #actions="{ row }">
      <div class="action-buttons">
        <el-button type="primary" link size="small" @click="handlePreview(row)">
          <i class="fa fa-eye" style="margin-right: 4px" />详情
        </el-button>
        <el-button type="success" link size="small" @click="handleDownload(row)">
          <i class="fa fa-download" style="margin-right: 4px" />下载
        </el-button>
        <el-button
          type="danger"
          link
          size="small"
          :loading="deletingId === row.id"
          :disabled="batchDeleting || batchMode"
          @click="handleDelete(row as DatasetItem)"
        >
          <i class="fa fa-trash-o" style="margin-right: 4px" />删除
        </el-button>
      </div>
    </template>
  </DataTablePage>
</template>

<style scoped lang="scss">
/* 胶囊切换栏样式 */
.capsule-tabs {
  display: flex;
  background: #f1f5f9;
  padding: 3px;
  border-radius: 8px;
  gap: 2px;
  border: 1px solid #e2e8f0;
}

.capsule-tab-item {
  border: 0;
  background: transparent;
  padding: 6px 20px;
  font-size: 13px;
  font-weight: 500;
  color: #64748b;
  cursor: pointer;
  border-radius: 6px;
  transition: all 0.2s ease;
  outline: none;

  &:hover {
    color: #1e293b;
  }

  &.active {
    background: #fff;
    color: #4f46e5;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06), 0 1px 2px rgba(0, 0, 0, 0.04);
    font-weight: 600;
  }
}

.numeric-cell {
  font-variant-numeric: tabular-nums;
  white-space: nowrap;
}

</style>
