package io.renren.common.utils.export;

import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.view.AbstractView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * Created by xk on 2017/12/4 0004.
 */
public class JxlsView extends AbstractView {
    private static Logger log = LoggerFactory.getLogger(JxlsView.class);

    private JxlsTemplate template;

    private Object data;
    private Object sheetdata;

    public JxlsView() {
        this.setContentType("application/vnd.ms-excel");
    }

    public JxlsView(JxlsTemplate template, Object data) {
        this();
        this.template = template;
        this.data = data;
    }

    public JxlsView(JxlsTemplate template, Object data, Object sheetdata) {
        this();
        this.template = template;
        this.data = data;
        this.sheetdata = sheetdata;
    }

    protected boolean generatesDownloadContent() {
        return true;
    }

    protected final void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType(this.getContentType());
        response.setHeader("Content-Disposition", "attachment;filename="
                + EncodeTools.encodeFileNameByBrowser(template.getName(), request));
        InputStream is = null;
        try {
            is = JxlsView.class.getResourceAsStream(template.getPath());
            Context context = new Context();
            context.putVar("data", data);
            context.putVar("sheetNames", sheetdata);
            logger.info("data" + data);
            logger.info("is" + is);
            logger.info("getOutputStream" + response.getOutputStream());
            JxlsHelper.getInstance().processTemplate(is, response.getOutputStream(), context);
        } catch (Exception e) {
            log.error("导出失败", e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    log.error("is关闭失败", e);
                }
            }
        }

    }
}
