package cn.com.qmth.examcloud.tool.controller;

import cn.com.qmth.examcloud.tool.config.Constants;
import cn.com.qmth.examcloud.tool.vo.user.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

public class BaseController {

    private final static Logger log = LoggerFactory.getLogger(BaseController.class);

    protected HttpServletRequest currentRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    protected HttpSession currentSession() {
        return currentRequest().getSession();
    }

    protected User currentLoginUser() {
        return (User) currentSession().getAttribute(Constants.LOGIN_USER);
    }

    protected void download(HttpServletResponse response, byte[] bytes, String title) {
        try (OutputStream out = response.getOutputStream();) {
            response.reset();
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(title, "UTF-8"));
            out.write(bytes);
            out.flush();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    protected void download(HttpServletResponse response, File file, String title) {
        if (file == null || !file.exists() || !file.isFile()) {
            this.download(response, new byte[0], "文件不存在");
            return;
        }

        try (FileInputStream fis = new FileInputStream(file);
             OutputStream out = response.getOutputStream();
        ) {
            response.reset();
            response.setHeader("Accept-Length", String.valueOf(fis.available()));
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(title, "UTF-8"));
            int read;
            byte[] bytes = new byte[1024];
            while ((read = fis.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            out.flush();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}
