package com.ningdatech.carapi.common.util;

import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.ningdatech.basic.model.ApiResponse;
import com.ningdatech.basic.util.StrPool;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;
import java.util.function.BiConsumer;

/**
 * <p>
 * ExcelDownUtil
 * </p>
 *
 * @author WendyYang
 * @since 00:48 2022/11/5
 */
@Slf4j
public class ExcelDownUtil {

    private static String encodeName(String name) {
        String fileName;
        try {
            fileName = URLEncoder.encode(name, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("文件名编码异常：", e);
            fileName = UUID.randomUUID().toString().replace("-", "");
        }
        return fileName;
    }

    @SneakyThrows
    private static <T> void down(HttpServletResponse response, T param, BiConsumer<HttpServletResponse, T> consumer) {
        response.setCharacterEncoding("utf-8");
        try {
            consumer.accept(response, param);
        } catch (Exception e) {
            log.error("文件导出失败：", e);
            response.reset();
            response.setContentType(StrPool.CONTENT_TYPE);
            ApiResponse<Void> res = ApiResponse.of(HttpStatus.SC_BAD_REQUEST, "导出失败", null);
            response.setStatus(HttpStatus.SC_BAD_REQUEST);
            response.getWriter().println(JSON.toJSONString(res));
        }
    }

    public static <T> void downXls(HttpServletResponse response, T param, BiConsumer<HttpServletResponse, T> consumer) {
        response.setContentType(ExcelUtil.XLS_CONTENT_TYPE);
        down(response, param, consumer);
    }

    public static <T> void downXlsx(HttpServletResponse response, T param, BiConsumer<HttpServletResponse, T> consumer) {
        response.setContentType(ExcelUtil.XLSX_CONTENT_TYPE);
        down(response, param, consumer);
    }

    public static void setFileName(String fileName, HttpServletResponse response) {
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + encodeName(fileName) + ".xls");
    }

}
