package com.dxhy.common.util;

import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.lang.reflect.Method;
import java.util.*;

/**
 *
 * @author jiaohongyang poi操作excel工具类 导入兼容.xls和.xlsx，导出仅支持.xlsx
 *
 * @date 2019年5月1日
 *
 */
@Component
@SuppressWarnings({"AliDeprecation", "AlibabaUndefineMagicConstant"})
@Slf4j
public class ExcelPoiUtil {
    private static WriteSheet writeSheet;
    private static WriteTable writeTable;
    private static ExcelWriter writer = null;
    // private static Sheet sheet;
    // private static Table table;

    public static void exportListArrayToExcel1(String excelFile, String title, JSONObject jsonObject, List dataList,
                                               boolean firstPage, boolean lastPage) throws Exception {
        // 文件存储路径是否存在
        File filePath = new File(getFilePath(excelFile));
        if (!filePath.exists()) {
            boolean mkdirs = filePath.mkdirs();
            log.info("创建目录：{}", mkdirs);
        }

        File file = new File(excelFile);
        if (firstPage) {
            // 首次导出时，如果文件存在则需要先删除，防止由于之前的任务失败导致的数据重复写入
            if (!file.exists()) {
                boolean delete = file.delete();
                log.info("首次导出删除文件：{}", delete);
            }
        }
        // excel不存在则创建
        if (!file.exists()) {
            boolean newFile = file.createNewFile();
            log.info("创建文件：{}", newFile);
        }
        // 生成excel
        JSONArray jsonArray = jsonObject.getJSONArray("titleExcleList");
        Object[] objects = jsonArray.toArray();
        String[] titleColumns = Arrays.copyOf(objects, objects.length, String[].class);
        JSONArray jsonArray1 = jsonObject.getJSONArray("titleExcleProp");
        Object[] objects1 = jsonArray1.toArray();
        String[] titleProp = Arrays.copyOf(objects1, objects1.length, String[].class);
        List<List<String>> list1 = new ArrayList<>();
        if (dataList != null && dataList.size() > 0) {
            for (Object o : dataList) {
                List<String> data = new ArrayList<>();
                for (String s : titleProp) {
                    String value = (String)getValue(o, s);
                    data.add(value);
                }
                list1.add(data);
            }
        }
        if (firstPage) {
            List<List<String>> titles = new ArrayList<>();
            for (String titleColumn : titleColumns) {
                titles.add(Collections.singletonList(titleColumn));
            }
            writer = EasyExcel.write(excelFile).registerWriteHandler(new CustomCellWriteHandler()).build();
            writeSheet = EasyExcel.writerSheet(1).sheetName(title).build();
            writeTable = EasyExcel.writerTable().head(titles).build();
            writer.write(list1, writeSheet, writeTable);
        } else {
            writer.write(list1, writeSheet, writeTable);
        }
        if (lastPage) {
            writer.finish();
        }

    }

    public static Object getValue(Object dto, String name) throws Exception {
        String s = name.substring(0, 1).toUpperCase();
        String substring = name.substring(1);
        try {
            Method method = dto.getClass().getMethod("get" + s + substring);
            return method.invoke(dto);
        } catch (Exception e) {
            return "";
        }
    }

    public static void exportListArrayToExcel(String excelFile, String title, String[] titleColumns,
                                              List<String[]> dataList, boolean firstPage, boolean lastPage) throws Exception {
        log.info("传入的dataList={}",dataList);

        // 文件存储路径是否存在
        File filePath = new File(getFilePath(excelFile));
        if (!filePath.exists()) {
            boolean mkdirs = filePath.mkdirs();
            log.info("创建目录：{}", mkdirs);
        }

        File file = new File(excelFile);
        if (firstPage) {
            // 首次导出时，如果文件存在则需要先删除，防止由于之前的任务失败导致的数据重复写入
            if (!file.exists()) {
                boolean delete = file.delete();
                log.info("首次导出删除文件：{}", delete);
            }
        }
        // excel不存在则创建
        if (!file.exists()) {
            boolean newFile = file.createNewFile();
            log.info("创建文件：{}", newFile);
        }
        List<List<String>> list = new ArrayList<>();
        for (String[] datas : dataList) {
            list.add(Arrays.asList(datas));
        }
        // 生成excel
        if (firstPage) {

            List<List<String>> titles = new ArrayList<>();
            for (String titleColumn : titleColumns) {
                titles.add(Collections.singletonList(titleColumn));
            }
            cn.hutool.poi.excel.ExcelWriter writer1 = ExcelUtil.getWriter(true);
            writer = EasyExcel.write(excelFile).registerWriteHandler(new CustomCellWriteHandler()).build();
            log.info("title={}",title);
            writeSheet = EasyExcel.writerSheet(1).sheetName(title).build();
            writeTable = EasyExcel.writerTable().head(titles).build();
            writer.write(list, writeSheet, writeTable);
        } else {

            writer.write(list, writeSheet, writeTable);
        }
        if (lastPage) {
            writer.finish();
        }

    }

    /**
    * @Description 写入第几个sheet
    * @Return void
     * * @param isfindsh 是否结束此excel，true，excel结束不再操作
    * @Author wangruwei
    * @Date 2022/11/30 11:23
    **/
    public static void exportListArrayToExcelBySheetNum(String excelFile, List<Map<String,Object>> sheetList) throws Exception {
        // 文件存储路径是否存在
        File filePath = new File(getFilePath(excelFile));
        if (!filePath.exists()) {
            boolean mkdirs = filePath.mkdirs();
            log.info("创建目录：{}", mkdirs);
        }

        File file = new File(excelFile);
        if (!file.exists()) {
            boolean delete = file.delete();
            log.info("首次导出删除文件：{}", delete);
        }
        // excel不存在则创建
        if (!file.exists()) {
            boolean newFile = file.createNewFile();
            log.info("创建文件：{}", newFile);
        }

        writer = EasyExcel.write(excelFile).registerWriteHandler(new CustomCellWriteHandler()).build();
        for (int i = 0; i < sheetList.size(); i++) {
            Map<String, Object> stringObjectMap = sheetList.get(i);
            List<String[]> dataList = (List<String[]>) stringObjectMap.get("data");
            List<List<String>> list = new ArrayList<>();
            for (String[] datas : dataList) {
                list.add(Arrays.asList(datas));
            }
            String title = stringObjectMap.get("title").toString();
            String[] titleColumns = (String[]) stringObjectMap.get("titleColumns");

            List<List<String>> titles = new ArrayList<>();
            for (String titleColumn : titleColumns) {
                titles.add(Collections.singletonList(titleColumn));
            }
            cn.hutool.poi.excel.ExcelWriter writer1 = ExcelUtil.getWriter(true);
            writeSheet = EasyExcel.writerSheet(i+1).sheetName(title).build();
            writeTable = EasyExcel.writerTable().head(titles).build();
            writer.write(list, writeSheet, writeTable);
        }
        writer.finish();

    }

    /**
     * 根据全路径获取存储路径
     *
     * @param fileName
     *            文件名
     *
     *
     */
    private static String getFilePath(String fileName) {
        StringBuilder filePath = new StringBuilder();
        // linux服务器
        if (!fileName.contains(":")) {
            filePath.append("/");
        }
        String[] filePaths = fileName.split("/");

        for (int i = 0; i < filePaths.length - 1; i++) {
            if (!StringHelper.isBlank(filePaths[i])) {
                filePath.append(filePaths[i]);
                filePath.append("/");
            }
        }
        return filePath.toString();
    }
}
