<template>
  <div class="frame-body adaption-frame-body summary-remind-page">
    <el-card shadow="never">
      <template #header>
        <div class="page-header">
          <div>
            <div class="page-title">简报提醒</div>
            <div class="page-subtitle">维护简报相关定时任务，保留旧版页面的任务增删改和执行控制。</div>
          </div>
          <div class="page-actions">
            <el-button @click="load">刷新</el-button>
            <el-button type="primary" @click="openCreate">新增定时任务</el-button>
          </div>
        </div>
      </template>

      <el-form :inline="true" @submit.prevent>
        <el-form-item>
          <el-input v-model="search.jobName" placeholder="请输入任务名称" clearable @keyup.enter="searchList" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchList">搜索</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="rows" border>
        <el-table-column prop="jobName" label="定时任务" min-width="180" />
        <el-table-column prop="jobGroup" label="任务组" min-width="120" />
        <el-table-column prop="cronExpression" label="Cron表达式" min-width="180" />
        <el-table-column prop="jobDescription" label="任务描述" min-width="220" />
        <el-table-column prop="previousFireTime" label="上次执行时间" min-width="160" />
        <el-table-column prop="nextFireTime" label="下次执行时间" min-width="160" />
        <el-table-column prop="createTime" label="创建时间" min-width="160" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.jobStatus === 'NORMAL' ? 'success' : 'danger'">
              {{ row.jobStatus === 'NORMAL' ? '执行中' : '已停止' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320" align="center" fixed="right">
          <template #default="{ row }">
            <el-button v-if="row.jobStatus === 'NORMAL'" link type="warning" @click="pause(row)">暂停</el-button>
            <el-button v-else link type="success" @click="resume(row)">恢复执行</el-button>
            <el-button link type="primary" @click="openEdit(row)">编辑</el-button>
            <el-button link type="danger" @click="remove(row)">删除</el-button>
            <el-button link @click="trigger(row)">立即执行</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pager-wrap">
        <el-pagination
          v-model:current-page="search.pageIndex"
          v-model:page-size="search.pageSize"
          background
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="load"
          @current-change="load"
        />
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="640px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="任务执行类" prop="jobName">
          <el-input v-model="form.jobName" clearable />
        </el-form-item>
        <el-form-item label="任务组名" prop="jobGroup">
          <el-input v-model="form.jobGroup" clearable />
        </el-form-item>
        <el-form-item label="Cron表达式" prop="cronExpression">
          <el-input v-model="form.cronExpression" clearable />
          <a class="cron-link" target="_blank" href="https://www.matools.com/cron/">在线生成 Cron 表达式</a>
        </el-form-item>
        <el-form-item label="任务描述" prop="jobDescription">
          <el-input v-model="form.jobDescription" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="submit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { reactive, ref } from 'vue'
import {
  summaryRemindTaskAdd,
  summaryRemindTaskDelete,
  summaryRemindTaskEdit,
  summaryRemindTaskList,
  summaryRemindTaskPause,
  summaryRemindTaskResume,
  summaryRemindTaskTrigger,
} from '@/api/otr/summary/core'

const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增定时任务')
const editing = ref(false)
const rows = ref<any[]>([])
const total = ref(0)
const formRef = ref<ElFormInstance>()

const search = reactive({
  pageIndex: 1,
  pageSize: 10,
  jobName: '',
})

const form = reactive({
  id: undefined as string | number | undefined,
  jobName: '',
  jobGroup: '',
  cronExpression: '',
  jobDescription: '',
})

const rules = reactive({
  jobName: [{ required: true, message: '任务名不能为空', trigger: 'blur' }],
  jobGroup: [{ required: true, message: '任务组名不能为空', trigger: 'blur' }],
  cronExpression: [{ required: true, message: 'Cron表达式不能为空', trigger: 'blur' }],
  jobDescription: [{ required: true, message: '任务描述不能为空', trigger: 'blur' }],
})

function resetForm() {
  form.id = undefined
  form.jobName = ''
  form.jobGroup = ''
  form.cronExpression = ''
  form.jobDescription = ''
}

async function load() {
  loading.value = true
  try {
    const res: any = await summaryRemindTaskList({
      pageIndex: search.pageIndex,
      pageSize: search.pageSize,
      jobName: search.jobName,
    })
    const result = res?.result || {}
    rows.value = result.records || result.list || []
    total.value = Number(result.total || rows.value.length)
  } finally {
    loading.value = false
  }
}

function searchList() {
  search.pageIndex = 1
  load()
}

function reset() {
  search.pageIndex = 1
  search.pageSize = 10
  search.jobName = ''
  load()
}

function openCreate() {
  editing.value = false
  dialogTitle.value = '新增定时任务'
  resetForm()
  dialogVisible.value = true
}

function openEdit(row: any) {
  editing.value = true
  dialogTitle.value = '编辑定时任务'
  form.id = row.id
  form.jobName = row.jobName || ''
  form.jobGroup = row.jobGroup || ''
  form.cronExpression = row.cronExpression || ''
  form.jobDescription = row.jobDescription || ''
  dialogVisible.value = true
}

async function submit() {
  const valid = await formRef.value?.validate().catch(() => false)
  if (!valid) return
  submitting.value = true
  try {
    if (editing.value) {
      await summaryRemindTaskEdit({ ...form })
      ElMessage.success('编辑成功')
    } else {
      await summaryRemindTaskAdd({ ...form })
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    load()
  } finally {
    submitting.value = false
  }
}

function buildTaskPayload(row: any) {
  if (row?.keyId) {
    return { keyId: row.keyId }
  }
  return {
    id: row?.id,
    jobName: row?.jobName,
    jobGroup: row?.jobGroup,
  }
}

function pause(row: any) {
  ElMessageBox.confirm(`确定暂停任务 ${row.jobName} 吗？`, '系统提示', {
    confirmButtonText: '提交',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      await summaryRemindTaskPause(buildTaskPayload(row))
      ElMessage.success('暂停成功')
      load()
    })
    .catch(() => undefined)
}

function resume(row: any) {
  ElMessageBox.confirm(`确定恢复任务 ${row.jobName} 吗？`, '系统提示', {
    confirmButtonText: '提交',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      await summaryRemindTaskResume(buildTaskPayload(row))
      ElMessage.success('恢复成功')
      load()
    })
    .catch(() => undefined)
}

function trigger(row: any) {
  ElMessageBox.confirm(`确定立即执行任务 ${row.jobName} 吗？`, '系统提示', {
    confirmButtonText: '提交',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      await summaryRemindTaskTrigger(buildTaskPayload(row))
      ElMessage.success('执行成功')
    })
    .catch(() => undefined)
}

function remove(row: any) {
  ElMessageBox.confirm(`确定删除任务 ${row.jobName} 吗？`, '系统提示', {
    confirmButtonText: '提交',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      await summaryRemindTaskDelete(buildTaskPayload(row))
      ElMessage.success('删除成功')
      load()
    })
    .catch(() => undefined)
}

load()
</script>

<style scoped lang="scss">
.summary-remind-page {
  .page-header {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 16px;
  }

  .page-title {
    font-size: 18px;
    font-weight: 600;
    color: #111827;
  }

  .page-subtitle {
    margin-top: 4px;
    font-size: 13px;
    color: #6b7280;
  }

  .page-actions {
    display: flex;
    gap: 12px;
  }

  .pager-wrap {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
  }

  .cron-link {
    display: inline-block;
    margin-top: 6px;
    color: #409eff;
    text-decoration: none;
  }
}
</style>

