package com.ximai.common.utils.excel;

import com.alibaba.excel.EasyExcel;
import io.swagger.annotations.ApiModel;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Optional;

/**
 * description: ExcelWriter <br>
 * date: 2022/2/24 13:36 <br>
 * author: xi.feng <br>
 * version: 1.0 <br>
 */
public class ExcelWriter {
    public static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    public static <T> void write(OutputStream outputStream, Class<T> head, Collection<T> data){
        String sheetName = Optional.ofNullable(head.getAnnotation(ApiModel.class)).map(ApiModel::value).orElse("Sheet1");
        EasyExcel.write(outputStream, head).sheet(sheetName).doWrite(data);
    }

    public static <T> void write(OutputStream outputStream, Class<T> head){
        write(outputStream, head, new ArrayList<>(0));
    }

    public static <T> void write(HttpServletResponse response, Class<T> head, Collection<T> data) throws IOException {
        Optional<String> name = Optional.ofNullable(head.getAnnotation(ApiModel.class)).map(ApiModel::value);
        String now = LocalDateTime.now().format(dateTimeFormatter);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(name.orElse(head.getSimpleName()) + now, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx'");

        String sheetName = name.orElse("Sheet1");
        EasyExcel.write(response.getOutputStream(), head).registerWriteHandler(new I18ncellWriteHandler()).sheet(sheetName).doWrite(data);
    }

    public static <T> void write(HttpServletResponse response, Class<T> head) throws IOException {
        write(response, head, new ArrayList<>(0));
    }
}
