<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" :model="listQuery" class="demo-form-inline">
        <el-form-item label="状态">
          <el-radio-group v-model="status" size="small" @change="handleStatusChange">
            <el-radio-button label="total">全部 {{ statusInfo.total || 0 }}</el-radio-button>
            <el-radio-button label="success">成功 {{ statusInfo.success || 0 }}</el-radio-button>
            <el-radio-button label="error">失败 {{ statusInfo.error || 0 }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="项目">
          <el-input v-model="listQuery.project" placeholder="项目名称" clearable />
        </el-form-item>
        <el-form-item label="爬虫">
          <el-input v-model="listQuery.spider" placeholder="爬虫名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getList">查询</el-button>
          <el-button type="danger" @click="handleClearLogs">清空日志</el-button>
          <el-button type="default" @click="setupAutoRefresh">
            <el-icon v-if="isAutoRefreshing">
              <Loading />
            </el-icon>
            {{ isAutoRefreshing ? '停止自动刷新' : '自动刷新' }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label="ID" width="80">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="项目名" align="center">
        <template #default="scope">
          {{ scope.row.project }}
        </template>
      </el-table-column>
      <el-table-column label="Spider" align="center">
        <template #default="scope">
          {{ scope.row.spider }}
        </template>
      </el-table-column>
      <el-table-column label="调度模式" align="center">
        <template #default="scope">
          {{ scope.row.schedule_mode }}
        </template>
      </el-table-column>
      <el-table-column label="调度状态" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status ? 'success' : 'danger'">
            {{ scope.row.status ? '成功' : '失败' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="错误消息" align="center">
        <template #default="scope">
          {{ scope.row.message || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="运行状态" align="center">
        <template #default="scope">
          {{ scope.row.run_status || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="执行日志" align="center">

      </el-table-column>
      <el-table-column label="调度时间" align="center">
        <template #default="scope">
          {{ scope.row.create_time || '-' }}
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-config-provider :locale="zhCn">
        <el-pagination :current-page="listQuery.page" :page-sizes="[10, 20, 30, 50]" :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </el-config-provider>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute } from 'vue-router'
import { Loading } from '@element-plus/icons-vue'
import * as scheduleApi from '@/api/schedule'
// ElConfigProvider 组件
import { ElConfigProvider } from 'element-plus';
// 引入中文包
import zhCn from 'element-plus/es/locale/lang/zh-cn';

const route = useRoute()
const list = ref<{
  id: number,
  create_time: string,
  message: string,
  option: string,
  project: string,
  run_status: string,
  schedule_job_id: string,
  schedule_mode: string,
  scrapyd_server_id: number,
  spider: string,
  spider_job_id: string,
  status: boolean
}[]>([])
const total = ref(0)
const listLoading = ref(false)
const status = ref('total')
const isAutoRefreshing = ref(false)
let refreshInterval: any = null
const refreshFrequency = 5000 // 5秒刷新一次
const statusInfo = reactive({
  total: 0,
  success: 0,
  error: 0
})

const listQuery = reactive({
  page: 1,
  limit: 10,
  project: '',
  spider: '',
  job_id: '',
  scrapydServerId: localStorage.getItem('scrapyd_server_id') || ''
})

// 获取日志列表
const getList = async () => {
  listLoading.value = true
  try {
    const res = await scheduleApi.getScheduleLogs({
      status: status.value,
      ...listQuery,
    })
    list.value = res.data.list || []
    total.value = res.data.total || 0

    // 更新状态计数
    if (res.data) {
      statusInfo.total = res.data.total || 0
      statusInfo.success = res.data.success || 0
      statusInfo.error = res.data.error || 0
    }
  } catch (error) {
    console.error('获取调度日志失败:', error)
  } finally {
    listLoading.value = false
  }
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  listQuery.limit = val
  getList()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  listQuery.page = val
  getList()
}

// 处理状态变化
const handleStatusChange = () => {
  listQuery.page = 1
  getList()
}

// 设置或取消自动刷新
const setupAutoRefresh = () => {
  if (isAutoRefreshing.value) {
    clearInterval(refreshInterval)
    refreshInterval = null
    isAutoRefreshing.value = false
    ElMessage({
      type: 'info',
      message: '已停止自动刷新'
    })
  } else {
    refreshInterval = setInterval(() => {
      getList()
    }, refreshFrequency)
    isAutoRefreshing.value = true
    ElMessage({
      type: 'success',
      message: `已设置每${refreshFrequency / 1000}秒自动刷新`
    })
  }
}

// 清空日志
const handleClearLogs = () => {
  // 构建确认提示信息
  let confirmMsg = '确认清空'

  if (status.value !== 'total') {
    confirmMsg += `${status.value === 'success' ? '成功' : '失败'}`
  }

  confirmMsg += '调度日志'

  if (listQuery.project) {
    confirmMsg += `（项目：${listQuery.project}`
    if (listQuery.spider) {
      confirmMsg += `，爬虫：${listQuery.spider}`
    }
    confirmMsg += '）'
  } else if (listQuery.spider) {
    confirmMsg += `（爬虫：${listQuery.spider}）`
  }

  confirmMsg += '?'

  ElMessageBox.confirm(confirmMsg, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    customClass: 'custom-message-box',
  }).then(async () => {
    try {
      // 构造清空参数，可以按项目、爬虫过滤
      const clearParams = {
        status: status.value === 'total' ? '' : status.value,
        project: listQuery.project,
        spider: listQuery.spider,
        scrapydServerId: listQuery.scrapydServerId,
        job_id: listQuery.job_id
      }

      await scheduleApi.removeScheduleLogs(clearParams)
      ElMessage({
        type: 'success',
        message: '清空成功!'
      })
      getList()
    } catch (error) {
      console.error('清空日志失败:', error)
      ElMessage({
        type: 'error',
        message: '清空失败，请稍后重试'
      })
    }
  }).catch(() => {
    // 取消操作
  })
}

// 组件挂载时从路由参数获取初始过滤条件
onMounted(() => {
  // 从路由参数中获取项目和爬虫名称
  const queryProject = route.query.project as string
  const querySpider = route.query.spider as string
  const queryServerId = route.query.scrapydServerId as string
  const queryJob = route.query.job as string

  if (queryProject) listQuery.project = queryProject
  if (querySpider) listQuery.spider = querySpider
  if (queryServerId) listQuery.scrapydServerId = queryServerId
  if (queryJob) listQuery.job_id = queryJob

  getList()
})

// 组件卸载前清除定时器
onBeforeUnmount(() => {
  if (refreshInterval) {
    clearInterval(refreshInterval)
  }
})
</script>

<style lang="scss" scoped>
.filter-container {
  padding-bottom: 10px;
  text-align: left;
}

.pagination-container {
  padding: 10px 0;
}

.el-button:focus {
  outline: none;
}


</style>

<style>
.custom-message-box .el-button--primary {
  outline: none;
}

.custom-message-box .el-button--default {
  outline: none;
}

.custom-message-box .el-message-box__headerbtn {
  outline: none;
}
</style>