<template>
  <div class="page">
    <div class="page-header">
      <div class="header-left">
        <h2>{{ t('Scheduled Jobs') }}</h2>
        <p class="page-description">{{ t('Manage and monitor scheduled jobs') }}</p>
      </div>
      <div class="header-right">
        <div class="filters">
          <n-input
            v-model:value="searchQuery"
            :placeholder="t('Search jobs...')"
            clearable
            style="width: 200px"
          />
          <n-select
            v-model:value="frequencyFilter"
            :options="frequencyOptions"
            :placeholder="t('Frequency')"
            style="width: 120px"
          />
          <n-select
            v-model:value="statusFilter"
            :options="statusOptions"
            :placeholder="t('Status')"
            style="width: 120px"
          />
        </div>
        <div class="view-toggle">
          <button 
            class="toggle-btn" 
            :class="{ active: viewMode === 'list' }"
            @click="viewMode = 'list'"
            :title="t('List View')"
          >
            <i class="fa fa-list"></i>
          </button>
          <button 
            class="toggle-btn" 
            :class="{ active: viewMode === 'card' }"
            @click="viewMode = 'card'"
            :title="t('Card View')"
          >
            <i class="fa fa-th-large"></i>
          </button>
        </div>
        <button class="refresh-btn" @click="reload" :disabled="loading">
          <i :class="loading ? 'fa fa-spinner fa-spin' : 'fa fa-refresh'"></i>
        </button>
      </div>
    </div>

    <div class="page-content">
      <div v-if="loading" class="loading">
        <i class="fa fa-spinner fa-spin"></i> {{ t('Loading...') }}
      </div>
      <div v-else>
        <!-- 列表视图 -->
        <div class="job-list">
          <div class="list-header">
            <div class="col-name">{{ t('Method') }}</div>
            <div class="col-frequency">{{ t('Frequency') }}</div>
            <div class="col-cron">{{ t('Cron Format') }}</div>
            <div class="col-status">{{ t('Status') }}</div>
            <div class="col-last-execution">{{ t('Last Execution') }}</div>
            <div class="col-actions">{{ t('Actions') }}</div>
          </div>
          <div class="list-body">
            <div 
              v-for="job in jobs" 
              :key="job.name" 
              class="list-item"
              @click="openDetail(job.name)"
            >
              <div class="col-name">
                <div class="name">{{ job.method || job.name }}</div>
                <div class="description">{{ job.name }}</div>
              </div>
              <div class="col-frequency">
                <span class="badge">{{ t(job.frequency || '—') }}</span>
              </div>
              <div class="col-cron">
                <span v-if="job.cron_format" class="cron-text">{{ job.cron_format }}</span>
                <span v-else class="text-muted">—</span>
              </div>
              <div class="col-status">
                <n-checkbox v-model:checked="job.stopped" @update:checked="() => handleStatusChange(job)">
                  {{ job.stopped ? t('Stopped') : t('Running') }}
                </n-checkbox>
              </div>
              <div class="col-last-execution">
                <span v-if="job.last_execution" class="datetime-text">{{ formatDateTime(job.last_execution) }}</span>
                <span v-else class="text-muted">—</span>
              </div>
              <div class="col-actions">
                <button 
                  class="action-btn" 
                  @click.stop="toggleJobStatus(job.name)" 
                  :title="job.stopped ? t('Start') : t('Stop')"
                >
                  <i :class="job.stopped ? 'fa fa-play' : 'fa fa-pause'"></i>
                </button>
                <button class="action-btn" @click.stop="openDetail(job.name)" :title="t('View Details')">
                  <i class="fa fa-eye"></i>
                </button>
              </div>
            </div>
          </div>
          <!-- 分页 -->
          <div class="list-pagination">
            <n-pagination v-model:page="page" :page-count="pageCount" size="small" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { t } from '../../shared/i18n'
import { NInput, NSelect, NPagination, NCheckbox, useMessage } from 'naive-ui'
import { 
  getScheduledJobs, 
  toggleScheduledJobStatus, 
  getFrequencyOptions
} from '../../shared/api/scheduledJobs'

