<script setup>
import { reactive, computed, ref } from 'vue'
import { formatTime } from '../utils/benchmarkUtils'
import GradientButton from '@/components/GradientButton.vue'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { Spinner } from '@/components/ui/spinner'

const props = defineProps({
  data: { type: Array, required: true },
  selectedRowKeys: { type: Array, required: true },
  loading: { type: Boolean, default: false },
  loadingMore: { type: Boolean, default: false },
  hasMore: { type: Boolean, default: false },
})

const emit = defineEmits(['update:selectedRowKeys', 'export', 'loadMore', 'createAsyncTask'])

// 列定义
const columns = [
  { key: 'cover', title: '封面', width: '100px' },
  { key: 'desc', title: '描述', width: '200px' },
  { key: 'digg_count', title: '点赞', width: '80px', sortable: true },
  { key: 'comment_count', title: '评论', width: '80px', sortable: true },
  { key: 'share_count', title: '分享', width: '80px', sortable: true },
  { key: 'collect_count', title: '收藏', width: '80px', sortable: true },
  { key: 'duration_s', title: '时长', width: '80px', sortable: true },
  { key: 'create_time', title: '创建时间', width: '140px', sortable: true },
]

// 排序状态
const sortKey = ref('digg_count')
const sortOrder = ref('desc')

// 全选状态
const isAllSelected = computed(() => {
  return props.data.length > 0 && props.selectedRowKeys.length === props.data.length
})

// 切换排序
function handleSort(key) {
  if (sortKey.value === key) {
    sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
  } else {
    sortKey.value = key
    sortOrder.value = 'desc'
  }
  emit('update:selectedRowKeys', [])
}

// 选择切换
function handleSelectAll() {
  if (isAllSelected.value) {
    emit('update:selectedRowKeys', [])
  } else {
    emit('update:selectedRowKeys', props.data.map(item => String(item.id)))
  }
}

function handleSelect(id) {
  const key = String(id)
  const newKeys = [...props.selectedRowKeys]
  const index = newKeys.indexOf(key)
  if (index > -1) {
    newKeys.splice(index, 1)
  } else {
    newKeys.push(key)
  }
  emit('update:selectedRowKeys', newKeys)
}

// 排序后的数据
const sortedData = computed(() => {
  const data = [...props.data]
  const key = sortKey.value

  if (!key) return data

  return data.sort((a, b) => {
    const aVal = a[key] || 0
    const bVal = b[key] || 0
    return sortOrder.value === 'asc' ? aVal - bVal : bVal - aVal
  })
})

// 格式化数字
function formatNumber(value) {
  return value ? value.toLocaleString('zh-CN') : '0'
}
</script>

