package com.nbport.zgwl.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.nbport.zgwl.exception.ServiceErrorCodeRange;
import com.nbport.zgwl.exception.ServiceException;
import com.nbport.zgwl.utils.FileStorageUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

@Service
@Slf4j
@RequiredArgsConstructor
public class LocalFileService {

    @Value("${file.local.path:${user.dir}/upload-files}")
    private String localPath;

    public String upload(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new ServiceException("上传文件不能为空");
        }
        try {
            Path rootPath = Paths.get(localPath).toAbsolutePath().normalize();
            Files.createDirectories(rootPath);

            String dateFolder = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
            String suffix = FileStorageUtils.getFileSuffix(Objects.requireNonNullElse(file.getOriginalFilename(), ""));
            String fileName = IdUtil.simpleUUID() + suffix;
            String relativePath = dateFolder + "/" + fileName;
            Path targetPath = FileStorageUtils.resolveFilePath(rootPath, relativePath);
            Files.createDirectories(targetPath.getParent());
            file.transferTo(targetPath);
            log.info("文件上传成功，targetPath={}", targetPath);
            return relativePath;
        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new ServiceException("文件上传失败");
        }
    }

    public ResponseEntity<ByteArrayResource> download(String fileName) {
        try {
            Path rootPath = Paths.get(localPath).toAbsolutePath().normalize();
            Path filePath = FileStorageUtils.resolveFilePath(rootPath, fileName);
            if (!Files.exists(filePath) || Files.isDirectory(filePath)) {
                throw new ServiceException(ServiceErrorCodeRange.FILE_NOT_FOUND, "文件不存在");
            }
            byte[] bytes = Files.readAllBytes(filePath);
            String contentType = Files.probeContentType(filePath);
            MediaType mediaType = contentType == null ? MediaType.APPLICATION_OCTET_STREAM : MediaType.parseMediaType(contentType);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(mediaType);
            headers.setContentLength(bytes.length);
            headers.setContentDisposition(ContentDisposition.inline().filename(filePath.getFileName().toString()).build());
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(new ByteArrayResource(bytes));
        } catch (IOException e) {
            log.error("文件下载失败", e);
            throw new ServiceException("文件下载失败");
        }
    }
}
