/**
 * @description 定时任务相关API
 * @author yslg
 * @since 2025-10-25
 */

import { api } from '@/apis/index';
import type { 
  CrontabTask, 
  CrontabLog, 
  DataCollectionItem, 
  CrontabItem, 
  TaskMeta,
  EmailDefault,
  EmailRecipient,
  CreateTaskRequest,
  ResultDomain, 
  PageParam 
} from '@/types';

/**
 * 定时任务API服务
 */
export const crontabApi = {
  baseUrl: '/crontab',

  // ==================== 定时任务管理 ====================

  /**
   * 获取可创建的定时任务列表（从数据库获取任务元数据）
   * @returns Promise<ResultDomain<TaskMeta>>
   */
  async getEnabledCrontabList(): Promise<ResultDomain<TaskMeta>> {
    const response = await api.get<TaskMeta>(`${this.baseUrl}/getEnabledCrontabList`);
    return response.data;
  },

  /**
   * 创建定时任务
   * @param task 任务对象
   * @returns Promise<ResultDomain<CrontabTask>>
   */
  async createTask(task: CreateTaskRequest): Promise<ResultDomain<CrontabTask>> {
    const response = await api.post<CrontabTask>(`${this.baseUrl}/crontabTask`, task);
    return response.data;
  },

  /**
   * 更新定时任务
   * @param request 更新任务请求（包含任务信息、元数据ID等）
   * @returns Promise<ResultDomain<CrontabTask>>
   */
  async updateTask(request: CreateTaskRequest): Promise<ResultDomain<CrontabTask>> {
    const response = await api.put<CrontabTask>(`${this.baseUrl}/crontabTask`, request);
    return response.data;
  },

  /**
   * 删除定时任务
   * @param task 任务对象
   * @returns Promise<ResultDomain<CrontabTask>>
   */
  async deleteTask(task: CrontabTask): Promise<ResultDomain<CrontabTask>> {
    const response = await api.delete<CrontabTask>(`${this.baseUrl}/crontabTask`, task);
    return response.data;
  },

  /**
   * 根据ID查询任务
   * @param taskId 任务ID
   * @returns Promise<ResultDomain<CrontabTask>>
   */
  async getTaskById(taskId: string): Promise<ResultDomain<CrontabTask>> {
    const response = await api.get<CrontabTask>(`${this.baseUrl}/task/${taskId}`);
    return response.data;
  },

  /**
   * 查询任务列表
   * @param filter 过滤条件
   * @returns Promise<ResultDomain<CrontabTask>>
   */
  async getTaskList(filter?: Partial<CrontabTask>): Promise<ResultDomain<CrontabTask>> {
    const response = await api.post<CrontabTask>(`${this.baseUrl}/task/list`, filter);
    return response.data;
  },

  /**
   * 分页查询任务列表
   * @param filter 过滤条件
   * @param pageParam 分页参数
   * @returns Promise<ResultDomain<CrontabTask>>
   */
  async getTaskPage(filter?: Partial<CrontabTask>, pageParam?: PageParam): Promise<ResultDomain<CrontabTask>> {
    const response = await api.post<CrontabTask>(`${this.baseUrl}/crontabTaskPage`, {
      filter,
      pageParam: {
        pageNumber: pageParam?.pageNumber || 1,
        pageSize: pageParam?.pageSize || 10
      }
    });
    return response.data;
  },

  /**
   * 启动定时任务
   * @param taskId 任务ID
   * @returns Promise<ResultDomain<CrontabTask>>
   */
  async startTask(taskId: string): Promise<ResultDomain<CrontabTask>> {
    const response = await api.post<CrontabTask>(`${this.baseUrl}/task/start/${taskId}`);
    return response.data;
  },

  /**
   * 暂停定时任务
   * @param taskId 任务ID
   * @returns Promise<ResultDomain<CrontabTask>>
   */
  async pauseTask(taskId: string): Promise<ResultDomain<CrontabTask>> {
    const response = await api.post<CrontabTask>(`${this.baseUrl}/task/pause/${taskId}`);
    return response.data;
  },

  /**
   * 立即执行一次任务
   * @param taskId 任务ID
   * @returns Promise<ResultDomain<CrontabTask>>
   */
  async executeTaskOnce(taskId: string): Promise<ResultDomain<CrontabTask>> {
    const response = await api.post<CrontabTask>(`${this.baseUrl}/task/execute/${taskId}`,{},{showLoading: false});
    return response.data;
  },

  /**
   * 验证Cron表达式
   * @param cronExpression Cron表达式
   * @returns Promise<ResultDomain<string>>
   */
  async validateCronExpression(cronExpression: string): Promise<ResultDomain<string>> {
    const response = await api.get<string>(`${this.baseUrl}/task/validate`, {
      cronExpression
    });
    return response.data;
  },

  // ==================== 定时任务日志 ====================

  /**
   * 根据任务ID查询日志
   * @param taskId 任务ID
   * @returns Promise<ResultDomain<CrontabLog>>
   */
  async getLogsByTaskId(taskId: string): Promise<ResultDomain<CrontabLog>> {
    const response = await api.get<CrontabLog>(`${this.baseUrl}/log/task/${taskId}`);
    return response.data;
  },

  /**
   * 查询日志列表
   * @param filter 过滤条件
   * @returns Promise<ResultDomain<CrontabLog>>
   */
  async getLogList(filter?: Partial<CrontabLog>): Promise<ResultDomain<CrontabLog>> {
    const response = await api.post<CrontabLog>(`${this.baseUrl}/log/list`, filter);
    return response.data;
  },

  /**
   * 分页查询日志列表
   * @param filter 过滤条件
   * @param pageParam 分页参数
   * @returns Promise<ResultDomain<CrontabLog>>
   */
  async getLogPage(filter?: Partial<CrontabLog>, pageParam?: PageParam): Promise<ResultDomain<CrontabLog>> {
    const response = await api.post<CrontabLog>(`${this.baseUrl}/crontabTaskLogPage`, {
      filter,
      pageParam: {
        pageNumber: pageParam?.pageNumber || 1,
        pageSize: pageParam?.pageSize || 10
      }
    });
    return response.data;
  },

  /**
   * 根据ID查询日志详情
   * @param logId 日志ID
   * @returns Promise<ResultDomain<CrontabLog>>
   */
  async getLogById(logId: string): Promise<ResultDomain<CrontabLog>> {
    const response = await api.get<CrontabLog>(`${this.baseUrl}/log/${logId}`);
    return response.data;
  },

  /**
   * 清理指定天数之前的日志
   * @param days 天数
   * @returns Promise<ResultDomain<number>>
   */
  async cleanLogs(days: number): Promise<ResultDomain<number>> {
    const response = await api.delete<number>(`${this.baseUrl}/log/clean/${days}`);
    return response.data;
  },

  /**
   * 删除日志
   * @param log 日志对象
   * @returns Promise<ResultDomain<CrontabLog>>
   */
  async deleteLog(log: CrontabLog): Promise<ResultDomain<CrontabLog>> {
    const response = await api.delete<CrontabLog>(`${this.baseUrl}/log`, log);
    return response.data;
  },

  // ==================== 数据采集项管理 ====================

  /**
   * 根据任务日志ID查询数据采集项列表
   * @param taskLogId 任务日志ID
   * @returns Promise<ResultDomain<DataCollectionItem>>
   */
  async getCollectionItemsByLogId(taskLogId: string): Promise<ResultDomain<DataCollectionItem>> {
    const response = await api.get<DataCollectionItem>(`${this.baseUrl}/collection/item/task/${taskLogId}`);
    return response.data;
  },

  /**
   * 分页查询数据采集项列表
   * @param filter 过滤条件
   * @param pageParam 分页参数
   * @returns Promise<ResultDomain<DataCollectionItem>>
   */
  async getCollectionItemPage(filter?: Partial<DataCollectionItem>, pageParam?: PageParam): Promise<ResultDomain<DataCollectionItem>> {
    const response = await api.post<DataCollectionItem>(`${this.baseUrl}/collection/item/page`, {
      filter,
      pageParam: {
        pageNumber: pageParam?.pageNumber || 1,
        pageSize: pageParam?.pageSize || 10
      }
    });
    return response.data;
  },

  /**
   * 转换采集项为资源文章
   * @param itemId 采集项ID
   * @param tagId 标签ID
   * @returns Promise<ResultDomain<string>>
   */
  async convertItemToResource(itemId: string, tagId: string): Promise<ResultDomain<string>> {
    const response = await api.post<string>(`${this.baseUrl}/collection/item/resource`, {
      itemId,
      tagId
    });
    return response.data;
  },

  /**
   * 更新采集项状态为已转换
   * @param itemId 采集项ID
   * @param status 状态
   * @returns Promise<ResultDomain<string>>
   */
  async updateCollectionItemStatus(itemId: string, status: number): Promise<ResultDomain<string>> {
    const response = await api.put<string>(`${this.baseUrl}/collection/item/${itemId}/status/${status}`);
    return response.data;
  },


  // ==================== 任务元数据管理 ====================

  /**
   * 创建任务元数据
   * @param taskMeta 任务元数据
   * @returns Promise<ResultDomain<TaskMeta>>
   */
  async createTaskMeta(taskMeta: TaskMeta): Promise<ResultDomain<TaskMeta>> {
    const response = await api.post<TaskMeta>(`${this.baseUrl}/meta`, taskMeta);
    return response.data;
  },

  /**
   * 更新任务元数据
   * @param taskMeta 任务元数据
   * @returns Promise<ResultDomain<TaskMeta>>
   */
  async updateTaskMeta(taskMeta: TaskMeta): Promise<ResultDomain<TaskMeta>> {
    const response = await api.put<TaskMeta>(`${this.baseUrl}/meta`, taskMeta);
    return response.data;
  },

  /**
   * 删除任务元数据
   * @param metaId 元数据ID
   * @returns Promise<ResultDomain<boolean>>
   */
  async deleteTaskMeta(metaId: string): Promise<ResultDomain<boolean>> {
    const response = await api.delete<boolean>(`${this.baseUrl}/meta/${metaId}`);
    return response.data;
  },

  /**
   * 根据ID查询任务元数据
   * @param metaId 元数据ID
   * @returns Promise<ResultDomain<TaskMeta>>
   */
  async getTaskMetaById(metaId: string): Promise<ResultDomain<TaskMeta>> {
    const response = await api.get<TaskMeta>(`${this.baseUrl}/meta/${metaId}`);
    return response.data;
  },

  /**
   * 查询所有任务元数据
   * @returns Promise<ResultDomain<TaskMeta>>
   */
  async getAllTaskMeta(): Promise<ResultDomain<TaskMeta>> {
    const response = await api.get<TaskMeta>(`${this.baseUrl}/meta/all`);
    return response.data;
  },

  /**
   * 根据分类查询任务元数据
   * @param category 分类
   * @returns Promise<ResultDomain<TaskMeta>>
   */
  async getTaskMetaByCategory(category: string): Promise<ResultDomain<TaskMeta>> {
    const response = await api.get<TaskMeta>(`${this.baseUrl}/meta/category/${category}`);
    return response.data;
  },

  /**
   * 分页查询任务元数据
   * @param filter 过滤条件
   * @param pageParam 分页参数
   * @returns Promise<ResultDomain<TaskMeta>>
   */
  async getTaskMetaPage(filter?: Partial<TaskMeta>, pageParam?: PageParam): Promise<ResultDomain<TaskMeta>> {
    const response = await api.post<TaskMeta>(`${this.baseUrl}/meta/page`, {
      filter,
      pageParam: {
        pageNumber: pageParam?.pageNumber || 1,
        pageSize: pageParam?.pageSize || 10
      }
    });
    return response.data;
  },

  // ==================== 邮件默认接收人管理 ====================

  /**
   * 创建默认接收人
   * @param emailDefault 默认接收人
   * @returns Promise<ResultDomain<EmailDefault>>
   */
  async createEmailDefault(emailDefault: EmailDefault): Promise<ResultDomain<EmailDefault>> {
    const response = await api.post<EmailDefault>(`${this.baseUrl}/email/default`, emailDefault);
    return response.data;
  },

  /**
   * 更新默认接收人
   * @param emailDefault 默认接收人
   * @returns Promise<ResultDomain<EmailDefault>>
   */
  async updateEmailDefault(emailDefault: EmailDefault): Promise<ResultDomain<EmailDefault>> {
    const response = await api.put<EmailDefault>(`${this.baseUrl}/email/default`, emailDefault);
    return response.data;
  },

  /**
   * 删除默认接收人
   * @param defaultId 默认ID
   * @returns Promise<ResultDomain<boolean>>
   */
  async deleteEmailDefault(defaultId: string): Promise<ResultDomain<boolean>> {
    const response = await api.delete<boolean>(`${this.baseUrl}/email/default/${defaultId}`);
    return response.data;
  },

  /**
   * 根据defaultId查询
   * @param defaultId 默认ID
   * @returns Promise<ResultDomain<EmailDefault>>
   */
  async getEmailDefaultById(defaultId: string): Promise<ResultDomain<EmailDefault>> {
    const response = await api.get<EmailDefault>(`${this.baseUrl}/email/default/${defaultId}`);
    return response.data;
  },

  /**
   * 根据metaId查询默认接收人
   * @param metaId 元数据ID
   * @returns Promise<ResultDomain<EmailDefault>>
   */
  async getEmailDefaultByMetaId(metaId: string): Promise<ResultDomain<EmailDefault>> {
    const response = await api.get<EmailDefault>(`${this.baseUrl}/email/default/meta/${metaId}`);
    return response.data;
  },

  // ==================== 邮件接收人管理 ====================

  /**
   * 创建邮件接收人
   * @param recipient 邮件接收人
   * @returns Promise<ResultDomain<EmailRecipient>>
   */
  async createEmailRecipient(recipient: EmailRecipient): Promise<ResultDomain<EmailRecipient>> {
    const response = await api.post<EmailRecipient>(`${this.baseUrl}/email/recipient`, recipient);
    return response.data;
  },

  /**
   * 批量创建邮件接收人
   * @param recipients 邮件接收人列表
   * @returns Promise<ResultDomain<boolean>>
   */
  async batchCreateEmailRecipient(recipients: EmailRecipient[]): Promise<ResultDomain<boolean>> {
    const response = await api.post<boolean>(`${this.baseUrl}/email/recipient/batch`, recipients);
    return response.data;
  },

  /**
   * 更新邮件接收人
   * @param recipient 邮件接收人
   * @returns Promise<ResultDomain<EmailRecipient>>
   */
  async updateEmailRecipient(recipient: EmailRecipient): Promise<ResultDomain<EmailRecipient>> {
    const response = await api.put<EmailRecipient>(`${this.baseUrl}/email/recipient`, recipient);
    return response.data;
  },

  /**
   * 删除邮件接收人
   * @param recipientId 接收人ID
   * @returns Promise<ResultDomain<boolean>>
   */
  async deleteEmailRecipient(recipientId: string): Promise<ResultDomain<boolean>> {
    const response = await api.delete<boolean>(`${this.baseUrl}/email/recipient/${recipientId}`);
    return response.data;
  },

  /**
   * 根据ID查询接收人
   * @param recipientId 接收人ID
   * @returns Promise<ResultDomain<EmailRecipient>>
   */
  async getEmailRecipientById(recipientId: string): Promise<ResultDomain<EmailRecipient>> {
    const response = await api.get<EmailRecipient>(`${this.baseUrl}/email/recipient/${recipientId}`);
    return response.data;
  },

  /**
   * 根据default_id查询接收人列表
   * @param defaultId 默认ID
   * @returns Promise<ResultDomain<EmailRecipient>>
   */
  async getRecipientsByDefaultId(defaultId: string): Promise<ResultDomain<EmailRecipient>> {
    const response = await api.get<EmailRecipient>(`${this.baseUrl}/email/recipient/default/${defaultId}`);
    return response.data;
  },

  /**
   * 根据任务ID查询接收人列表
   * @param taskId 任务ID
   * @returns Promise<ResultDomain<EmailRecipient>>
   */
  async getRecipientsByTaskId(taskId: string): Promise<ResultDomain<EmailRecipient>> {
    const response = await api.get<EmailRecipient>(`${this.baseUrl}/email/recipient/task/${taskId}`);
    return response.data;
  },

  /**
   * 查询所有启用的接收人
   * @returns Promise<ResultDomain<EmailRecipient>>
   */
  async getAllEnabledRecipients(): Promise<ResultDomain<EmailRecipient>> {
    const response = await api.get<EmailRecipient>(`${this.baseUrl}/email/recipient/enabled`);
    return response.data;
  },

  /**
   * 分页查询邮件接收人
   * @param filter 过滤条件
   * @param pageParam 分页参数
   * @returns Promise<ResultDomain<EmailRecipient>>
   */
  async getEmailRecipientPage(filter?: Partial<EmailRecipient>, pageParam?: PageParam): Promise<ResultDomain<EmailRecipient>> {
    const response = await api.post<EmailRecipient>(`${this.baseUrl}/email/recipient/page`, {
      filter,
      pageParam: {
        pageNumber: pageParam?.pageNumber || 1,
        pageSize: pageParam?.pageSize || 10
      }
    });
    return response.data;
  },

  /**
   * 删除default_id的所有接收人
   * @param defaultId 默认ID
   * @returns Promise<ResultDomain<boolean>>
   */
  async deleteRecipientsByDefaultId(defaultId: string): Promise<ResultDomain<boolean>> {
    const response = await api.delete<boolean>(`${this.baseUrl}/email/recipient/default/${defaultId}`);
    return response.data;
  },

  /**
   * 删除任务的所有接收人
   * @param taskId 任务ID
   * @returns Promise<ResultDomain<boolean>>
   */
  async deleteRecipientsByTaskId(taskId: string): Promise<ResultDomain<boolean>> {
    const response = await api.delete<boolean>(`${this.baseUrl}/email/recipient/task/${taskId}`);
    return response.data;
  },
};

