package ink.wgink.module.file.filter;

import com.alibaba.fastjson.JSON;
import ink.wgink.exceptions.base.SystemException;
import ink.wgink.module.file.manager.FilesManager;
import ink.wgink.pojo.bos.files.FilesShowCode;
import ink.wgink.pojo.result.ErrorResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @ClassName: FilesFilter
 * @Description: 文件过滤器
 * @Author: wanggeng
 * @Date: 2022/8/1 09:21
 * @Version: 1.0
 */
public class FilesFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String fileId = request.getParameter("file");
        String code = request.getParameter("code");
        String isOpen = request.getParameter("open");
        if (StringUtils.isBlank(code)) {
            notFoundResponse(response, "查看码不存在");
            return;
        }
        if (StringUtils.isBlank(fileId)) {
            notFoundResponse(response, "文件不存在");
            return;
        }
        try {
            FilesShowCode showCode = FilesManager.getInstance().getShowCode(fileId, code);
            if (Integer.parseInt(isOpen) == 0) {
                // 下载
                response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(showCode.getFileName(), "UTF-8"));
            }
        } catch (SystemException e) {
            notFoundResponse(response, e.getMessage());
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    /**
     * 文件未找到
     *
     * @param response
     * @param errorInfo
     * @throws IOException
     */
    private void notFoundResponse(HttpServletResponse response, String errorInfo) throws IOException {
        response.setStatus(HttpStatus.NOT_FOUND.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        ErrorResult result = new ErrorResult(ErrorResult.ErrorResultCodeEnum.FILE_ERROR.getValue(), errorInfo);
        response.getWriter().write(JSON.toJSONString(result));
    }
}
