5.13

package com.example.baoli.controller;

import com.example.baoli.entity.SparePart;
import com.example.baoli.service.SparePartService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/spare-parts")
public class SparePartController {

@Autowired
private SparePartService sparePartService;

@Autowired
private ObjectMapper objectMapper;

@GetMapping
public ResponseEntity<List<SparePart>> getAllSpareParts() {
List<SparePart> spareParts = sparePartService.getAllSpareParts();
return ResponseEntity.ok(spareParts);
}

@GetMapping("/{id}")
public ResponseEntity<SparePart> getSparePartById(@PathVariable Long id) {
Optional<SparePart> sparePart = sparePartService.getSparePartById(id);
return sparePart.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}

@PostMapping
public ResponseEntity<SparePart> createSparePart(@RequestBody SparePart sparePart) {
SparePart savedSparePart = sparePartService.saveSparePart(sparePart);
return ResponseEntity.ok(savedSparePart);
}

@PutMapping("/{id}")
public ResponseEntity<SparePart> updateSparePart(@PathVariable Long id, @RequestBody SparePart sparePart) {
sparePart.setId(id);
SparePart updatedSparePart = sparePartService.saveSparePart(sparePart);
return ResponseEntity.ok(updatedSparePart);
}

@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteSparePart(@PathVariable Long id) {
sparePartService.deleteSparePartById(id);
return ResponseEntity.ok().build();
}

@GetMapping("/search")
public ResponseEntity<List<SparePart>> searchSpareParts(@RequestParam String keyword) {
List<SparePart> spareParts = sparePartService.searchSpareParts(keyword);
return ResponseEntity.ok(spareParts);
}

@GetMapping("/status/{status}")
public ResponseEntity<List<SparePart>> getSparePartsByStatus(@PathVariable String status) {
List<SparePart> spareParts = sparePartService.getSparePartsByStatus(status);
return ResponseEntity.ok(spareParts);
}

@GetMapping("/low-stock")
public ResponseEntity<List<SparePart>> getLowStockParts() {
List<SparePart> spareParts = sparePartService.getLowStockParts();
return ResponseEntity.ok(spareParts);
}

/**
* 获取备件名称列表(用于下拉选择)
*/
@GetMapping("/names")
public ResponseEntity<List<String>> getSparePartNames() {
List<String> names = sparePartService.getDistinctPartNames();
return ResponseEntity.ok(names);
}

/**
* 根据备件名称获取型号列表
*/
@GetMapping("/models")
public ResponseEntity<List<String>> getSparePartModels(@RequestParam String partName) {
List<String> models = sparePartService.getModelsByPartName(partName);
return ResponseEntity.ok(models);
}

/**
* 获取备件详细信息(名称+型号)
*/
@GetMapping("/details")
public ResponseEntity<List<Map<String, Object>>> getSparePartDetails() {
List<Map<String, Object>> details = sparePartService.getSparePartDetails();
return ResponseEntity.ok(details);
}

/**
* 批量导出备件数据为JSON
*/
@GetMapping("/export")
public ResponseEntity<byte[]> exportData(@RequestParam(required = false) String status,
@RequestParam(required = false) String location) {
try {
List<SparePart> spareParts;
if (status != null) {
spareParts = sparePartService.getSparePartsByStatus(status);
} else if (location != null) {
spareParts = sparePartService.getSparePartsByLocation(location);
} else {
spareParts = sparePartService.getAllSpareParts();
}

String jsonData = objectMapper.writeValueAsString(spareParts);
byte[] data = jsonData.getBytes("UTF-8");

String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
String filename = "spare_parts_" + timestamp + ".json";

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setContentDispositionFormData("attachment", filename);
headers.setContentLength(data.length);

return ResponseEntity.ok()
.headers(headers)
.body(data);
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}

/**
* 模版导入功能
*/
@PostMapping("/import")
public ResponseEntity<Map<String, Object>> importData(@RequestParam("file") MultipartFile file) {
try {
if (file.isEmpty()) {
return ResponseEntity.badRequest().body(Map.of("success", false, "message", "文件为空"));
}

String content = new String(file.getBytes(), "UTF-8");
List<SparePart> spareParts = objectMapper.readValue(content,
objectMapper.getTypeFactory().constructCollectionType(List.class, SparePart.class));

int successCount = 0;
int errorCount = 0;
StringBuilder errorMessages = new StringBuilder();

for (SparePart sparePart : spareParts) {
try {
// 清除ID,让系统重新生成
sparePart.setId(null);
sparePart.setCreatedAt(LocalDateTime.now());
sparePart.setUpdatedAt(LocalDateTime.now());
sparePartService.saveSparePart(sparePart);
successCount++;
} catch (Exception e) {
errorCount++;
errorMessages.append("备件导入失败: ").append(e.getMessage()).append("; ");
}
}

Map<String, Object> result = Map.of(
"success", true,
"message", "导入完成",
"successCount", successCount,
"errorCount", errorCount,
"errorMessages", errorMessages.toString()
);

return ResponseEntity.ok(result);
} catch (IOException e) {
return ResponseEntity.badRequest().body(Map.of("success", false, "message", "文件解析失败: " + e.getMessage()));
} catch (Exception e) {
return ResponseEntity.badRequest().body(Map.of("success", false, "message", "导入失败: " + e.getMessage()));
}
}

@PutMapping("/{id}/quantity")
public ResponseEntity<SparePart> updateQuantity(@PathVariable Long id, @RequestParam Integer quantity) {
SparePart updatedSparePart = sparePartService.updateSparePartQuantity(id, quantity);
if (updatedSparePart != null) {
return ResponseEntity.ok(updatedSparePart);
}
return ResponseEntity.notFound().build();
}

@PutMapping("/{id}/status")
public ResponseEntity<SparePart> updateStatus(@PathVariable Long id, @RequestParam String status) {
SparePart updatedSparePart = sparePartService.updateSparePartStatus(id, status);
if (updatedSparePart != null) {
return ResponseEntity.ok(updatedSparePart);
}
return ResponseEntity.notFound().build();
}
}

 

posted @ 2025-05-13 22:59  混沌武士丞  阅读(6)  评论(0)    收藏  举报