<template>
  <div class="page-container-flex">
    <van-nav-bar title="定时任务" left-arrow placeholder @click-left="onClickLeft" />
    <div class="scroll-content">
      <van-pull-refresh v-model="loading" @refresh="fetchTasks">
        <div v-for="task in tasks" :key="task.name" class="task-card">
          <van-cell-group inset>
            <van-cell :title="task.jobDescription" :label="task.triggerDescription || task.name">
              <template #value>
                <van-tag :type="task.status === 'Paused' ? 'warning' : 'success'">
                  {{ task.status === 'Paused' ? '已暂停' : '已启动' }}
                </van-tag>
              </template>
            </van-cell>
            <van-cell title="任务标识" :value="task.name" />
            <van-cell title="下次执行" :value="task.nextRunTime || '无'" />
            <div class="card-footer">
              <van-row gutter="10">
                <van-col span="12">
                  <van-button 
                    type="primary" 
                    size="small" 
                    block 
                    icon="play"
                    @click="handleExecute(task)"
                  >
                    立即执行
                  </van-button>
                </van-col>
                <van-col span="12">
                  <van-button 
                    v-if="task.status !== 'Paused'"
                    type="warning" 
                    size="small" 
                    block 
                    icon="pause"
                    @click="handlePause(task)"
                  >
                    暂停任务
                  </van-button>
                  <van-button 
                    v-else
                    type="success" 
                    size="small" 
                    block 
                    icon="play-circle-o"
                    @click="handleResume(task)"
                  >
                    恢复任务
                  </van-button>
                </van-col>
              </van-row>
            </div>
          </van-cell-group>
        </div>
      </van-pull-refresh>

      <van-empty v-if="tasks.length === 0 && !loading" description="无定时任务" />

      <!-- 底部安全距离 -->
      <div style="height: calc(20px + env(safe-area-inset-bottom, 0px))"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showConfirmDialog, showSuccessToast, showToast, showLoadingToast, closeToast } from 'vant'
import { getJobs, executeJob, pauseJob, resumeJob } from '@/api/job'

const router = useRouter()
const loading = ref(false)
const tasks = ref([])

const fetchTasks = async () => {
  loading.value = true
  try {
    const { success, data, message } = await getJobs()
    if (success) {
      tasks.value = data
    } else {
      showToast(message || '获取任务列表失败')
    }
  } catch (error) {
    console.error('获取任务列表失败:', error)
    showToast('获取任务列表失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchTasks()
})

const onClickLeft = () => {
  router.back()
}

const handleExecute = async (task) => {
  try {
    await showConfirmDialog({
      title: '确认执行',
      message: `确定要立即执行"${task.jobDescription}"吗？`,
    })

    showLoadingToast({
      message: '执行中...',
      forbidClick: true,
      duration: 0
    })

    const { success, message } = await executeJob(task.name)
    if (success) {
      showSuccessToast('执行指令已发送')
      setTimeout(fetchTasks, 1000)
    } else {
      showToast(message || '执行失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('执行失败:', error)
      showToast('执行失败')
    }
  } finally {
    closeToast()
  }
}

const handlePause = async (task) => {
  try {
    await showConfirmDialog({
      title: '确认暂停',
      message: `确定要暂停"${task.jobDescription}"吗？`,
    })

    const { success, message } = await pauseJob(task.name)
    if (success) {
      showSuccessToast('已暂停')
      fetchTasks()
    } else {
      showToast(message || '暂停失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('暂停失败:', error)
      showToast('暂停失败')
    }
  }
}

const handleResume = async (task) => {
  try {
    const { success, message } = await resumeJob(task.name)
    if (success) {
      showSuccessToast('已恢复')
      fetchTasks()
    } else {
      showToast(message || '恢复失败')
    }
  } catch (error) {
    console.error('恢复失败:', error)
    showToast('恢复失败')
  }
}
</script>

<style scoped>
.task-card {
  margin-top: 15px;
}

.card-footer {
  padding: 10px 16px;
  background-color: var(--van-background-2);
}

.scroll-content {
  padding-bottom: 20px;
}

/* 设置页面容器背景色 */
:deep(.van-nav-bar) {
  background: transparent !important;
}
</style>
