package com.cf.imes.module.executor.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.cf.imes.module.executor.dal.dataobject.order.OrderDO;
import com.cf.imes.module.executor.util.fileConversion.admin.files.excel.OrderPlateImportExcelVO;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.ResourceUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * excel 文件写入
 */
public class ExcelWriterUtil {

    // 写excel
    public static void write(HttpServletResponse response,
                             Map<Object, Object> orderMap,
                             List<OrderPlateImportExcelVO> list,
                             String filePathErr) throws IOException {

        //输入流
        InputStream inputStream = ResourceUtils.getURL(filePathErr).openStream();
        ServletOutputStream outputStream = response.getOutputStream();


        //设置输出流和模板信息
        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();

        //开启自动换行，自动换行表示每次写入一条list数据是都会重新生成一行空行,此选项默认是关闭的,需要提前设置为true
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();

        //准备单组和数据
        Map<String, String> map = new HashMap<>();
        map.put("customOrderNo", (String) orderMap.get("自定义单号"));
        map.put("customer", (String) orderMap.get("客户"));
        map.put("address", (String) orderMap.get("客户地址"));
        map.put("phoneNumber", (String) orderMap.get("客户电话"));
        map.put("remark", (String) orderMap.get("备注"));
        map.put("splitter", (String) orderMap.get("拆单员"));
        map.put("salesman", (String) orderMap.get("业务员"));
        map.put("dealerPhoneNumber", (String) orderMap.get("经销商电话"));
        map.put("dealer", (String) orderMap.get("经销商"));
        map.put("deliveryDate", (String) orderMap.get("出货日期"));

        excelWriter.fill(map, writeSheet);

        //列表
        excelWriter.fill(list, fillConfig, writeSheet);

        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        //关流
        excelWriter.finish();
        inputStream.close();
        outputStream.close();
    }

    // 写excel
    public static void writeErr(HttpServletResponse response,
                                String err,
                                String filePathErr) throws IOException {
        //输入流
        InputStream inputStream = ResourceUtils.getURL(filePathErr).openStream();
        ServletOutputStream outputStream = response.getOutputStream();

        //设置输出流和模板信息
        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();

        //准备单组和数据
        Map<String, String> map = new HashMap<>();
        map.put("err", err);

        excelWriter.fill(map, writeSheet);


        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        //关流
        excelWriter.finish();
        inputStream.close();
        outputStream.close();
    }

    public static void exportExcelZip(HttpServletResponse response, Map<OrderDO, Object> map, String filePathErr, String type) throws IOException {
        ServletOutputStream outputStream = response.getOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);

        try {
            for (Map.Entry<OrderDO, Object> entry : map.entrySet()) {
                OrderDO k = entry.getKey();
                Object value = entry.getValue();

                // 创建ExcelWriter并填充数据
                InputStream inputStream = ResourceUtils.getURL(filePathErr).openStream();
                ExcelWriter excelWriter = EasyExcel.write(outputStream)
                        .withTemplate(inputStream)
                        .excelType(ExcelTypeEnum.XLS)
                        .build();

                WriteSheet writeSheet = EasyExcel.writerSheet().build();
                // 填充订单数据
                excelWriter.fill(fillOrderData(k), writeSheet);
                // 填充列表数据
                excelWriter.fill(value, fillConfig(), writeSheet);

                // 写入ZipOutputStream
                ZipEntry zipEntry = new ZipEntry(type + "_" + k.getId() + ".xls");
                zipOutputStream.putNextEntry(zipEntry);
                Workbook workbook = excelWriter.writeContext().writeWorkbookHolder().getWorkbook();
                workbook.write(zipOutputStream);
                excelWriter.finish(); // 关闭ExcelWriter

                // 关闭输入流
                inputStream.close();
            }
        } finally {
            // 关闭流
            zipOutputStream.close();
            outputStream.close();
        }
    }

    public static void exportExcel(HttpServletResponse response,
                                   OrderDO orderDO,
                                   List<OrderPlateImportExcelVO> list,
                                   String filePathErr,
                                   String type) throws IOException {
        //输入流
        InputStream inputStream = ResourceUtils.getURL(filePathErr+ "\\" + type).openStream();
        ServletOutputStream outputStream = response.getOutputStream();


        //设置输出流和模板信息
        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();

        //开启自动换行，自动换行表示每次写入一条list数据是都会重新生成一行空行,此选项默认是关闭的,需要提前设置为true
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();

        //准备单组和数据
        Map<String, String> mapOrder = fillOrderData(orderDO);

        excelWriter.fill(mapOrder, writeSheet);

        //列表
        excelWriter.fill(list, fillConfig, writeSheet);

        //设置文件名的编码格式,防止文件名乱码
        String fileName = URLEncoder.encode(type.replace("模板",String.valueOf(orderDO.getId())), "UTF-8");
        //固定写法,设置响应头
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");

        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        //关流
        excelWriter.finish();
        inputStream.close();
        outputStream.close();
    }

    // 填充订单数据
    private static Map<String, String> fillOrderData(OrderDO order) {
        Map<String, String> orderMap = new HashMap<>();
        orderMap.put("customOrderNo", order.getCustomOrderNo());
        orderMap.put("orderId", order.getId().toString());
        orderMap.put("orderData", order.getOrderDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        orderMap.put("customer", order.getCustomer());
        orderMap.put("address", order.getAddress());
        orderMap.put("phoneNumber", order.getPhoneNumber());
        orderMap.put("remark", order.getRemark());
        orderMap.put("splitter", order.getSplitter());
        orderMap.put("salesman", order.getSalesman());
        orderMap.put("dealerPhoneNumber", order.getDealerPhoneNumber());
        orderMap.put("dealer", order.getDealer());
        orderMap.put("deliveryDate", order.getDeliveryDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        return orderMap;
    }

    // 填充配置
    private static FillConfig fillConfig() {
        return FillConfig.builder().forceNewRow(Boolean.TRUE).build();
    }

}
