BatchCancelTaskAction.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace App\Module\Cleanup\AdminControllers\Actions;
  3. use App\Module\Cleanup\Services\CleanupService;
  4. use Dcat\Admin\Grid\BatchAction;
  5. use Dcat\Admin\Actions\Response;
  6. use Illuminate\Http\Request;
  7. /**
  8. * 批量取消任务Action
  9. *
  10. * 用于批量取消清理任务
  11. */
  12. class BatchCancelTaskAction extends BatchAction
  13. {
  14. /**
  15. * 按钮标题
  16. */
  17. protected $title = '批量取消';
  18. /**
  19. * 处理请求
  20. */
  21. public function handle(Request $request)
  22. {
  23. try {
  24. // 获取选中的ID
  25. $ids = $this->getKey();
  26. if (empty($ids)) {
  27. return $this->response()->error('请选择要取消的任务');
  28. }
  29. $reason = $request->input('reason', '批量取消操作');
  30. $successCount = 0;
  31. $failCount = 0;
  32. $errors = [];
  33. foreach ($ids as $taskId) {
  34. try {
  35. $result = CleanupService::cancelTask($taskId, $reason);
  36. if ($result['success']) {
  37. $successCount++;
  38. } else {
  39. $failCount++;
  40. $errors[] = "任务 {$taskId}: " . $result['message'];
  41. }
  42. } catch (\Exception $e) {
  43. $failCount++;
  44. $errors[] = "任务 {$taskId}: " . $e->getMessage();
  45. }
  46. }
  47. $message = "成功取消 {$successCount} 个任务";
  48. if ($failCount > 0) {
  49. $message .= ",失败 {$failCount} 个";
  50. }
  51. $response = $this->response()->success($message)->refresh();
  52. if (!empty($errors)) {
  53. $errorDetail = implode('<br>', array_slice($errors, 0, 5));
  54. if (count($errors) > 5) {
  55. $errorDetail .= '<br>...还有 ' . (count($errors) - 5) . ' 个错误';
  56. }
  57. $response->detail($errorDetail);
  58. }
  59. return $response;
  60. } catch (\Exception $e) {
  61. return $this->response()
  62. ->error('批量取消失败:' . $e->getMessage());
  63. }
  64. }
  65. /**
  66. * 确认对话框
  67. */
  68. public function confirm()
  69. {
  70. return [
  71. '确认批量取消任务?',
  72. '⚠️ 任务取消后无法恢复,已完成的清理操作不会回滚!',
  73. [
  74. 'reason' => [
  75. 'type' => 'textarea',
  76. 'label' => '取消原因',
  77. 'placeholder' => '请输入取消原因(可选)',
  78. 'rows' => 3,
  79. ]
  80. ]
  81. ];
  82. }
  83. }