module.exports = class extends think.Model {
  get tableName() {
    return 'export_task';
  }

  /**
   * 生成任务编号: EX + 时间戳 + 随机数
   */
  generateTaskNo() {
    const ts = String(Date.now()).slice(-10);
    const rand = String(Math.floor(Math.random() * 1000)).padStart(3, '0');
    return 'EX' + ts + rand;
  }

  /**
   * 获取任务列表（分页）
   */
  async getList({ page = 1, pageSize = 10, status, createBy }) {
    const where = { is_deleted: 0 };
    if (status !== undefined && status !== '') {
      where.status = parseInt(status, 10);
    }
    if (createBy) {
      where.create_by = createBy;
    }
    return this.where(where)
      .order('id DESC')
      .page(page, pageSize)
      .countSelect();
  }

  /**
   * 获取待处理的任务（用于后台执行）
   */
  async getPendingTask() {
    return this.where({ status: 0, is_deleted: 0 })
      .order('id ASC')
      .find();
  }

  /**
   * 恢复中断的任务（processing 超过30分钟的标记为失败）
   */
  async recoverStuckTasks() {
    const thirtyMinAgo = think.datetime(new Date(Date.now() - 30 * 60 * 1000));
    const stuck = await this.where({
      status: 1,
      started_at: ['<', thirtyMinAgo],
      is_deleted: 0
    }).select();
    if (stuck.length) {
      await this.where({
        status: 1,
        started_at: ['<', thirtyMinAgo],
        is_deleted: 0
      }).update({
        status: 3,
        error_log: '任务超时，服务重启后自动标记为失败'
      });
      think.logger.warn(`[ExportTask] 恢复了 ${stuck.length} 个中断任务`);
    }
    return stuck.length;
  }
};
