<template>
  <div class="page">
    <div class="page-header">
      <div class="header-left">
        <h2>{{ t('Scheduled Jobs') }}</h2>
      </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>
        <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" :style="{ gridTemplateColumns: getGridTemplateColumns() }">
            <div 
              v-for="field in listViewFields" 
              :key="field.fieldname"
              class="col-header"
              :class="`col-${field.fieldname}`"
            >
              {{ t(field.label || field.fieldname) }}
            </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"
              :style="{ gridTemplateColumns: getGridTemplateColumns() }"
              @click="openDetail(job.name)"
            >
              <template v-for="field in listViewFields" :key="field.fieldname">
                <div class="col-field" :class="`col-${field.fieldname}`">
                  <template v-if="field.fieldtype === 'Check'">
                    <n-checkbox 
                      v-model:checked="job[field.fieldname]" 
                      @update:checked="field.fieldname === 'stopped' ? () => handleStatusChange(job) : undefined"
                      @click.stop
                    />
                    <span 
                      :class="['status-badge', job[field.fieldname] ? 'stopped' : 'running']"
                      v-if="field.fieldname === 'stopped'"
                    >
                      {{ job[field.fieldname] ? t('Stopped') : t('Running') }}
                    </span>
                  </template>
                  <template v-else>
                    <div v-if="field.fieldname === 'method' || field.fieldname === 'name'" class="col-name-wrapper">
                      <div class="name">{{ renderFieldValue(field, job).value }}</div>
                      <div v-if="field.fieldname === 'method' && job.name !== job.method" class="description">{{ job.name }}</div>
                    </div>
                    <span 
                      v-else-if="field.fieldtype === 'Select' && field.fieldname === 'frequency'"
                      class="badge"
                    >
                      {{ t(renderFieldValue(field, job).value) }}
                    </span>
                    <span 
                      v-else-if="field.fieldname === 'cron_format' && job.cron_format"
                      class="cron-text"
                    >
                      {{ renderFieldValue(field, job).value }}
                    </span>
                    <span 
                      v-else-if="field.fieldtype === 'Datetime' || field.fieldtype === 'Date'"
                      :class="job[field.fieldname] ? 'datetime-text' : 'text-muted'"
                    >
                      {{ renderFieldValue(field, job).value }}
                    </span>
                    <span v-else :class="job[field.fieldname] ? '' : 'text-muted'">
                      {{ renderFieldValue(field, job).value }}
                    </span>
                  </template>
                </div>
              </template>
              <div class="col-actions">
                <button 
                  :class="['action-btn', job.stopped ? 'start-btn' : 'stop-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 axios from 'axios'
import { getPageTypeMeta } from '@/shared/api/common'
import { formatDateTimeInTimezone } from '@/shared/utils/timezone'
import { 
  getScheduledJobs, 
  toggleScheduledJobStatus
} 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 searchQuery = ref('')
const frequencyFilter = ref('all')
const statusFilter = ref('all')
const page = ref(1)
const pageSize = ref(parseInt(localStorage.getItem('itemsPerPage') || '10'))

// 字段元数据
const metaFields = ref<any[]>([])
const listViewFields = ref<any[]>([]) // 列表中显示的字段

// 选项数据
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 {
    return formatDateTimeInTimezone(dateTimeStr)
  } catch (error) {
    return dateTimeStr
  }
}

// 生成动态网格列模板
function getGridTemplateColumns(): string {
  if (listViewFields.value.length === 0) {
    return '1fr 120px 150px 100px 180px 120px'
  }
  
  // 为每个字段生成列宽
  const columns = listViewFields.value.map((field: any) => {
    // 根据字段类型和名称设置合适的列宽
    if (field.fieldname === 'method' || field.fieldname === 'name') {
      return '1fr' // 主字段自适应宽度
    } else if (field.fieldname === 'frequency') {
      return '120px'
    } else if (field.fieldname === 'cron_format') {
      return '150px'
    } else if (field.fieldname === 'stopped') {
      return '120px'
    } else if (field.fieldtype === 'Datetime' || field.fieldtype === 'Date') {
      return '180px'
    } else if (field.fieldtype === 'Check') {
      return '100px'
    } else {
      return '120px' // 默认宽度
    }
  })
  
  // 添加操作列
  columns.push('120px')
  
  return columns.join(' ')
}

