package com.zcxk.rmcp.web.excel.download;


import com.zcxk.core.common.util.FileUtil;
import com.zcxk.rmcp.web.excel.model.DownloadExcelData;
import com.zcxk.rmcp.web.service.CommonService;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.URLEncoder;


public abstract class AbstractDownloadExcelAdapter {



    protected DownloadExcelService excelService;
    protected DownloadExcelData data;


    public AbstractDownloadExcelAdapter build(DownloadExcelData data){
        this.data = data;
        return this;

    }
    public AbstractDownloadExcelAdapter setParam(DownloadExcelService excelService){
        this.excelService = excelService;
        this.excelService.setParam(data);
        return this;
    }
    /**
     * 填充模板数据
     */
    public abstract AbstractDownloadExcelAdapter fillData();

    /**
     * 下载文件
     */
    public void downloadExcel(){
        try (FileInputStream fileInputStream = new FileInputStream(data.getFilePath())){
            String filename = URLEncoder.encode( data.getDownloadName()+".xlsx", "UTF-8");
            //设置下载头
            data.getResponse().setHeader("Content-Disposition", "attachment;filename=" + filename);
            ServletOutputStream outputStream = data.getResponse().getOutputStream();

            //将文件写入浏览器
            byte[] bys = new byte[fileInputStream.available()];
            fileInputStream.read(bys);
            outputStream.write(bys);
            outputStream.flush();
            outputStream.close();
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            FileUtil.deleteFile(data.getFilePath());
        }

    }
}
