package com.sinata.appointment.controller; import cn.dev33.satoken.annotation.SaCheckPermission; import com.sinata.appointment.common.Result; import com.sinata.appointment.common.ResultUtil; import com.sinata.appointment.dto.ExportTaskStatusVo; import com.sinata.appointment.service.ExportApplicationService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @Tag(name = "导出") @RestController @RequestMapping("/api/exports") @RequiredArgsConstructor public class ExportController { private final ExportApplicationService exportApplicationService; @Operation(summary = "异步导出任务入队") @PostMapping("/enqueue") @SaCheckPermission("exports:enqueue") public Result> enqueue(@RequestBody Map body) { String type = body.get("type") != null ? body.get("type").toString() : "appointment"; @SuppressWarnings("unchecked") Map criteria = body.get("criteria") instanceof Map ? (Map) body.get("criteria") : Map.of(); String taskId = exportApplicationService.enqueueExport(type, criteria); Map res = new HashMap<>(); res.put("taskId", taskId); return ResultUtil.data(res); } @Operation(summary = "查询导出任务状态") @GetMapping("/{taskId}") @SaCheckPermission("exports:enqueue") public Result status(@PathVariable String taskId) { ExportTaskStatusVo status = exportApplicationService.getTaskStatus(taskId); if (status == null) { return ResultUtil.error(404, "导出任务不存在"); } return ResultUtil.data(status); } @Operation(summary = "下载导出文件") @GetMapping("/{taskId}/download") @SaCheckPermission("exports:enqueue") public ResponseEntity download(@PathVariable String taskId) throws IOException { Path filePath = exportApplicationService.getExportFilePath(taskId); if (filePath == null) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new byte[0]); } return ResponseEntity.ok() .contentType( MediaType.parseMediaType( "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) .header( HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filePath.getFileName() + "\"") .body(Files.readAllBytes(filePath)); } }