<template>
  <div class="page">
    <div class="page-header">
      <div class="header-left">
        <h2>{{ t('Local Jobs') }}</h2>
      </div>
      <div class="header-right">
        <!-- 搜索 / 筛选 -->
        <div class="filters">
          <n-input
            v-model:value="searchQuery"
            :placeholder="t('Search')"
            clearable
            style="width: 220px"
          />
          <n-select
            v-model:value="statusFilter"
            :options="statusOptions"
            style="width: 160px"
          />
        </div>
        <button class="refresh-btn" @click="reload" :disabled="loading">
          <i :class="loading ? 'fa fa-spinner fa-spin' : 'fa fa-refresh'"></i>
        </button>
        <button 
          v-if="selectedJobs.length > 0"
          class="delete-btn" 
          @click="handleDeleteSelected" 
          :disabled="deleting || loading"
        >
          <i class="fa fa-trash"></i>
          {{ t('Delete Selected Jobs') }} ({{ selectedJobs.length }})
        </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-checkbox">
              <input 
                type="checkbox" 
                :checked="selectedJobs.length === jobs.length && jobs.length > 0"
                :indeterminate="selectedJobs.length > 0 && selectedJobs.length < jobs.length"
                @change="toggleSelectAll"
              />
            </div>
            <div class="col-status">{{ t('Status') }}</div>
            <div class="col-job-name">{{ t('Job Name') }}</div>
            <div class="col-queue">{{ t('Queue') }}</div>
            <div class="col-started">{{ t('Started At') }}</div>
            <div class="col-ended">{{ t('Ended At') }}</div>
            <div class="col-duration">{{ t('Time Taken') }}</div>
            <div class="col-actions">{{ t('Actions') }}</div>
          </div>
          <div class="list-body">
            <div 
              v-for="job in jobs" 
              :key="job.job_id" 
              class="job-list-item" 
              :class="{ selected: selectedJobs.includes(job.job_id) }"
              @click="openDetail(job.job_id)"
            >
              <div class="col-checkbox">
                <input 
                  type="checkbox" 
                  :checked="selectedJobs.includes(job.job_id)"
                  @click.stop="toggleJobSelection(job.job_id)"
                />
              </div>
              <div class="col-status" @click.stop="openDetail(job.job_id)">
                <span class="status-badge" :class="job.status">{{ t(job.status) }}</span>
              </div>
              <div class="col-job-name" @click.stop="openDetail(job.job_id)">
                <div class="job-name">{{ job.job_name || job.job_id }}</div>
                <div class="job-id">{{ job.job_id }}</div>
              </div>
              <div class="col-queue" @click.stop="openDetail(job.job_id)">
                <span class="queue-badge">{{ t(job.queue) }}</span>
              </div>
              <div class="col-started" @click.stop="openDetail(job.job_id)">
                {{ formatDateTime(job.started_at) }}
              </div>
              <div class="col-ended" @click.stop="openDetail(job.job_id)">
                {{ formatDateTime(job.ended_at) }}
              </div>
              <div class="col-duration" @click.stop="openDetail(job.job_id)">
                {{ formatDuration(job.time_taken) }}
              </div>
              <div class="col-actions" @click.stop>
                <button 
                  v-if="job.status === 'started' || job.status === 'queued'"
                  class="action-btn stop-btn" 
                  @click="stopJob(job.job_id)" 
                  :title="t('Stop Job')"
                >
                  <i class="fa fa-stop"></i>
                </button>
                <button class="action-btn" @click="openDetail(job.job_id)" :title="t('View Details')">
                  <i class="fa fa-eye"></i>
                </button>
                <button class="action-btn delete-btn" @click="deleteJob(job.job_id)" :title="t('Delete Job')">
                  <i class="fa fa-trash"></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, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { t } from '@/shared/i18n'
import { formatDateTimeInTimezone } from '@/shared/utils/timezone'
import { NInput, NSelect, NPagination, useDialog, useMessage } from 'naive-ui'
import { getLocalJobList, deleteLocalJob, batchDeleteLocalJobs, stopLocalJob } from '@/shared/api/localJobs'

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

const loading = ref(true)
const deleting = ref(false)
const jobs = ref<any[]>([])
const allJobs = ref<any[]>([]) // 保存所有原始数据
const total = ref(0)
const selectedJobs = ref<string[]>([])
const searchQuery = ref('')
const statusFilter = ref('all')
const page = ref(1)
const pageSize = ref(parseInt(localStorage.getItem('itemsPerPage') || '20'))

const statusOptions = computed(() => [
  { label: t('All'), value: 'all' },
  { label: t('Queued'), value: 'queued' },
  { label: t('Started'), value: 'started' },
  { label: t('Finished'), value: 'finished' },
  { label: t('Failed'), value: 'failed' },
  { label: t('Deferred'), value: 'deferred' },
  { label: t('Scheduled'), value: 'scheduled' },
  { label: t('Canceled'), value: 'canceled' }
])

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

async function fetchJobs() {
  loading.value = true
  try {
    const result = await getLocalJobList(page.value, pageSize.value)
    
    allJobs.value = result.items || []
    
    // 处理数据（搜索和过滤）
    processJobs()
    total.value = result.total || 0
  } catch (error) {
    console.error('Fetch jobs error:', error)
    jobs.value = []
    allJobs.value = []
    total.value = 0
    message.error(t('Failed to load jobs'))
  } finally {
    loading.value = false
  }
}