const router = useRouter()
const message = useMessage()

// 响应式数据
const loading = ref(false)
const jobs = ref<any[]>([])
const allJobs = ref<any[]>([]) // 保存所有原始数据
const total = ref(0)
const viewMode = ref<'card' | 'list'>('list')
const searchQuery = ref('')
const frequencyFilter = ref('all')
const statusFilter = ref('all')
const page = ref(1)
const pageSize = ref(parseInt(localStorage.getItem('itemsPerPage') || '10'))

// 选项数据
const frequencyOptions = ref<{ label: string; value: string }[]>([])
const statusOptions = computed(() => [
  { label: t('All'), value: 'all' },
  { label: t('Running'), value: 'running' },
  { label: t('Stopped'), value: 'stopped' }
])

const pageCount = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))

// 获取任务列表
async function fetchJobs() {
  loading.value = true
  try {
    // 构建过滤条件
    const filters = []
    if (searchQuery.value) {
      filters.push(['method', 'like', `%${searchQuery.value}%`])
    }
    if (frequencyFilter.value !== 'all') {
      filters.push(['frequency', '=', frequencyFilter.value])
    }
    if (statusFilter.value !== 'all') {
      const isStopped = statusFilter.value === 'stopped'
      filters.push(['stopped', '=', isStopped ? 1 : 0])
    }
    
    const result = await getScheduledJobs(page.value, pageSize.value, filters)
    
    allJobs.value = result.items || []
    processJobs()
    total.value = result.total || 0
  } catch (error) {
    console.error('获取任务列表失败:', error)
    message.error(t('Failed to load jobs'))
    jobs.value = []
    allJobs.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

async function processJobs() {
  let filteredJobs = [...allJobs.value]
  
  // 转换 stopped 字段为布尔类型
  filteredJobs = filteredJobs.map(job => ({
    ...job,
    stopped: Boolean(job.stopped)
  }))
  
  // 前端搜索和过滤（如果后端没有处理）
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filteredJobs = filteredJobs.filter(job => 
      job.method?.toLowerCase().includes(query) ||
      job.name?.toLowerCase().includes(query)
    )
  }
  
  if (frequencyFilter.value !== 'all') {
    filteredJobs = filteredJobs.filter(job => job.frequency === frequencyFilter.value)
  }
  
  if (statusFilter.value !== 'all') {
    const isStopped = statusFilter.value === 'stopped'
    filteredJobs = filteredJobs.filter(job => !!job.stopped === isStopped)
  }
  
  jobs.value = filteredJobs
}

function reload() {
  fetchJobs()
}

function openDetail(name: string) {
  router.push({ name: 'ScheduledJobDetail', params: { id: name } })
}

// 处理状态变化
async function handleStatusChange(job: any) {
  try {
    const result = await toggleScheduledJobStatus(job.name)
    
    if (result.success) {
      message.success(result.message || t('Job status updated successfully'))
      // 状态已经在 v-model 中自动更新了
    } else {
      message.error(result.message || t('Failed to update job status'))
      // 如果保存失败，恢复原状态
      job.stopped = !job.stopped
    }
  } catch (error) {
    console.error('Toggle job status error:', error)
    message.error(t('Failed to update job status'))
    // 如果保存失败，恢复原状态
    job.stopped = !job.stopped
  }
}

async function toggleJobStatus(jobName: string) {
  try {
    const result = await toggleScheduledJobStatus(jobName)
    
    if (result.success) {
      message.success(result.message || t('Job status updated successfully'))
      await fetchJobs()
    } else {
      message.error(result.message || t('Failed to update job status'))
    }
  } catch (error) {
    console.error('Toggle job status error:', error)
    message.error(t('Failed to update job status'))
  }
}

function formatDateTime(dateTimeStr: string) {
  if (!dateTimeStr) return '—'
  try {
    const date = new Date(dateTimeStr)
    return date.toLocaleString()
  } catch (error) {
    return dateTimeStr
  }
}

// 加载频率选项
async function loadFrequencyOptions() {
  try {
    const options = await getFrequencyOptions()
    frequencyOptions.value = [
      { label: t('All'), value: 'all' },
      ...options.map(option => ({
        label: t(option),
        value: option
      }))
    ]
  } catch (error) {
    console.error('Failed to load frequency options:', error)
  }
}

// 监听搜索和筛选变化
watch([searchQuery, frequencyFilter, statusFilter], () => {
  page.value = 1 // 重置到第一页
  fetchJobs()
}, { deep: true })

// 监听分页变化
watch([page], () => {
  fetchJobs()
})

// 监听每页数量变化（从系统设置）
watch(() => localStorage.getItem('itemsPerPage'), (newValue) => {
  if (newValue) {
    pageSize.value = parseInt(newValue)
    page.value = 1 // 重置到第一页
    fetchJobs()
  }
})

onMounted(() => {
  loadFrequencyOptions()
  fetchJobs()
})
</script>

<style scoped>
.page { 
  padding: 16px; 
  width: 100%;
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: flex-start; 
  justify-content: space-between;
  margin-bottom: 24px;
}

.header-left h2 {
  font-size: 28px;
  font-weight: 700;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.page-description {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.filters { 
  display: flex; 
  gap: 8px; 
  align-items: center; 
}

.view-toggle {
  display: flex;
  background: #f8fafc;
  border-radius: 8px;
  padding: 2px;
  border: 1px solid #e2e8f0;
}

.toggle-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: transparent;
  color: #64748b;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.toggle-btn:hover {
  background: #e2e8f0;
  color: #475569;
}

.toggle-btn.active {
  background: #2563eb;
  color: white;
}

.refresh-btn {
  width: 36px;
  height: 36px;
  border: none;
  border-radius: 8px;
  background: #f8fafc;
  color: #64748b;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.refresh-btn:hover {
  background: #e2e8f0;
  color: #475569;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.refresh-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.refresh-btn:disabled:hover {
  background: #f8fafc;
  color: #64748b;
  transform: none;
  box-shadow: none;
}

.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #6b7280;
  font-size: 16px;
}

.loading i {
  margin-right: 8px;
}

/* 列表视图 */
.job-list {
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  overflow: hidden;
}

.list-header {
  display: grid;
  grid-template-columns: 1fr 120px 150px 100px 180px 120px;
  gap: 16px;
  padding: 16px 20px;
  background: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

.list-body {
  max-height: 600px;
  overflow-y: auto;
}

.list-item {
  display: grid;
  grid-template-columns: 1fr 120px 150px 100px 180px 120px;
  gap: 16px;
  padding: 16px 20px;
  border-bottom: 1px solid #f3f4f6;
  cursor: pointer;
  transition: background-color 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.list-item:hover {
  background: #f9fafb;
}

.list-item:last-child {
  border-bottom: none;
}

.col-name {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.col-name .name {
  font-weight: 600;
  color: #111827;
  font-size: 14px;
  margin-bottom: 2px;
}

.col-name .description {
  color: #6b7280;
  font-size: 12px;
  line-height: 1.3;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.col-frequency {
  display: flex;
  align-items: center;
}

.col-cron {
  display: flex;
  align-items: center;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
}

.cron-text {
  color: #374151;
  background: #f3f4f6;
  padding: 2px 6px;
  border-radius: 4px;
}

.col-status {
  display: flex;
  align-items: center;
}

.col-last-execution {
  display: flex;
  align-items: center;
  color: #6b7280;
  font-size: 13px;
}

.datetime-text {
  color: #374151;
}

.text-muted {
  color: #9ca3af;
}

.col-actions {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.action-btn {
  width: 28px;
  height: 28px;
  border: none;
  background: #f3f4f6;
  color: #6b7280;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.action-btn:hover {
  background: #3b82f6;
  color: white;
}

.badge {
  background: #f3f4f6;
  color: #374151;
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.running {
  background: #d1fae5;
  color: #065f46;
}

.status-badge.stopped {
  background: #fee2e2;
  color: #dc2626;
}

.list-pagination {
  padding: 16px 20px;
  border-top: 1px solid #e5e7eb;
  background: #f9fafb;
  display: flex;
  justify-content: center;
}
</style>
