<template>
  <div class="page-container">
    <h1>Ptskit 种子列表</h1>
    <div class="table-header">
      <el-input v-model="searchQuery" placeholder="搜索种子标题..." @keyup.enter="fetchData(1)" style="width: 300px;"></el-input>
      <el-button type="primary" :icon="'Refresh'" @click="fetchData(1)" :loading="loading">刷新</el-button>
    </div>
    <el-table :data="tableData" v-loading="loading" border>
      <el-table-column prop="title" label="标题" min-width="300"></el-table-column>
      <el-table-column prop="size" label="大小" width="120"></el-table-column>
      <el-table-column prop="seeders" label="做种" width="100"></el-table-column>
      <el-table-column prop="leechers" label="下载" width="100"></el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" :icon="'Download'" @click="handleDownload(row)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 20px; justify-content: flex-end;"
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import * as api from '../api';

const loading = ref(false);
const searchQuery = ref('');
const tableData = ref([]);
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
});

const fetchData = async (page = pagination.currentPage) => {
  loading.value = true;
  pagination.currentPage = page;
  try {
    const params = { 
      page: pagination.currentPage, 
      pageSize: pagination.pageSize,
      query: searchQuery.value
    };
    const res = await api.getPtskitTorrents(params);
    tableData.value = res.list;
    pagination.total = res.total;
  } finally {
    loading.value = false;
  }
};

const handleDownload = async (row) => {
  ElMessageBox.confirm(`确定要下载 "${row.title}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info',
  }).then(async () => {
    try {
      await api.addDownloadTask({ url: row.download_url });
      ElMessage.success('已发送下载指令！');
    } catch (error) {
      console.error("下载失败", error);
    }
  });
};

const handleSizeChange = (size) => {
  pagination.pageSize = size;
  fetchData(1);
};

const handleCurrentChange = (page) => {
  fetchData(page);
};

onMounted(() => fetchData());
</script>