// 加载字段元数据
async function loadMetaFields() {
  try {
    const result = await getPageTypeMeta('Local Scheduled Job')
    const data = result.success && result.data ? result.data : {}
    metaFields.value = data.fields || []
    
    // 筛选出需要在列表视图中显示的字段
    listViewFields.value = metaFields.value.filter((field: any) => {
      // 显示 in_list_view 为 1 的字段，或者特定的字段
      return field.in_list_view === 1 || ['method', 'frequency', 'cron_format', 'stopped', 'last_execution'].includes(field.fieldname)
    })
    
    // 按 field_order 排序
    const fieldOrder = data.field_order || []
    listViewFields.value.sort((a: any, b: any) => {
      const indexA = fieldOrder.indexOf(a.fieldname)
      const indexB = fieldOrder.indexOf(b.fieldname)
      if (indexA === -1 && indexB === -1) return 0
      if (indexA === -1) return 1
      if (indexB === -1) return -1
      return indexA - indexB
    })
    
    // 从字段元数据中提取 frequency 字段的选项
    const frequencyField = metaFields.value.find((f: any) => f.fieldname === 'frequency')
    if (frequencyField && frequencyField.options) {
      const options = typeof frequencyField.options === 'string' 
        ? frequencyField.options.split('\n').filter((opt: string) => opt.trim())
        : []
      frequencyOptions.value = [
        { label: t('All'), value: 'all' },
        ...options.map((option: string) => ({
          label: t(option.trim()),
          value: option.trim()
        }))
      ]
    }
  } catch (error) {
    console.error('Failed to load meta fields:', error)
    // 如果加载失败，使用默认字段
    listViewFields.value = [
      { fieldname: 'method', label: 'Method', fieldtype: 'Data' },
      { fieldname: 'frequency', label: 'Frequency', fieldtype: 'Select' },
      { fieldname: 'cron_format', label: 'Cron Format', fieldtype: 'Data' },
      { fieldname: 'stopped', label: 'Status', fieldtype: 'Check' },
      { fieldname: 'last_execution', label: 'Last Execution', fieldtype: 'Datetime' }
    ]
  }
}

// 根据字段类型渲染字段值
function renderFieldValue(field: any, job: any): any {
  const value = job[field.fieldname]
  const fieldtype = field.fieldtype || 'Data'
  
  switch (fieldtype) {
    case 'Check':
      return {
        type: 'checkbox',
        value: Boolean(value)
      }
    
    case 'Datetime':
    case 'Date':
      if (!value) return { type: 'text', value: '—' }
      try {
        const date = new Date(value)
        return {
          type: 'text',
          value: date.toLocaleString()
        }
      } catch {
        return { type: 'text', value: value }
      }
    
    case 'Select':
      // Select 字段直接显示值
      return {
        type: 'text',
        value: value || '—'
      }
    
    case 'Link':
      // Link 字段显示链接值
      return {
        type: 'text',
        value: value || '—'
      }
    
    case 'Data':
    case 'Small Text':
    case 'Text':
    default:
      return {
        type: 'text',
        value: value || '—'
      }
  }
}

// 监听搜索和筛选变化
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(() => {
  loadMetaFields()
  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; 
}

.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;
  gap: 16px;
  padding: 16px 20px;
  background: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
  font-size: 14px;
  font-weight: 600;
  color: #374151;
  align-items: center;
}

.col-header {
  color: #374151;
}

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

.list-item {
  display: grid;
  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);
  align-items: center;
}

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

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

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

.col-name-wrapper {
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 100%;
}

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

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

/* 保留向后兼容的类名 */
.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;
  gap: 8px;
}

/* 将checkbox选中状态（已停止）的背景改为红色 */
.col-status :deep(.n-checkbox--checked .n-checkbox-box) {
  background-color: #ef4444 !important;
  border-color: #ef4444 !important;
}

.col-status :deep(.n-checkbox--checked .n-checkbox-box:hover) {
  background-color: #dc2626 !important;
  border-color: #dc2626 !important;
}

.col-status :deep(.n-checkbox--checked .n-checkbox-box__border) {
  border-color: #ef4444 !important;
}

.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;
}

/* 启动按钮 - 绿色系（与详情页执行按钮配色一致） */
.action-btn.start-btn {
  background: #dcfce7;
  color: #166534;
}

.action-btn.start-btn:hover {
  background: #bbf7d0;
  color: #15803d;
  box-shadow: 0 2px 8px rgba(34, 197, 94, 0.15);
}

/* 停止按钮 - 红色系 */
.action-btn.stop-btn {
  background: #fee2e2;
  color: #dc2626;
}

.action-btn.stop-btn:hover {
  background: #fecaca;
  color: #b91c1c;
  box-shadow: 0 2px 8px rgba(239, 68, 68, 0.15);
}

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

.status-badge {
  padding: 4px 10px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  display: inline-block;
  white-space: nowrap;
}

.status-badge.running {
  background: #dcfce7;
  color: #166534;
  border: 1px solid rgba(34, 197, 94, 0.2);
}

.status-badge.stopped {
  background: #fee2e2;
  color: #dc2626;
  border: 1px solid rgba(239, 68, 68, 0.2);
}

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