package com.ruoyi.system.config;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.URLUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.HttpDownloadUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * 本地文件公开下载配置
 * 方式一:SpringBoot静态资源配置
 * 方式二:Servlet
 */
@Configuration
@RequiredArgsConstructor
@Slf4j
public class DownloadFileConfig {

    private final RuoYiConfig config;

    @Bean
    public WebMvcConfigurer DownloadFileWebMvcConfigurer() {
        return new WebMvcConfigurer(){

            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
                //加入外部静态资源html文件夹
                String path = new File(new File(config.upload.savePath).getAbsolutePath()).toURI().toString();
                registry.addResourceHandler(config.upload.pre+"/**").addResourceLocations(path);
                log.info("添加静态资源目: {}/** ={}",config.upload.pre,path);

            }
        };
    }


    public ServletRegistrationBean DownloadFileServletRegistrationBean() {
        ServletRegistrationBean bean = new ServletRegistrationBean();
        bean.setServlet(new HttpServlet() {
            @Override
            protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                String uri = req.getRequestURI().substring(config.upload.pre.length());
                uri = URLUtil.decode(uri);
                File down = new File(config.upload.savePath, uri);
                if(down.isFile()) {
                    try {
                        HttpDownloadUtil.download(req, resp,down,
                            FileNameUtil.getName(uri));
                        resp.getOutputStream().close();
                    } catch (Exception e) {
                        resp.reset();
                        resp.sendError(404);
                    }
                }else {
                    resp.sendError(404);
                }
            }
        });
        bean.addUrlMappings(config.upload.pre+"/*");
        return bean;
    }
}
