<template>
  <div class="app-container">
    <schedule-tool @success="getData" />
    <div style="height: 20px"></div>
    <schedule-table
      :data="list"
      @success="getData"
      @sort-change="handleSortChange"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { ScheduleTypeOptions, ScheduleTypeEnum } from '@/enums/schedule-type-enum'
import * as scheduleApi from '@/api/schedule'

const list = ref([])
// 排序
const orderProp = ref('')
const orderType = ref('')

const getData = async () => {
  const options = await getScrapydServerPage()
  
  try {
    const res = await scheduleApi.getJobs({scrapydServerId: localStorage.getItem('scrapydServerId')!})
    
    if (res.code === 0) {
      list.value = res.data.map((item: any) => {
        // 服务名
        let scrapyd_server = options.find(
          (x: any) => x.value == item.scrapyd_server_id
        )

        item.scrapyd_server_label = scrapyd_server ? scrapyd_server.label : ''

        // 调度方式
        if (item.kwargs.schedule_type == ScheduleTypeEnum.ONLY_ONE_SERVER) {
          item.schedule_type_label = item.scrapyd_server_label
        } else {
          let ScheduleTypeItem = ScheduleTypeOptions.find(
            (x) => item.kwargs.schedule_type == x.value
          )
          item.schedule_type_label = ScheduleTypeItem
            ? ScheduleTypeItem.label
            : ''
        }

        return item
      })
    }
  } catch (error) {
    console.error('获取调度任务列表失败:', error)
  }
}

const handleSortChange = ({ column, prop, order }: any) => {
  orderType.value = order

  // 如果有排序方式再给排序字段
  if (orderType.value) {
    orderProp.value = prop
  } else {
    orderProp.value = ''
  }
}

const getScrapydServerPage = async () => {
  try {
    const res = await scheduleApi.getScrapydServerPage()

    return res.data?.list.map((item: any) => {
      return {
        label: item.server_name,
        value: item.id + '',
      }
    }) || []
  } catch (error) {
    console.error('获取Scrapyd服务列表失败:', error)
    return []
  }
}

onMounted(() => {
  getData()
})
</script>

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