<template>
  <section class="card results-card" v-if="data.length > 0">
    <div class="section-header">
      <div class="section-title">分析结果</div>
      <div class="button-group">
        <GradientButton
          :text="`导出Excel (${selectedRowKeys.length}/20)`"
          size="small"
          @click="$emit('export')"
          :disabled="data.length === 0 || selectedRowKeys.length === 0 || selectedRowKeys.length > 20"
          icon="download"
        />
        <GradientButton
          :text="`批量分析 (${selectedRowKeys.length}/20)`"
          size="small"
          @click="$emit('createAsyncTask')"
          :disabled="data.length === 0 || selectedRowKeys.length === 0 || selectedRowKeys.length > 20"
          icon="clock-circle"
        />
      </div>
    </div>

    <!-- 表格 -->
    <div class="table-wrapper">
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead class="w-[40px]">
              <Checkbox
                :checked="isAllSelected"
                @update:checked="handleSelectAll"
                class="checkbox-small"
              />
            </TableHead>
            <TableHead
              v-for="col in columns"
              :key="col.key"
              :class="[col.width && `w-[${col.width}]`, col.sortable && 'cursor-pointer']"
              @click="col.sortable && handleSort(col.key)"
            >
              <div class="flex items-center gap-1">
                {{ col.title }}
                <span v-if="col.sortable" class="sort-icon">
                  <svg v-if="sortKey !== col.key" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M7 15l5 5 5-5M7 9l5-5 5 5"/>
                  </svg>
                  <svg v-else-if="sortOrder === 'asc'" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M12 19V5M5 12l7-7 7 7"/>
                  </svg>
                  <svg v-else width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M12 5v14M5 12l7 7 7-7"/>
                  </svg>
                </span>
              </div>
            </TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          <TableRow v-if="loading">
            <TableCell :col-span="columns.length + 1" class="h-32 text-center">
              <Spinner class="mx-auto" />
            </TableCell>
          </TableRow>
          <TableRow
            v-else
            v-for="record in sortedData"
            :key="record.id"
            class="table-row"
          >
            <TableCell class="w-[40px]">
              <Checkbox
                :checked="selectedRowKeys.includes(String(record.id))"
                @update:checked="handleSelect(record.id)"
                class="checkbox-small"
              />
            </TableCell>
            <TableCell>
              <div class="cover-wrapper">
                <a v-if="record.cover && record.share_url" :href="record.share_url" target="_blank" class="cover-link">
                  <img :src="record.cover" alt="cover" loading="lazy" class="cover-img" />
                  <span v-if="record.is_top" class="top-tag">置顶</span>
                </a>
                <template v-else-if="record.cover">
                  <img :src="record.cover" alt="cover" loading="lazy" class="cover-img" />
                  <span v-if="record.is_top" class="top-tag">置顶</span>
                </template>
                <span v-else class="no-cover">无封面</span>
              </div>
            </TableCell>
            <TableCell>
              <span :title="record.desc" class="truncate-text">{{ record.desc || '-' }}</span>
            </TableCell>
            <TableCell>{{ formatNumber(record.digg_count) }}</TableCell>
            <TableCell>{{ formatNumber(record.comment_count) }}</TableCell>
            <TableCell>{{ formatNumber(record.share_count) }}</TableCell>
            <TableCell>{{ formatNumber(record.collect_count) }}</TableCell>
            <TableCell>{{ record.duration_s ? `${record.duration_s}s` : '-' }}</TableCell>
            <TableCell>{{ formatTime(record.create_time) }}</TableCell>
          </TableRow>
        </TableBody>
      </Table>
    </div>

    <!-- 加载更多 -->
    <div v-if="hasMore" class="load-more-footer">
      <Button
        :disabled="loadingMore"
        size="lg"
        variant="outline"
        @click="$emit('loadMore')"
        class="load-more-btn"
      >
        <Spinner v-if="loadingMore" class="mr-2 h-4 w-4" />
        {{ loadingMore ? '加载中...' : '加载更多内容' }}
      </Button>
      <div class="load-more-hint">已加载 {{ data.length }} 条</div>
    </div>
    <div v-else-if="data.length > 0" class="no-more-hint">
      已加载全部内容
    </div>
  </section>
</template>

<style scoped>
.card {
  background: var(--color-bg-card);
  border-radius: var(--radius-md);
  padding: var(--space-4);
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--color-gray-200);
  overflow: hidden;
}

.results-card {
  min-height: 420px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--space-3);
}

.button-group {
  display: flex;
  align-items: center;
  gap: var(--space-3);
}

.section-title {
  font-size: var(--font-size-xs);
  color: var(--color-gray-600);
  margin-bottom: var(--space-3);
}

.table-wrapper {
  overflow-x: auto;
  max-height: calc(100vh - 400px);
  overflow-y: auto;
}

.table-wrapper::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.table-wrapper::-webkit-scrollbar-track {
  background: transparent;
}

.table-wrapper::-webkit-scrollbar-thumb {
  background: var(--color-gray-300);
  border-radius: 3px;
}

.table-row:hover {
  background: var(--color-gray-50);
}

.checkbox-small {
  transform: scale(0.85);
}

.cover-wrapper {
  position: relative;
  display: inline-block;
}

.cover-link {
  display: block;
  cursor: pointer;
}

.cover-link:hover .cover-img {
  transform: scale(1.02);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.top-tag {
  position: absolute;
  top: var(--space-1);
  left: var(--space-1);
  padding: 1px 6px;
  font-size: 10px;
  color: #fff;
  background: var(--color-error-500);
  border-radius: 2px;
}

.cover-img {
  width: 80px;
  height: 45px;
  object-fit: cover;
  border-radius: var(--radius-sm);
  border: 1px solid var(--color-gray-200);
  transition: transform 0.2s, box-shadow 0.2s;
}

.no-cover {
  color: var(--color-gray-500);
  font-size: var(--font-size-xs);
}

.truncate-text {
  display: block;
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.sort-icon {
  opacity: 0.4;
  transition: opacity var(--duration-fast);
}

.table-row:hover .sort-icon,
[onclick]:hover .sort-icon {
  opacity: 1;
}

.load-more-footer,
.no-more-hint {
  text-align: center;
  border-top: 1px solid var(--color-gray-200);
}

.load-more-footer {
  padding: var(--space-4);
}

.load-more-btn {
  max-width: 200px;
  height: 40px;
  font-size: var(--font-size-base);
  border-radius: var(--radius-md);
}

.load-more-hint,
.no-more-hint {
  font-size: var(--font-size-xs);
  color: var(--color-gray-600);
}

.load-more-hint {
  margin-top: var(--space-2);
}

.no-more-hint {
  padding: var(--space-3);
}
</style>
