<template>
  <div class="cleanup-test-page">
    <div class="page-header">
      <h1>任务清理功能测试</h1>
      <p>测试任务清理系统的各项功能</p>
    </div>

    <div class="test-sections">
      <!-- 统计信息测试 -->
      <el-card class="test-section">
        <template #header>
          <div class="section-header">
            <h3>统计信息测试</h3>
            <el-button type="primary" @click="testGetStats" :loading="loadingStats">
              获取统计信息
            </el-button>
          </div>
        </template>
        <div class="test-content">
          <div v-if="statsResult" class="result-display">
            <h4>统计结果:</h4>
            <pre>{{ JSON.stringify(statsResult, null, 2) }}</pre>
          </div>
          <div v-if="statsError" class="error-display">
            <h4>错误信息:</h4>
            <p>{{ statsError }}</p>
          </div>
        </div>
      </el-card>

      <!-- 完整清理测试 -->
      <el-card class="test-section">
        <template #header>
          <div class="section-header">
            <h3>完整清理测试</h3>
            <el-button type="danger" @click="testFullCleanup" :loading="loadingCleanup">
              执行完整清理
            </el-button>
          </div>
        </template>
        <div class="test-content">
          <div class="warning-box">
            <el-alert
              title="警告"
              type="warning"
              :closable="false"
              show-icon
            >
              <template #default>
                <p>此操作将清理所有已完成和失败的任务，请谨慎操作！</p>
              </template>
            </el-alert>
          </div>
          <div v-if="cleanupResult" class="result-display">
            <h4>清理结果:</h4>
            <pre>{{ JSON.stringify(cleanupResult, null, 2) }}</pre>
          </div>
          <div v-if="cleanupError" class="error-display">
            <h4>错误信息:</h4>
            <p>{{ cleanupError }}</p>
          </div>
        </div>
      </el-card>

      <!-- 用户清理测试 -->
      <el-card class="test-section">
        <template #header>
          <div class="section-header">
            <h3>用户清理测试</h3>
          </div>
        </template>
        <div class="test-content">
          <el-form :model="userCleanupForm" :rules="userCleanupRules" ref="userCleanupFormRef">
            <el-form-item label="用户名" prop="username">
              <el-input 
                v-model="userCleanupForm.username" 
                placeholder="请输入要清理的用户名"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-button 
                type="warning" 
                @click="testUserCleanup" 
                :loading="loadingUserCleanup"
              >
                清理用户任务
              </el-button>
            </el-form-item>
          </el-form>
          <div v-if="userCleanupResult" class="result-display">
            <h4>用户清理结果:</h4>
            <pre>{{ JSON.stringify(userCleanupResult, null, 2) }}</pre>
          </div>
          <div v-if="userCleanupError" class="error-display">
            <h4>错误信息:</h4>
            <p>{{ userCleanupError }}</p>
          </div>
        </div>
      </el-card>

      <!-- 队列状态测试 -->
      <el-card class="test-section">
        <template #header>
          <div class="section-header">
            <h3>队列状态测试</h3>
            <el-button type="info" @click="testQueueStatus" :loading="loadingQueue">
              获取队列状态
            </el-button>
          </div>
        </template>
        <div class="test-content">
          <div v-if="queueResult" class="result-display">
            <h4>队列状态:</h4>
            <pre>{{ JSON.stringify(queueResult, null, 2) }}</pre>
          </div>
          <div v-if="queueError" class="error-display">
            <h4>错误信息:</h4>
            <p>{{ queueError }}</p>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

// 响应式数据
const loadingStats = ref(false)
const loadingCleanup = ref(false)
const loadingUserCleanup = ref(false)
const loadingQueue = ref(false)

const statsResult = ref(null)
const statsError = ref(null)
const cleanupResult = ref(null)
const cleanupError = ref(null)
const userCleanupResult = ref(null)
const userCleanupError = ref(null)
const queueResult = ref(null)
const queueError = ref(null)

const userCleanupFormRef = ref(null)
const userCleanupForm = reactive({
  username: ''
})

const userCleanupRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 50, message: '用户名长度在2到50个字符', trigger: 'blur' }
  ]
})

// 测试方法
const getAuthHeaders = () => {
  const token = sessionStorage.getItem('token')
  return token ? { 'Authorization': `Bearer ${token}` } : {}
}

const testGetStats = async () => {
  loadingStats.value = true
  statsResult.value = null
  statsError.value = null
  
  try {
    const response = await fetch('/api/cleanup/cleanup-stats', {
      headers: {
        'Content-Type': 'application/json',
        ...getAuthHeaders()
      }
    })
    if (response.ok) {
      statsResult.value = await response.json()
      ElMessage.success('获取统计信息成功')
    } else {
      statsError.value = `HTTP ${response.status}: ${response.statusText}`
    }
  } catch (error) {
    statsError.value = error.message
    ElMessage.error('获取统计信息失败')
  } finally {
    loadingStats.value = false
  }
}

const testFullCleanup = async () => {
  loadingCleanup.value = true
  cleanupResult.value = null
  cleanupError.value = null
  
  try {
    const response = await fetch('/api/cleanup/full-cleanup', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...getAuthHeaders()
      }
    })
    
    if (response.ok) {
      cleanupResult.value = await response.json()
      ElMessage.success('完整清理执行成功')
    } else {
      cleanupError.value = `HTTP ${response.status}: ${response.statusText}`
    }
  } catch (error) {
    cleanupError.value = error.message
    ElMessage.error('执行完整清理失败')
  } finally {
    loadingCleanup.value = false
  }
}

const testUserCleanup = async () => {
  const valid = await userCleanupFormRef.value.validate()
  if (!valid) return
  
  loadingUserCleanup.value = true
  userCleanupResult.value = null
  userCleanupError.value = null
  
  try {
    const response = await fetch(`/api/cleanup/user-tasks/${userCleanupForm.username}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...getAuthHeaders()
      }
    })
    
    if (response.ok) {
      userCleanupResult.value = await response.json()
      ElMessage.success(`用户 ${userCleanupForm.username} 的任务清理完成`)
    } else {
      userCleanupError.value = `HTTP ${response.status}: ${response.statusText}`
    }
  } catch (error) {
    userCleanupError.value = error.message
    ElMessage.error('清理用户任务失败')
  } finally {
    loadingUserCleanup.value = false
  }
}

const testQueueStatus = async () => {
  loadingQueue.value = true
  queueResult.value = null
  queueError.value = null
  
  try {
    const response = await fetch('/api/diagnostic/queue-status')
    if (response.ok) {
      queueResult.value = await response.json()
      ElMessage.success('获取队列状态成功')
    } else {
      queueError.value = `HTTP ${response.status}: ${response.statusText}`
    }
  } catch (error) {
    queueError.value = error.message
    ElMessage.error('获取队列状态失败')
  } finally {
    loadingQueue.value = false
  }
}
</script>

<style scoped>
.cleanup-test-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  color: #1e293b;
  margin-bottom: 10px;
}

.page-header p {
  color: #64748b;
  font-size: 16px;
}

.test-sections {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.test-section {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-header h3 {
  margin: 0;
  color: #1e293b;
}

.test-content {
  padding: 20px 0;
}

.warning-box {
  margin-bottom: 20px;
}

.result-display,
.error-display {
  margin-top: 20px;
  padding: 16px;
  border-radius: 8px;
}

.result-display {
  background: #f0f9ff;
  border: 1px solid #0ea5e9;
}

.error-display {
  background: #fef2f2;
  border: 1px solid #ef4444;
}

.result-display h4,
.error-display h4 {
  margin: 0 0 12px 0;
  color: #1e293b;
}

.result-display pre {
  margin: 0;
  font-size: 12px;
  color: #1e293b;
  white-space: pre-wrap;
  word-break: break-all;
}

.error-display p {
  margin: 0;
  color: #dc2626;
  font-weight: 500;
}

@media (max-width: 768px) {
  .cleanup-test-page {
    padding: 10px;
  }
  
  .section-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
}
</style>
