ArticleGenerationTaskController.java 28.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
package com.aigeo.article.controller;

import com.aigeo.article.entity.ArticleGenerationTask;
import com.aigeo.article.service.ArticleGenerationService;
import com.aigeo.common.enums.TaskStatus;
import com.aigeo.common.result.Result;
import com.aigeo.common.result.ResultCode;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 文章生成任务管理控制器
 * 
 * @author AIGEO Team
 * @since 1.0.0
 */
@Tag(name = "文章生成任务管理", description = "AI文章生成任务管理接口,支持任务的创建、查询、更新和删除操作")
@RestController
@RequestMapping("/api/article-tasks")
@RequiredArgsConstructor
@Slf4j
public class ArticleGenerationTaskController {

    private final ArticleGenerationService articleGenerationService;

    @Operation(
        summary = "分页查询文章生成任务列表", 
        description = "支持按任务状态、用户、公司等条件分页查询文章生成任务列表,默认按创建时间倒序排列"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/list")
    public Result<Page<ArticleGenerationTask>> listTasks(
        @Parameter(description = "页码,从0开始", example = "0") 
        @RequestParam(defaultValue = "0") int page,
        
        @Parameter(description = "页大小,默认10条", example = "10") 
        @RequestParam(defaultValue = "10") int size,
        
        @Parameter(description = "公司ID(可选)") 
        @RequestParam(required = false) Integer companyId,
        
        @Parameter(description = "用户ID(可选)") 
        @RequestParam(required = false) Integer userId,
        
        @Parameter(description = "任务状态") 
        @RequestParam(required = false) TaskStatus status,
        
        @Parameter(description = "文章主题(模糊查询)") 
        @RequestParam(required = false) String articleTheme,
        
        @Parameter(description = "开始时间(格式:yyyy-MM-ddTHH:mm:ss)") 
        @RequestParam(required = false) String startTime,
        
        @Parameter(description = "结束时间(格式:yyyy-MM-ddTHH:mm:ss)") 
        @RequestParam(required = false) String endTime
    ) {
        try {
            Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
            LocalDateTime start = startTime != null ? LocalDateTime.parse(startTime) : null;
            LocalDateTime end = endTime != null ? LocalDateTime.parse(endTime) : null;
            
            Page<ArticleGenerationTask> tasks = articleGenerationService.searchTasks(
                companyId, userId, status, articleTheme, start, end, pageable
            );
            return Result.success("查询成功", tasks);
        } catch (Exception e) {
            log.error("分页查询文章生成任务列表失败", e);
            return Result.error("查询失败");
        }
    }

    @Operation(
        summary = "获取所有文章生成任务(简化版)", 
        description = "获取所有文章生成任务的基本信息,用于下拉选择等场景"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping
    public Result<List<ArticleGenerationTask>> getAllTasks() {
        try {
            List<ArticleGenerationTask> tasks = articleGenerationService.getAllTasks();
            return Result.success("查询成功", tasks);
        } catch (Exception e) {
            log.error("获取所有文章生成任务失败", e);
            return Result.error("查询失败");
        }
    }

    @Operation(
        summary = "根据ID查询文章生成任务详情", 
        description = "通过任务ID获取文章生成任务的详细信息"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "404", description = "任务不存在"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/{id}")
    public Result<ArticleGenerationTask> getTaskById(
        @Parameter(description = "任务ID", required = true, example = "1") 
        @PathVariable @NotNull Integer id
    ) {
        try {
            return articleGenerationService.getTaskById(id)
                .map(task -> Result.success("查询成功", task))
                .orElse(Result.error(ResultCode.DATA_NOT_FOUND, "任务不存在"));
        } catch (Exception e) {
            log.error("根据ID查询文章生成任务详情失败, id: {}", id, e);
            return Result.error("查询失败");
        }
    }

    @Operation(
        summary = "根据公司ID查询文章生成任务", 
        description = "获取指定公司下的所有文章生成任务"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "404", description = "公司不存在"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/company/{companyId}")
    public Result<List<ArticleGenerationTask>> getTasksByCompanyId(
        @Parameter(description = "公司ID", required = true, example = "1") 
        @PathVariable @NotNull Integer companyId
    ) {
        try {
            List<ArticleGenerationTask> tasks = articleGenerationService.getTasksByCompanyId(companyId);
            return Result.success("查询成功", tasks);
        } catch (Exception e) {
            log.error("根据公司ID查询文章生成任务失败, companyId: {}", companyId, e);
            return Result.error("查询失败");
        }
    }

    @Operation(
        summary = "根据用户ID查询文章生成任务", 
        description = "获取指定用户创建的所有文章生成任务"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "404", description = "用户不存在"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/user/{userId}")
    public Result<List<ArticleGenerationTask>> getTasksByUserId(
        @Parameter(description = "用户ID", required = true, example = "1") 
        @PathVariable @NotNull Integer userId
    ) {
        try {
            List<ArticleGenerationTask> tasks = articleGenerationService.getTasksByUserId(userId);
            return Result.success("查询成功", tasks);
        } catch (Exception e) {
            log.error("根据用户ID查询文章生成任务失败, userId: {}", userId, e);
            return Result.error("查询失败");
        }
    }

    @Operation(
        summary = "根据任务状态查询文章生成任务", 
        description = "获取指定状态的所有文章生成任务"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/status/{status}")
    public Result<List<ArticleGenerationTask>> getTasksByStatus(
        @Parameter(description = "任务状态", required = true) 
        @PathVariable @NotNull TaskStatus status
    ) {
        try {
            List<ArticleGenerationTask> tasks = articleGenerationService.getTasksByStatus(status);
            return Result.success("查询成功", tasks);
        } catch (Exception e) {
            log.error("根据任务状态查询文章生成任务失败, status: {}", status, e);
            return Result.error("查询失败");
        }
    }

    @Operation(
        summary = "获取进行中的任务", 
        description = "获取所有状态为进行中的文章生成任务"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/running")
    public Result<List<ArticleGenerationTask>> getRunningTasks(
        @Parameter(description = "公司ID(可选)") 
        @RequestParam(required = false) Integer companyId
    ) {
        try {
            List<ArticleGenerationTask> tasks = articleGenerationService.getRunningTasks(companyId);
            return Result.success("查询成功", tasks);
        } catch (Exception e) {
            log.error("获取进行中的任务失败", e);
            return Result.error("查询失败");
        }
    }

    @Operation(
        summary = "获取最近完成的任务", 
        description = "获取最近完成的文章生成任务列表"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/recent-completed")
    public Result<List<ArticleGenerationTask>> getRecentCompletedTasks(
        @Parameter(description = "公司ID(可选)") 
        @RequestParam(required = false) Integer companyId,
        
        @Parameter(description = "返回数量", example = "10") 
        @RequestParam(defaultValue = "10") int limit
    ) {
        try {
            List<ArticleGenerationTask> tasks = articleGenerationService.getRecentCompletedTasks(companyId, limit);
            return Result.success("查询成功", tasks);
        } catch (Exception e) {
            log.error("获取最近完成的任务失败", e);
            return Result.error("查询失败");
        }
    }

    @Operation(
        summary = "创建新的文章生成任务", 
        description = "创建一个新的文章生成任务,包含生成参数和配置"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "创建成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "429", description = "任务队列已满"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PostMapping
    public Result<ArticleGenerationTask> createTask(
        @Parameter(description = "文章生成任务信息", required = true) 
        @Valid @RequestBody ArticleGenerationTask task
    ) {
        try {
            // 检查任务队列是否已满
            if (articleGenerationService.isTaskQueueFull(task.getCompanyId())) {
                return Result.error(ResultCode.TOO_MANY_REQUESTS, "任务队列已满,请稍后再试");
            }
            
            ArticleGenerationTask savedTask = articleGenerationService.saveTask(task);
            log.info("成功创建文章生成任务: {} (用户ID: {})", savedTask.getArticleTheme(), savedTask.getUserId());
            return Result.success("创建成功", savedTask);
        } catch (Exception e) {
            log.error("创建文章生成任务失败", e);
            return Result.error("创建失败");
        }
    }

    @Operation(
        summary = "批量创建文章生成任务", 
        description = "批量创建多个文章生成任务"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "批量创建成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "429", description = "任务数量超限"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PostMapping("/batch")
    public Result<List<ArticleGenerationTask>> batchCreateTasks(
        @Parameter(description = "文章生成任务列表", required = true) 
        @Valid @RequestBody List<ArticleGenerationTask> tasks
    ) {
        try {
            if (tasks.size() > 50) {
                return Result.error(ResultCode.BAD_REQUEST, "单次批量创建任务数量不能超过50个");
            }
            
            List<ArticleGenerationTask> savedTasks = articleGenerationService.batchSaveTasks(tasks);
            log.info("成功批量创建文章生成任务,数量: {}", savedTasks.size());
            return Result.success("批量创建成功", savedTasks);
        } catch (Exception e) {
            log.error("批量创建文章生成任务失败", e);
            return Result.error("批量创建失败");
        }
    }

    @Operation(
        summary = "更新文章生成任务", 
        description = "根据ID更新文章生成任务的详细信息"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "更新成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "404", description = "任务不存在"),
        @ApiResponse(responseCode = "409", description = "任务状态不允许更新"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PutMapping("/{id}")
    public Result<ArticleGenerationTask> updateTask(
        @Parameter(description = "任务ID", required = true, example = "1") 
        @PathVariable @NotNull Integer id,
        
        @Parameter(description = "更新的任务信息", required = true) 
        @Valid @RequestBody ArticleGenerationTask taskDetails
    ) {
        try {
            return articleGenerationService.getTaskById(id)
                .map(existingTask -> {
                    // 检查任务状态是否允许更新
                    if (existingTask.getStatus() == TaskStatus.COMPLETED) {
                        return Result.<ArticleGenerationTask>error(ResultCode.CONFLICT, "已完成的任务不允许更新");
                    }
                    
                    // 更新字段
                    existingTask.setArticleTheme(taskDetails.getArticleTheme());
                    existingTask.setStatus(taskDetails.getStatus());
                    existingTask.setProgress(taskDetails.getProgress());
                    
                    ArticleGenerationTask savedTask = articleGenerationService.saveTask(existingTask);
                    log.info("成功更新文章生成任务: {}", savedTask.getArticleTheme());
                    return Result.success("更新成功", savedTask);
                })
                .orElse(Result.error(ResultCode.DATA_NOT_FOUND, "任务不存在"));
        } catch (Exception e) {
            log.error("更新文章生成任务失败, id: {}", id, e);
            return Result.error("更新失败");
        }
    }

    @Operation(
        summary = "启动文章生成任务", 
        description = "启动指定的文章生成任务"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "启动成功"),
        @ApiResponse(responseCode = "404", description = "任务不存在"),
        @ApiResponse(responseCode = "409", description = "任务状态不允许启动"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PostMapping("/{id}/start")
    public Result<String> startTask(
        @Parameter(description = "任务ID", required = true, example = "1") 
        @PathVariable @NotNull Integer id
    ) {
        try {
            if (!articleGenerationService.existsById(id)) {
                return Result.error(ResultCode.DATA_NOT_FOUND, "任务不存在");
            }
            
            boolean started = articleGenerationService.startTask(id);
            if (started) {
                log.info("成功启动文章生成任务, id: {}", id);
                return Result.success("任务启动成功");
            } else {
                return Result.error(ResultCode.CONFLICT, "任务状态不允许启动");
            }
        } catch (Exception e) {
            log.error("启动文章生成任务失败, id: {}", id, e);
            return Result.error("启动失败");
        }
    }

    @Operation(
        summary = "暂停文章生成任务", 
        description = "暂停正在运行的文章生成任务"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "暂停成功"),
        @ApiResponse(responseCode = "404", description = "任务不存在"),
        @ApiResponse(responseCode = "409", description = "任务状态不允许暂停"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PostMapping("/{id}/pause")
    public Result<String> pauseTask(
        @Parameter(description = "任务ID", required = true, example = "1") 
        @PathVariable @NotNull Integer id
    ) {
        try {
            if (!articleGenerationService.existsById(id)) {
                return Result.error(ResultCode.DATA_NOT_FOUND, "任务不存在");
            }
            
            boolean paused = articleGenerationService.pauseTask(id);
            if (paused) {
                log.info("成功暂停文章生成任务, id: {}", id);
                return Result.success("任务暂停成功");
            } else {
                return Result.error(ResultCode.CONFLICT, "任务状态不允许暂停");
            }
        } catch (Exception e) {
            log.error("暂停文章生成任务失败, id: {}", id, e);
            return Result.error("暂停失败");
        }
    }

    @Operation(
        summary = "取消文章生成任务", 
        description = "取消指定的文章生成任务"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "取消成功"),
        @ApiResponse(responseCode = "404", description = "任务不存在"),
        @ApiResponse(responseCode = "409", description = "任务状态不允许取消"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PostMapping("/{id}/cancel")
    public Result<String> cancelTask(
        @Parameter(description = "任务ID", required = true, example = "1") 
        @PathVariable @NotNull Integer id
    ) {
        try {
            if (!articleGenerationService.existsById(id)) {
                return Result.error(ResultCode.DATA_NOT_FOUND, "任务不存在");
            }
            
            boolean cancelled = articleGenerationService.cancelTask(id);
            if (cancelled) {
                log.info("成功取消文章生成任务, id: {}", id);
                return Result.success("任务取消成功");
            } else {
                return Result.error(ResultCode.CONFLICT, "任务状态不允许取消");
            }
        } catch (Exception e) {
            log.error("取消文章生成任务失败, id: {}", id, e);
            return Result.error("取消失败");
        }
    }

    @Operation(
        summary = "重试失败的文章生成任务", 
        description = "重新启动失败的文章生成任务"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "重试成功"),
        @ApiResponse(responseCode = "404", description = "任务不存在"),
        @ApiResponse(responseCode = "409", description = "任务状态不允许重试"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PostMapping("/{id}/retry")
    public Result<String> retryTask(
        @Parameter(description = "任务ID", required = true, example = "1") 
        @PathVariable @NotNull Integer id
    ) {
        try {
            if (!articleGenerationService.existsById(id)) {
                return Result.error(ResultCode.DATA_NOT_FOUND, "任务不存在");
            }
            
            boolean retried = articleGenerationService.retryTask(id);
            if (retried) {
                log.info("成功重试文章生成任务, id: {}", id);
                return Result.success("任务重试成功");
            } else {
                return Result.error(ResultCode.CONFLICT, "任务状态不允许重试");
            }
        } catch (Exception e) {
            log.error("重试文章生成任务失败, id: {}", id, e);
            return Result.error("重试失败");
        }
    }

    @Operation(
        summary = "删除文章生成任务", 
        description = "根据ID删除文章生成任务记录(软删除)"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "删除成功"),
        @ApiResponse(responseCode = "404", description = "任务不存在"),
        @ApiResponse(responseCode = "409", description = "任务正在运行,无法删除"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @DeleteMapping("/{id}")
    public Result<String> deleteTask(
        @Parameter(description = "任务ID", required = true, example = "1") 
        @PathVariable @NotNull Integer id
    ) {
        try {
            if (!articleGenerationService.existsById(id)) {
                return Result.error(ResultCode.DATA_NOT_FOUND, "任务不存在");
            }
            
            // 检查任务是否正在运行
            if (articleGenerationService.isTaskRunning(id)) {
                return Result.error(ResultCode.CONFLICT, "任务正在运行,无法删除");
            }
            
            articleGenerationService.deleteTask(id);
            log.info("成功删除文章生成任务, id: {}", id);
            return Result.success("删除成功");
        } catch (Exception e) {
            log.error("删除文章生成任务失败, id: {}", id, e);
            return Result.error("删除失败");
        }
    }

    @Operation(
        summary = "获取任务执行日志", 
        description = "获取文章生成任务的执行日志信息"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "404", description = "任务不存在"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/{id}/logs")
    public Result<List<String>> getTaskLogs(
        @Parameter(description = "任务ID", required = true, example = "1") 
        @PathVariable @NotNull Integer id,
        
        @Parameter(description = "日志级别(INFO/WARN/ERROR)") 
        @RequestParam(required = false) String level,
        
        @Parameter(description = "最大返回行数", example = "100") 
        @RequestParam(defaultValue = "100") int limit
    ) {
        try {
            if (!articleGenerationService.existsById(id)) {
                return Result.error(ResultCode.DATA_NOT_FOUND, "任务不存在");
            }
            
            List<String> logs = articleGenerationService.getTaskLogs(id, level, limit);
            return Result.success("查询成功", logs);
        } catch (Exception e) {
            log.error("获取任务执行日志失败, id: {}", id, e);
            return Result.error("查询失败");
        }
    }

    @Operation(
        summary = "获取任务统计信息", 
        description = "获取文章生成任务相关的统计数据"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "统计成功"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/statistics")
    public Result<TaskStatistics> getTaskStatistics(
        @Parameter(description = "公司ID(可选)") 
        @RequestParam(required = false) Integer companyId,
        
        @Parameter(description = "统计时间范围(天数)", example = "30") 
        @RequestParam(defaultValue = "30") int days
    ) {
        try {
            ArticleGenerationService.TaskStatistics serviceStats = articleGenerationService.getTaskStatistics(companyId, days);
            TaskStatistics statistics = new TaskStatistics(
                serviceStats.getTotalTasks(),
                serviceStats.getPendingTasks(),
                serviceStats.getRunningTasks(),
                serviceStats.getCompletedTasks(),
                serviceStats.getFailedTasks(),
                serviceStats.getSuccessRate(),
                serviceStats.getAverageExecutionTime()
            );
            return Result.success("统计成功", statistics);
        } catch (Exception e) {
            log.error("获取任务统计信息失败", e);
            return Result.error("统计失败");
        }
    }

    @Operation(
        summary = "清理已完成的任务", 
        description = "清理指定天数前完成的文章生成任务"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "清理成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @DeleteMapping("/cleanup")
    public Result<String> cleanupCompletedTasks(
        @Parameter(description = "保留天数", required = true, example = "30") 
        @RequestParam @NotNull Integer retentionDays
    ) {
        try {
            if (retentionDays < 1) {
                return Result.error(ResultCode.BAD_REQUEST, "保留天数必须大于0");
            }
            
            int cleanedCount = articleGenerationService.cleanupCompletedTasks(retentionDays);
            log.info("清理已完成的任务成功,清理数量: {}", cleanedCount);
            return Result.success(String.format("成功清理 %d 个已完成的任务", cleanedCount));
        } catch (Exception e) {
            log.error("清理已完成的任务失败", e);
            return Result.error("清理失败");
        }
    }

    /**
     * 任务统计信息DTO
     */
    public static class TaskStatistics {
        private long totalTasks;
        private long pendingTasks;
        private long runningTasks;
        private long completedTasks;
        private long failedTasks;
        private double successRate;
        private double averageExecutionTime;
        
        // constructors, getters and setters
        public TaskStatistics(long totalTasks, long pendingTasks, long runningTasks, 
                            long completedTasks, long failedTasks, double successRate, 
                            double averageExecutionTime) {
            this.totalTasks = totalTasks;
            this.pendingTasks = pendingTasks;
            this.runningTasks = runningTasks;
            this.completedTasks = completedTasks;
            this.failedTasks = failedTasks;
            this.successRate = successRate;
            this.averageExecutionTime = averageExecutionTime;
        }
        
        // getters and setters
        public long getTotalTasks() { return totalTasks; }
        public void setTotalTasks(long totalTasks) { this.totalTasks = totalTasks; }
        
        public long getPendingTasks() { return pendingTasks; }
        public void setPendingTasks(long pendingTasks) { this.pendingTasks = pendingTasks; }
        
        public long getRunningTasks() { return runningTasks; }
        public void setRunningTasks(long runningTasks) { this.runningTasks = runningTasks; }
        
        public long getCompletedTasks() { return completedTasks; }
        public void setCompletedTasks(long completedTasks) { this.completedTasks = completedTasks; }
        
        public long getFailedTasks() { return failedTasks; }
        public void setFailedTasks(long failedTasks) { this.failedTasks = failedTasks; }
        
        public double getSuccessRate() { return successRate; }
        public void setSuccessRate(double successRate) { this.successRate = successRate; }
        
        public double getAverageExecutionTime() { return averageExecutionTime; }
        public void setAverageExecutionTime(double averageExecutionTime) { this.averageExecutionTime = averageExecutionTime; }
    }
}