package com.weather.modules.weather.filescan.controller;

import com.weather.common.constant.Constant;
import com.weather.modules.weather.filescan.dto.WeatherFileScanRecordDTO;
import com.weather.modules.weather.filescan.service.WeatherFileScanRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("filescan/file")
@Tag(name = "文件展示")
public class FileDownloadController {

    @Resource
    private WeatherFileScanRecordService weatherFileScanRecordService;

    @GetMapping("display/{id}")
    @Operation(summary = "获取展示文件")
    @RequiresPermissions("filescan:record:display")
    public ResponseEntity<org.springframework.core.io.Resource> displayFile(@PathVariable("id") Long id) {
        WeatherFileScanRecordDTO record = weatherFileScanRecordService.get(id);
        if (record == null || record.getDisplayPath() == null) {
            return ResponseEntity.notFound().build();
        }

        File file = new File(record.getDisplayPath());
        if (!file.exists()) {
            return ResponseEntity.notFound().build();
        }

        FileSystemResource resource = new FileSystemResource(file);
        String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        String ext = record.getFileExt();
        if (ext == null) {
            // fall through to default
        } else if ("png".equalsIgnoreCase(ext)) {
            contentType = MediaType.IMAGE_PNG_VALUE;
        } else if ("gif".equalsIgnoreCase(ext)) {
            contentType = MediaType.IMAGE_GIF_VALUE;
        } else if ("jpg".equalsIgnoreCase(ext) || "jpeg".equalsIgnoreCase(ext)) {
            contentType = MediaType.IMAGE_JPEG_VALUE;
        } else if ("txt".equalsIgnoreCase(ext)) {
            contentType = MediaType.TEXT_PLAIN_VALUE;
        }

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "inline; filename=\"" + URLEncoder.encode(record.getFileName(), StandardCharsets.UTF_8) + "\"")
                .body(resource);
    }
}