function processJobs() {
  let filteredJobs = [...allJobs.value]
  
  // 前端搜索和过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filteredJobs = filteredJobs.filter(job => 
      job.job_name?.toLowerCase().includes(query) ||
      job.job_id?.toLowerCase().includes(query) ||
      job.queue?.toLowerCase().includes(query)
    )
  }
  
  if (statusFilter.value !== 'all') {
    filteredJobs = filteredJobs.filter(job => job.status === statusFilter.value)
  }
  
  jobs.value = filteredJobs
}

function reload() {
  fetchJobs()
}

// 选择相关函数
function toggleJobSelection(jobId: string) {
  const index = selectedJobs.value.indexOf(jobId)
  if (index > -1) {
    selectedJobs.value.splice(index, 1)
  } else {
    selectedJobs.value.push(jobId)
  }
}

function toggleSelectAll() {
  if (selectedJobs.value.length === jobs.value.length) {
    selectedJobs.value = []
  } else {
    selectedJobs.value = jobs.value.map(job => job.job_id)
  }
}

async function handleDeleteSelected() {
  if (selectedJobs.value.length === 0) return
  
  dialog.error({
    title: t('Confirm Delete'),
    content: t('Are you sure you want to delete the selected jobs? This action cannot be undone.'),
    positiveText: t('Delete'),
    negativeText: t('Cancel'),
    onPositiveClick: async () => {
      deleting.value = true
      try {
        const result = await batchDeleteLocalJobs(selectedJobs.value)
        
        if (result.success) {
          // 使用翻译键和参数进行翻译
          let translatedMessage = t(result.message)
          if (result.message_params) {
            // 替换参数占位符
            Object.entries(result.message_params).forEach(([key, value]) => {
              translatedMessage = translatedMessage.replace(`{${key}}`, String(value))
            })
          }
          message.success(translatedMessage)
          selectedJobs.value = []
          await fetchJobs()
        } else {
          message.error(t('Delete failed'))
        }
      } catch (error) {
        console.error('Delete error:', error)
        message.error(t('Delete failed'))
      } finally {
        deleting.value = false
      }
    }
  })
}

async function deleteJob(jobId: string) {
  dialog.error({
    title: t('Confirm Delete'),
    content: t('Are you sure you want to delete this job?'),
    positiveText: t('Delete'),
    negativeText: t('Cancel'),
    onPositiveClick: async () => {
      try {
        const result = await deleteLocalJob(jobId)
        
        if (result.success) {
          message.success(t('Job deleted successfully'))
          await fetchJobs()
        } else {
          message.error(t('Failed to delete job'))
        }
      } catch (error) {
        console.error('Delete error:', error)
        message.error(t('Failed to delete job'))
      }
    }
  })
}

async function stopJob(jobId: string) {
  dialog.warning({
    title: t('Confirm Stop'),
    content: t('Are you sure you want to stop this job?'),
    positiveText: t('Stop'),
    negativeText: t('Cancel'),
    onPositiveClick: async () => {
      try {
        const result = await stopLocalJob(jobId)
        
        if (result.success) {
          message.success(t('Job stopped successfully'))
          await fetchJobs()
        } else {
          message.error(t('Failed to stop job'))
        }
      } catch (error) {
        console.error('Stop error:', error)
        message.error(t('Failed to stop job'))
      }
    }
  })
}

function formatDateTime(dateStr: string) {
  if (!dateStr) return '—'
  try {
    return formatDateTimeInTimezone(dateStr)
  } catch {
    return dateStr
  }
}

function formatDuration(duration: string | number) {
  if (!duration) return '—'
  if (typeof duration === 'number') {
    return `${duration}s`
  }
  return duration
}

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

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

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

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

onMounted(() => {
  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);
}

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

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

/* 删除按钮 */
.delete-btn {
  background: #ef4444;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.delete-btn:hover {
  background: #dc2626;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
}

.delete-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 列表视图样式 */
.job-list {
  background: #fff;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  width: 100%;
}

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

.list-header > div {
  color: #374151;
}

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

.list-pagination {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  border-top: 1px solid #f3f4f6;
}

.job-list-item {
  display: grid;
  grid-template-columns: 40px 100px 2fr 100px 150px 150px 100px 120px;
  gap: 16px;
  padding: 16px 20px;
  border-bottom: 1px solid #f3f4f6;
  cursor: pointer;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  align-items: center;
}

.job-list-item:hover {
  background: #f8fafc;
}

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

.col-job-name {
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-width: 0;
}

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

.job-id {
  color: #6b7280;
  font-size: 12px;
  font-family: monospace;
}

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

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

.col-started,
.col-ended,
.col-duration {
  display: flex;
  align-items: center;
  color: #6b7280;
  font-size: 13px;
}

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

.status-badge.queued {
  background: #fef3c7;
  color: #92400e;
}

.status-badge.started {
  background: #dbeafe;
  color: #1e40af;
}

.status-badge.finished {
  background: #dcfce7;
  color: #166534;
}

.status-badge.failed {
  background: #fee2e2;
  color: #991b1b;
}

.status-badge.deferred {
  background: #f3e8ff;
  color: #7c3aed;
}

.status-badge.scheduled {
  background: #e0f2fe;
  color: #0369a1;
}

.status-badge.canceled {
  background: #f1f5f9;
  color: #475569;
}

.queue-badge {
  background: #eef2ff;
  color: #334155;
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 11px;
  font-weight: 500;
}

.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.stop-btn:hover {
  background: #f59e0b;
}

.action-btn.delete-btn:hover {
  background: #ef4444;
}

/* 选择相关样式 */
.col-checkbox {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
}

.job-list-item.selected {
  background: #f0f9ff;
  border-color: #3b82f6;
}
</style>
