package com.erp.file.controller;

import com.erp.common.core.model.ApiResponse;
import com.erp.file.dto.*;
import com.erp.file.entity.FileEntity;
import com.erp.file.service.FileService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.InputStreamResource;
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.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * 文件控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/files")
@RequiredArgsConstructor
public class FileController {
    
    private final FileService fileService;
    
    // ==================== 查询操作 ====================
    
    /**
     * 文件列表
     */
    @GetMapping
    public ApiResponse<PagedResponse<FileResponse>> listFiles(FileQueryRequest request) {
        PagedResponse<FileResponse> result = fileService.listFiles(request);
        return ApiResponse.success(result);
    }
    
    /**
     * 文件详情
     */
    @GetMapping("/{id}")
    public ApiResponse<FileResponse> getFile(@PathVariable Long id) {
        FileResponse result = fileService.getFileById(id);
        return ApiResponse.success(result);
    }
    
    /**
     * 获取文件统计
     */
    @GetMapping("/statistics")
    public ApiResponse<FileStatisticsResponse> getStatistics(@RequestParam(required = false) Long userId) {
        FileStatisticsResponse result = fileService.getStatistics(userId);
        return ApiResponse.success(result);
    }
    
    /**
     * 获取模块列表
     */
    @GetMapping("/modules")
    public ApiResponse<List<String>> getModules() {
        List<String> result = fileService.getModules();
        return ApiResponse.success(result);
    }
    
    // ==================== 上传操作 ====================
    
    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public ApiResponse<FileResponse> upload(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "module", defaultValue = "default") String module,
            @RequestParam(value = "purpose", defaultValue = "upload") String purpose,
            @RequestParam(required = false) String description,
            @RequestHeader(value = "X-User-Id", required = false) Long userId) {
        
        // TODO: 从Security Context获取真实用户ID
        if (userId == null) {
            userId = 1L; // 默认用户，，后续从Token解析
        }
        
        FileResponse result = fileService.uploadFile(file, module, purpose, description, userId);
        return ApiResponse.success("文件上传成功", result);
    }
    
    /**
     * 批量上传文件
     */
    @PostMapping("/batch-upload")
    public ApiResponse<BatchUploadResponse> batchUpload(
            @RequestParam("files") MultipartFile[] files,
            @RequestParam(value = "module", defaultValue = "default") String module,
            @RequestParam(value = "purpose", defaultValue = "upload") String purpose,
            @RequestHeader(value = "X-User-Id", required = false) Long userId) {
        
        if (userId == null) {
            userId = 1L;
        }
        
        BatchUploadResponse result = fileService.batchUpload(files, module, purpose, userId);
        String message = String.format("批量上传完成，成功 %d 个，失败 %d 个", 
                result.getUploadedCount(), result.getFailedCount());
        return ApiResponse.success(message, result);
    }
    
    // ==================== 更新操作 ====================
    
    /**
     * 更新文件信息
     */
    @PutMapping("/{id}")
    public ApiResponse<FileResponse> update(
            @PathVariable Long id,
            @Valid @RequestBody FileUpdateRequest request) {
        FileResponse result = fileService.updateFile(id, request);
        return ApiResponse.success("文件信息更新成功", result);
    }
    
    // ==================== 删除操作 ====================
    
    /**
     * 删除文件
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable Long id) {
        fileService.deleteFile(id);
        return ApiResponse.success("文件删除成功", null);
    }
    
    /**
     * 批量删除文件
     */
    @PostMapping("/batch-delete")
    public ApiResponse<Map<String, Object>> batchDelete(@Valid @RequestBody BatchDeleteRequest request) {
        Map<String, Object> result = fileService.batchDelete(request.getFileIds());
        return ApiResponse.success(result);
    }
    
    /**
     * 清理过期文件
     */
    @PostMapping("/cleanup")
    public ApiResponse<Map<String, Object>> cleanup(@RequestParam(required = false, defaultValue = "30") Integer days) {
        Map<String, Object> result = fileService.cleanupExpired(days);
        return ApiResponse.success(result);
    }
    
    // ==================== 下载预览 ====================
    
    /**
     * 下载文件
     */
    @GetMapping("/{id}/download")
    public ResponseEntity<InputStreamResource> download(@PathVariable Long id) {
        try {
            FileEntity entity = fileService.getFileEntityForDownload(id);
            InputStream inputStream = fileService.downloadFile(id);
            
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, 
                            "attachment; filename=\"" + entity.getOriginalName() + "\"")
                    .header(HttpHeaders.CONTENT_TYPE, entity.getMimeType())
                    .contentType(MediaType.parseMediaType(entity.getMimeType()))
                    .body(new InputStreamResource(inputStream));
        } catch (Exception e) {
            log.error("文件下载失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 预览文件
     */
    @GetMapping("/{id}/preview")
    public ResponseEntity<InputStreamResource> preview(@PathVariable Long id) {
        try {
            FileEntity entity = fileService.getFileEntityForDownload(id);
            InputStream inputStream = fileService.previewFile(id);
            
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, 
                            "inline; filename=\"" + entity.getOriginalName() + "\"")
                    .header(HttpHeaders.CONTENT_TYPE, entity.getMimeType())
                    .contentType(MediaType.parseMediaType(entity.getMimeType()))
                    .body(new InputStreamResource(inputStream));
        } catch (Exception e) {
            log.error("文件预览失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    // ==================== 配置 ====================
    
    /**
     * 获取上传配置
     */
    @GetMapping("/config")
    public ApiResponse<UploadConfigResponse> getUploadConfig() {
        UploadConfigResponse result = fileService.getUploadConfig();
        return ApiResponse.success(result);
    }
}
