<template>
  <div class="schedule-page">
    <div class="page-header">
      <h2>定时任务</h2>
      <el-button type="primary" @click="openCreateDialog">
        <el-icon><Plus /></el-icon>
        创建任务
      </el-button>
    </div>

    <div class="page-card">
      <el-table :data="tasks" v-loading="loading">
        <el-table-column prop="title" label="任务名称" min-width="160" />
        <el-table-column label="任务类型" width="120">
          <template #default="{ row }">
            <el-tag size="small">{{ getTaskTypeText(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="执行时间" width="160">
          <template #default="{ row }">
            {{ formatTime(row.executeTime) }}
          </template>
        </el-table-column>
        <el-table-column label="重复" width="140">
          <template #default="{ row }">
            {{ getRepeatText(row.repeatType) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              :model-value="row.enabled"
              @change="(val: boolean) => handleToggle(row, val)"
              active-text="启用"
              inactive-text="停用"
              inline-prompt
            />
          </template>
        </el-table-column>
        <el-table-column label="下次执行" width="170">
          <template #default="{ row }">
            <span v-if="row.enabled">{{ formatNextRun(row) }}</span>
            <span v-else class="text-muted">已停用</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="openEditDialog(row)">编辑</el-button>
            <el-button type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-empty v-if="tasks.length === 0 && !loading" description="暂无定时任务，点击右上角创建" />
    </div>

    <!-- 创建/编辑任务对话框 -->
    <el-dialog
      v-model="showDialog"
      :title="editingTask ? '编辑定时任务' : '创建定时任务'"
      width="520px"
      @closed="resetForm"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="任务名称">
          <el-input v-model="form.title" placeholder="例如：每天同步评论" />
        </el-form-item>
        <el-form-item label="任务类型">
          <el-select v-model="form.type" style="width: 100%" placeholder="选择任务类型">
            <el-option label="同步评论" value="sync_comments" />
            <el-option label="同步作品" value="sync_works" />
            <el-option label="刷新账号" value="sync_accounts" />
          </el-select>
        </el-form-item>
        <el-form-item label="执行时间">
          <el-time-picker
            v-model="form.executeTime"
            format="HH:mm"
            placeholder="选择执行时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="重复方式">
          <el-radio-group v-model="form.repeatType">
            <el-radio-button label="once">仅一次</el-radio-button>
            <el-radio-button label="daily">每天</el-radio-button>
            <el-radio-button label="weekday">工作日</el-radio-button>
            <el-radio-button label="weekly">每周</el-radio-button>
            <el-radio-button label="custom">自定义</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.repeatType === 'weekly'" label="周几">
          <el-select v-model="form.dayOfWeek" placeholder="选择星期" style="width: 100%">
            <el-option label="周一" :value="1" />
            <el-option label="周二" :value="2" />
            <el-option label="周三" :value="3" />
            <el-option label="周四" :value="4" />
            <el-option label="周五" :value="5" />
            <el-option label="周六" :value="6" />
            <el-option label="周日" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.repeatType === 'custom'" label="自定义天数">
          <el-input-number v-model="form.customDays" :min="2" :max="30" />
          <span style="margin-left: 8px; color: var(--el-text-color-secondary);">天执行一次</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          {{ editingTask ? '保存' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';

interface ScheduledTask {
  id: string;
  title: string;
  type: string;
  executeTime: string; // "HH:mm"
  repeatType: 'once' | 'daily' | 'weekday' | 'weekly' | 'custom';
  dayOfWeek?: number;
  customDays?: number;
  enabled: boolean;
  createdAt: string;
  lastRunAt?: string;
}

const STORAGE_KEY = 'media-manager-scheduled-tasks';
const CHECK_INTERVAL = 60_000;

const loading = ref(false);
const saving = ref(false);
const showDialog = ref(false);
const editingTask = ref<ScheduledTask | null>(null);
const tasks = ref<ScheduledTask[]>([]);

const form = reactive({
  title: '',
  type: 'sync_comments',
  executeTime: null as Dayjs | null,
  repeatType: 'daily' as ScheduledTask['repeatType'],
  dayOfWeek: 1,
  customDays: 3,
});

let checkTimer: ReturnType<typeof setInterval> | null = null;

function loadTasks() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    tasks.value = raw ? JSON.parse(raw) : [];
  } catch {
    tasks.value = [];
  }
}

function saveTasks() {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks.value));
}

function resetForm() {
  editingTask.value = null;
  form.title = '';
  form.type = 'sync_comments';
  form.executeTime = null;
  form.repeatType = 'daily';
  form.dayOfWeek = 1;
  form.customDays = 3;
}

function openCreateDialog() {
  resetForm();
  showDialog.value = true;
}

function openEditDialog(task: ScheduledTask) {
  editingTask.value = task;
  form.title = task.title;
  form.type = task.type;
  const [h, m] = (task.executeTime || '09:00').split(':').map(Number);
  form.executeTime = dayjs().hour(h).minute(m);
  form.repeatType = task.repeatType;
  form.dayOfWeek = task.dayOfWeek ?? 1;
  form.customDays = task.customDays ?? 3;
  showDialog.value = true;
}

async function handleSave() {
  if (!form.title.trim()) { ElMessage.warning('请输入任务名称'); return; }
  if (!form.executeTime) { ElMessage.warning('请选择执行时间'); return; }
  if (form.repeatType === 'weekly' && !form.dayOfWeek) { ElMessage.warning('请选择星期几'); return; }

  saving.value = true;
  try {
    const timeStr = form.executeTime.format('HH:mm');
    const taskData: ScheduledTask = {
      id: editingTask.value?.id || Date.now().toString(36) + Math.random().toString(36).slice(2, 6),
      title: form.title.trim(),
      type: form.type,
      executeTime: timeStr,
      repeatType: form.repeatType,
      dayOfWeek: form.dayOfWeek,
      customDays: form.customDays,
      enabled: true,
      createdAt: new Date().toISOString(),
    };

    if (editingTask.value) {
      const idx = tasks.value.findIndex(t => t.id === editingTask.value!.id);
      if (idx >= 0) {
        taskData.enabled = editingTask.value.enabled;
        taskData.createdAt = editingTask.value.createdAt;
        taskData.lastRunAt = editingTask.value.lastRunAt;
        tasks.value[idx] = taskData;
      }
    } else {
      tasks.value.push(taskData);
    }

    saveTasks();
    showDialog.value = false;
    ElMessage.success(editingTask.value ? '任务已更新' : '任务已创建');
  } finally {
    saving.value = false;
  }
}

async function handleDelete(task: ScheduledTask) {
  await ElMessageBox.confirm(`确定删除任务"${task.title}"吗？`, '提示', { type: 'warning' });
  tasks.value = tasks.value.filter(t => t.id !== task.id);
  saveTasks();
  ElMessage.success('已删除');
}

function handleToggle(task: ScheduledTask, enabled: boolean) {
  const idx = tasks.value.findIndex(t => t.id === task.id);
  if (idx >= 0) {
    tasks.value[idx].enabled = enabled;
    saveTasks();
    ElMessage.success(enabled ? '已启用' : '已停用');
  }
}

function getTaskTypeText(type: string) {
  const map: Record<string, string> = {
    sync_comments: '同步评论', sync_works: '同步作品', sync_accounts: '刷新账号',
  };
  return map[type] || type;
}

function getRepeatText(repeatType: string) {
  const map: Record<string, string> = {
    once: '仅一次', daily: '每天', weekday: '工作日', weekly: '每周', custom: '自定义',
  };
  return map[repeatType] || repeatType;
}

function formatTime(time: string) { return time || '-'; }

function formatNextRun(task: ScheduledTask): string {
  const now = dayjs();
  const [h, m] = (task.executeTime || '00:00').split(':').map(Number);
  const target = now.hour(h).minute(m).second(0);

  for (let i = 0; i < 8; i++) {
    const candidate = target.add(i, 'day');
    if (shouldRunOnDate(task, candidate)) return candidate.format('YYYY-MM-DD HH:mm');
  }
  return '-';
}

function shouldRunOnDate(task: ScheduledTask, date: Dayjs): boolean {
  switch (task.repeatType) {
    case 'once': return date.isSame(dayjs(), 'day');
    case 'daily': return true;
    case 'weekday': return date.day() >= 1 && date.day() <= 5;
    case 'weekly': return date.day() === (task.dayOfWeek ?? 1);
    case 'custom': {
      const days = task.customDays || 3;
      const created = dayjs(task.createdAt).startOf('day');
      const diff = date.startOf('day').diff(created, 'day');
      return diff >= 0 && diff % days === 0;
    }
    default: return true;
  }
}

function checkAndExecute() {
  const now = dayjs();
  const currentTime = now.format('HH:mm');

  for (const task of tasks.value) {
    if (!task.enabled || task.executeTime !== currentTime || !shouldRunOnDate(task, now)) continue;
    if (task.lastRunAt && dayjs(task.lastRunAt).isSame(now, 'minute')) continue;

    task.lastRunAt = now.toISOString();
    if (task.repeatType === 'once') task.enabled = false;

    executeScheduledTask(task);
    saveTasks();
  }
}

async function executeScheduledTask(task: ScheduledTask) {
  try {
    const { useTaskQueueStore } = await import('@/stores/taskQueue');
    const taskStore = useTaskQueueStore();
    switch (task.type) {
      case 'sync_comments': await taskStore.syncComments(); break;
      case 'sync_works': await taskStore.syncWorks(); break;
      case 'sync_accounts': {
        const { accountsApi } = await import('@/api/accounts');
        const accounts = await accountsApi.getAccounts();
        for (const account of accounts) { await taskStore.syncAccount(account.id, account.accountName); }
        break;
      }
    }
  } catch (error) {
    console.error(`[Schedule] Failed: ${task.title}`, error);
  }
}

onMounted(() => { loadTasks(); checkTimer = setInterval(checkAndExecute, CHECK_INTERVAL); });
onUnmounted(() => { if (checkTimer) { clearInterval(checkTimer); checkTimer = null; } });
</script>

<style lang="scss" scoped>
.schedule-page { max-width: 1200px; margin: 0 auto; }
.page-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px; h2 { margin: 0; } }
.page-card { background: #fff; border-radius: 8px; padding: 20px 24px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06); }
.text-muted { color: var(--el-text-color-placeholder); font-size: 13px; }
</style>
