package com.yanzuoguang.cloud.excel;


import com.yanzuoguang.cloud.helper.HttpFileHelper;
import com.yanzuoguang.excel.ExcelConsole;
import com.yanzuoguang.excel.ExcelRow;
import com.yanzuoguang.excel.ExportBase;
import com.yanzuoguang.excel.ExportData;
import com.yanzuoguang.util.helper.StringHelper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * HTTP方式下载Excel文件
 *
 * @param <T> 行数据的类型
 * @author 颜佐光
 */
public class ExcelHttp<T extends Object> extends ExcelConsole<T> {

    /**
     * 导出成Excel
     *
     * @param exportData 导出信息
     */
    public ExcelHttp(ExportData exportData) {
        super(exportData);
    }

    /**
     * 导出成Excel
     *
     * @param config    导出信息
     * @param rowHandle 导出下载信息
     */
    public ExcelHttp(ExportData config, ExcelRow<T> rowHandle) {
        super(config, rowHandle);
    }

    /**
     * 下载文件
     *
     * @param response 输出流
     */
    public ExcelHttp down(HttpServletResponse response) throws IOException {
        return this.down(response, StringHelper.EMPTY);
    }

    /**
     * 下载文件
     *
     * @param response     输出流
     * @param downFileName 下载文件名
     */
    public ExcelHttp down(HttpServletResponse response, String downFileName) throws IOException {
        if (StringHelper.isEmpty(downFileName)) {
            downFileName = this.getConfig().getDownFileName();
        }
        if (StringHelper.isEmpty(downFileName)) {
            downFileName = this.getConfig().getFileName();
        }
        HttpFileHelper.localToDown(this.getFileName(), downFileName, response);
        return this;
    }

    /**
     * 导出数据
     *
     * @param req      请求对接
     * @param response 输出结果
     * @param excelDao dao层实现接口
     */
    public static <T extends Object, M extends Object> void export(ExportBase<T> req, HttpServletResponse response, ExcelDao<T, M> excelDao) {
        ExportData config = req.getConfig();
        if (config == null) {
            throw new RuntimeException("导出时请传入配置信息");
        }
        if (StringHelper.isEmpty(config.getServerPath())) {
            config.setServerPath("/home/cache/");
        }
        if (StringHelper.isEmpty(config.getFileName())) {
            config.setFileName(String.format("%s.xlsx", StringHelper.getNewID()));
        }
        if (StringHelper.isEmpty(config.getDownFileName())) {
            config.setDownFileName(String.format("%s-%s.xlsx", config.getTitle(), config.getSubTitle()));
        }
        ExcelHttp<M> excel = new ExcelHttp<>(config);
        try {
            excel.open();
            excelDao.export(excel, req.getCond());
            excel.save();
            excel.down(response);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("下载失败", e);
        } finally {
            // 删除生成的临时文件
            excel.remove();
        }
    }
}