<template>
  <div class="page-content">
    <div class="mb-5 flex items-center justify-between gap-4">
      <div>
        <h2 class="text-xl font-semibold">定时任务</h2>
        <p class="text-g-500 mt-1 text-sm">创建自动化任务：按 Cron 计划执行应用/数字员工，支持查看执行历史</p>
      </div>
      <ElButton type="primary" @click="openCreate">新建任务</ElButton>
    </div>

    <ElTable v-loading="loading" :data="tasks" row-key="id">
      <ElTableColumn prop="name" label="名称" min-width="160" />
      <ElTableColumn prop="target_type" label="目标类型" width="110">
        <template #default="{ row }">{{ row.target_type === 'application' ? '应用' : '数字员工' }}</template>
      </ElTableColumn>
      <ElTableColumn prop="target_code" label="目标" min-width="150" />
      <ElTableColumn prop="cron_expression" label="Cron" width="110" />
      <ElTableColumn prop="timezone" label="时区" width="130" />
      <ElTableColumn label="状态" width="90">
        <template #default="{ row }">
          <ElTag :type="row.enabled ? 'success' : 'info'">{{ row.enabled ? '启用' : '暂停' }}</ElTag>
        </template>
      </ElTableColumn>
      <ElTableColumn prop="last_status" label="上次结果" width="100">
        <template #default="{ row }">
          <ElTag :type="row.last_status === 'success' ? 'success' : row.last_status ? 'danger' : 'info'">
            {{ row.last_status || '—' }}
          </ElTag>
        </template>
      </ElTableColumn>
      <ElTableColumn prop="next_run_at" label="下次执行" width="180" />
      <ElTableColumn label="操作" width="260" fixed="right">
        <template #default="{ row }">
          <ElButton link type="success" :disabled="row.enabled" @click="setEnabled(row, true)">启动</ElButton>
          <ElButton link type="warning" :disabled="!row.enabled" @click="setEnabled(row, false)">暂停</ElButton>
          <ElButton link type="primary" @click="runNow(row)">立即执行</ElButton>
          <ElButton link type="primary" @click="openRuns(row)">历史</ElButton>
          <ElButton link type="primary" @click="openEdit(row)">编辑</ElButton>
          <ElButton link type="danger" @click="remove(row)">删除</ElButton>
        </template>
      </ElTableColumn>
    </ElTable>

    <ElDialog v-model="dialogVisible" :title="editingId ? '编辑任务' : '新建任务'" width="640px">
      <ElForm ref="formRef" :model="form" :rules="rules" label-width="110px">
        <ElFormItem label="名称" prop="name"><ElInput v-model="form.name" maxlength="128" /></ElFormItem>
        <ElFormItem label="目标类型" prop="target_type">
          <ElSelect v-model="form.target_type" class="w-full">
            <ElOption label="应用" value="application" />
            <ElOption label="数字员工" value="digital_employee" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="目标代码" prop="target_code"><ElInput v-model="form.target_code" placeholder="如 my-app / my-employee" /></ElFormItem>
        <ElFormItem label="Cron 表达式" prop="cron_expression"><ElInput v-model="form.cron_expression" placeholder="五字段,如 0 9 * * 1" /></ElFormItem>
        <ElFormItem label="时区">
          <ElInput v-model="form.timezone" placeholder="Asia/Shanghai" />
        </ElFormItem>
        <ElFormItem label="提示词">
          <ElInput v-model="form.prompt" type="textarea" :rows="3" placeholder="可选,追加给目标的任务提示" />
        </ElFormItem>
        <ElFormItem label="执行 API Key">
          <ElInput v-model="form.api_key" type="password" show-password :placeholder="editingId ? '留空表示不更换' : '必填'" />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" :loading="saving" @click="submit">保存</ElButton>
      </template>
    </ElDialog>

    <ElDialog v-model="runsVisible" title="执行历史" width="820px">
      <ElTable v-loading="runsLoading" :data="runs" size="small">
        <ElTableColumn prop="scheduled_for" label="计划时间" width="170" />
        <ElTableColumn prop="started_at" label="开始时间" width="170" />
        <ElTableColumn label="状态" width="90">
          <template #default="{ row }">
            <ElTag :type="row.status === 'success' ? 'success' : row.status === 'failed' ? 'danger' : 'warning'">
              {{ row.status }}
            </ElTag>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="attempts" label="尝试" width="70" />
        <ElTableColumn prop="error" label="错误" min-width="200" show-overflow-tooltip />
      </ElTable>
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
  import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'
  import request from '@/utils/http'

  interface Task {
    id: string
    name: string
    target_type: string
    target_code: string
    cron_expression: string
    timezone: string
    prompt?: string
    enabled: boolean
    last_status?: string
    next_run_at?: string
  }

  interface TaskInput {
    name: string
    target_type: string
    target_code: string
    cron_expression: string
    timezone: string
    prompt?: string
    api_key?: string
  }

  const tasks = ref<Task[]>([])
  const loading = ref(false)
  const saving = ref(false)
  const dialogVisible = ref(false)
  const editingId = ref('')
  const runsVisible = ref(false)
  const runsLoading = ref(false)
  const runs = ref<any[]>([])
  const formRef = ref<FormInstance>()
  const form = reactive<TaskInput>({
    name: '',
    target_type: 'application',
    target_code: '',
    cron_expression: '0 9 * * 1',
    timezone: 'Asia/Shanghai',
    prompt: '',
    api_key: ''
  })
  const rules: FormRules = {
    name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
    target_type: [{ required: true, message: '请选择目标类型', trigger: 'change' }],
    target_code: [{ required: true, message: '请输入目标代码', trigger: 'blur' }],
    cron_expression: [{ required: true, message: '请输入 Cron 表达式', trigger: 'blur' }]
  }

  async function load() {
    loading.value = true
    try {
      tasks.value = await request.get<Task[]>({ url: '/api/v1/portal/scheduled-tasks' })
    } finally {
      loading.value = false
    }
  }

  function openCreate() {
    editingId.value = ''
    Object.assign(form, { name: '', target_type: 'application', target_code: '', cron_expression: '0 9 * * 1', timezone: 'Asia/Shanghai', prompt: '', api_key: '' })
    dialogVisible.value = true
  }

  function openEdit(row: Task) {
    editingId.value = row.id
    Object.assign(form, {
      name: row.name,
      target_type: row.target_type,
      target_code: row.target_code,
      cron_expression: row.cron_expression,
      timezone: row.timezone,
      prompt: row.prompt || '',
      api_key: ''
    })
    dialogVisible.value = true
  }

  async function submit() {
    if (!(await formRef.value?.validate())) return
    saving.value = true
    try {
      const payload: TaskInput = { ...form }
      if (!payload.api_key) delete payload.api_key
      if (editingId.value) {
        await request.put({ url: `/api/v1/portal/scheduled-tasks/${editingId.value}`, params: payload })
        ElMessage.success('任务已更新')
      } else {
        await request.post({ url: '/api/v1/portal/scheduled-tasks', params: payload })
        ElMessage.success('任务已创建')
      }
      dialogVisible.value = false
      await load()
    } finally {
      saving.value = false
    }
  }

  async function setEnabled(row: Task, enabled: boolean) {
    try {
      await request.post({ url: `/api/v1/portal/scheduled-tasks/${row.id}/${enabled ? 'start' : 'pause'}` })
      await load()
    } catch { /* 全局错误提示 */ }
  }

  async function runNow(row: Task) {
    try {
      await request.post({ url: `/api/v1/portal/scheduled-tasks/${row.id}/run` })
      ElMessage.success('已加入执行队列')
    } catch { /* 全局错误提示 */ }
  }

  async function remove(row: Task) {
    try {
      await ElMessageBox.confirm(`确认删除任务「${row.name}」？`, '删除任务', { type: 'warning' })
    } catch {
      return
    }
    try {
      await request.del({ url: `/api/v1/portal/scheduled-tasks/${row.id}` })
      ElMessage.success('已删除')
      await load()
    } catch { /* 全局错误提示 */ }
  }

  async function openRuns(row: Task) {
    runsVisible.value = true
    runsLoading.value = true
    try {
      runs.value = await request.get<any[]>({ url: `/api/v1/portal/scheduled-tasks/${row.id}/runs` })
    } finally {
      runsLoading.value = false
    }
  }

  onMounted(load)
</script>
