<template>
  <div class="app-container">
    <SelectScrapydServer
      v-model:value="scrapydServerId"
      @on-init="handleSelectScrapydServerInit"
      @change="handleScrapydServerChange"
    ></SelectScrapydServer>

    <LogTable
      class="mt-md"
      type="logs"
      :scrapydServerId="scrapydServerId"
      v-loading="listLoading"
      :data="list"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import LogTable from './LogTable.vue';
import SelectScrapydServer from '@/components/SelectScrapydServer.vue';
import { getLogs } from '@/api/log';

const route = useRoute();
const scrapydServerId = ref('');
const list = ref<any[]>([]);
const listLoading = ref(true);

async function getData() {
  listLoading.value = true;

  try {
    const res = await getLogs({
      scrapydServerId: scrapydServerId.value,
    });

    if (res) {
      list.value = res.data;
    }
  } catch (error) {
    console.error('获取日志列表失败:', error);
  } finally {
    listLoading.value = false;
  }
}

const handleScrapydServerChange = () => {
  getData();
};

const handleSelectScrapydServerInit = (data: any) => {
  if (!scrapydServerId.value) {
    if (data && data.length > 0) {
      scrapydServerId.value = data[0].value;
    }
  }

  getData();
};

onMounted(() => {
  const queryScrapydServerId = route.query.scrapydServerId;
  if (queryScrapydServerId) {
    scrapydServerId.value = queryScrapydServerId as string;
  }
});
</script>

<style lang="scss" scoped></style>
