package org.wcs.serve.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.IOUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Service;
import org.wcs.factory.AppServeResponseFactory;
import org.wcs.model.vo.serve.AppServeDataResponse;
import org.wcs.serve.service.intf.IFileService;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FileService implements IFileService {

    /**
     * 获取文件名列表
     * @return 文件名列表
     */
    @Override
    public AppServeDataResponse<List<String>> getFilesName() {
        try {
            List<String> fileNames = new ArrayList<>();
            ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resourcePatternResolver.getResources("classpath:appFiles/*");
            for (Resource resource : resources) {
                fileNames.add(resource.getFilename());
            }
            return AppServeResponseFactory.success("获取文件列表成功", fileNames);
        } catch (Exception e) {
            log.error("获取文件列表失败", e);
            return AppServeResponseFactory.fail("获取文件列表失败", null);
        }

    }

    /**
     * 下载文件
     */
    @Override
    public void downLoadFile(String fileName, HttpServletResponse response) {
        Object userIdObj = StpUtil.getLoginId();
        if(userIdObj == null) {
            return;
        }
        String userId = userIdObj.toString();
        log.info("用户{};下载文件{}", userId, fileName);

        ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver();
        Resource resource = resourceLoader.getResource("classpath:appFiles/" + fileName);
        try (InputStream inputStream = resource.getInputStream()) {
            String headerValue = "attachment; filename*=UTF-8''" +
                    java.net.URLEncoder.encode(fileName, StandardCharsets.UTF_8);
            response.setCharacterEncoding("utf-8");
            String[] fileNames = fileName.split("\\.");
            String contentType = fileNames.length > 1 ? "application/" + fileNames[fileNames.length - 1] : "application/octet-stream";
            // 特别处理PDF文件
            if (contentType.equals("application/pdf")) {
                response.setContentType("application/pdf; charset=utf-8");
                response.setHeader("Content-Type", "application/pdf");
            } else {
                response.setContentType(contentType);
            }
            response.setHeader("Content-Disposition", headerValue);
            // 使用流式传输，避免将整个文件加载到内存
            ServletOutputStream os = response.getOutputStream();
            os.write(IOUtils.toByteArray(inputStream));
            os.flush();
        } catch (Exception e) {
            log.error("下载文件失败", e);
        } finally {
            try {
                resource.getInputStream().close();
                response.getOutputStream().close();
            } catch (Exception e) {
                log.error("关闭文件输入流失败", e);
            }
        }
    }
}
