<template>
  <div class="app-container">
    <JobTool
      :status-info="statusInfo"
      @status-change="handleStatusChange"
      @project-change="handleProjectChange"
      @server-change="handleServerChange"
      @success="fetchJobList"
      @on-init="handleToolInit"
    />
    <JobTable
      :data="jobList"
      :loading="loading"
      :scrapyd-server-id="scrapydServerId"
      :project="project"
      @success="fetchJobList"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import * as projectApi from '@/api/project';
import JobTool from '@/views/job/components/JobTool.vue';
import JobTable from '@/views/job/components/JobTable.vue';

const route = useRoute();
const loading = ref(false);
const jobList = ref<any[]>([]);
const scrapydServerId = ref('');
const project = ref('');
const status = ref('');

// 状态统计信息
const statusInfo = reactive({
  total: 0,
  finished: 0,
  pending: 0,
  running: 0
});

// 获取任务列表
const fetchJobList = async () => {
  if (!scrapydServerId.value || !project.value) {
    return;
  }

  loading.value = true;
  try {
    const res = await projectApi.getJobList({
      project: project.value,
      status: status.value,
      scrapydServerId: scrapydServerId.value
    });

    if (res.code === 0) {
      jobList.value = res.data.list || [];
      
      // 更新状态统计
      statusInfo.total = res.data.total || 0;
      statusInfo.pending = res.data.pending || 0;
      statusInfo.running = res.data.running || 0;
      statusInfo.finished = res.data.finished || 0;
    } else {
      ElMessage.error(res.message || '获取任务列表失败');
    }
  } catch (error) {
    console.error('获取任务列表失败:', error);
    ElMessage.error('获取任务列表失败');
  } finally {
    loading.value = false;
  }
};

// 处理状态变化
const handleStatusChange = (val: string) => {
  status.value = val;
  fetchJobList();
};

// 处理项目变化
const handleProjectChange = (val: string) => {
  project.value = val;
  fetchJobList();
};

// 处理服务器变化
const handleServerChange = (val: string) => {
  scrapydServerId.value = val;
};

// 处理工具栏初始化
const handleToolInit = (data: any[]) => {
  // 如果有项目数据且当前未选择项目，则选择第一个
  if (data && data.length > 0 && !project.value) {
    project.value = data[0].project;
    fetchJobList();
  }
};

onMounted(() => {
  // 从路由参数中获取初始值
  if (route.query.scrapydServerId) {
    scrapydServerId.value = route.query.scrapydServerId as string;
  }
  
  if (route.query.project) {
    project.value = route.query.project as string;
  }
  
  if (route.query.status) {
    status.value = route.query.status as string;
  }
  
  // 如果有必要参数，则自动获取任务列表
  if (scrapydServerId.value && project.value) {
    fetchJobList();
  }
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}
</style>
