package com.gree.mall.manager.utils.excel;



import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import com.alibaba.excel.read.listener.PageReadListener;
import com.gree.mall.manager.bean.ExcelData;
import com.gree.mall.manager.exception.RemoteServiceException;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder.BorderSide;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.Color;
import java.io.*;

import java.util.ArrayList;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;

@Slf4j
public class ExcelUtils {

    //常规导出excel
    public static void exportExcel(HttpServletRequest request, HttpServletResponse response, String fileName, ExcelData data,int idIndex,int[] mergeRows) throws Exception {
        setResponse(request,response,fileName);
        // 下载文件的默认名称
        exportExcel(data, response.getOutputStream(),idIndex,mergeRows);
    }


    public static void exportExcel(ExcelData data, OutputStream out,int idIndex,int[] mergeRows) throws Exception {

        XSSFWorkbook wb = new XSSFWorkbook();
        try {
            String sheetName = data.getName();
            if (null == sheetName) {
                sheetName = "Sheet1";
            }
            XSSFSheet sheet = wb.createSheet(sheetName);
            writeExcel(wb, sheet, data,idIndex,mergeRows);

            wb.write(out);
        } finally {
            wb.close();
        }
    }

    private static void writeExcel(XSSFWorkbook wb, Sheet sheet, ExcelData data,int idIndex,int[] mergeRows) {

        int rowIndex = 0;

        rowIndex = writeTitlesToExcel(wb, sheet, data.getTitles());
        writeRowsToExcel(wb, sheet, data.getRows(), rowIndex,idIndex,mergeRows);
        autoSizeColumns(sheet, data.getTitles().size() + 1);

    }

    private static int writeTitlesToExcel(XSSFWorkbook wb, Sheet sheet, List<String> titles) {
        int rowIndex = 0;
        int colIndex = 0;

        Font titleFont = wb.createFont();
        titleFont.setFontName("simsun");
        titleFont.setBold(true);
        // titleFont.setFontHeightInPoints((short) 14);
        titleFont.setColor(IndexedColors.BLACK.index);

        XSSFCellStyle titleStyle = wb.createCellStyle();
//        titleStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
//        titleStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        titleStyle.setFillForegroundColor(new XSSFColor(new Color(182, 184, 192)));
//        titleStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
        titleStyle.setFont(titleFont);
        titleStyle.setWrapText(true);
        setBorder(titleStyle, BorderStyle.THIN, new XSSFColor(new Color(182, 184, 192)));

        Row titleRow = sheet.createRow(rowIndex);
        // titleRow.setHeightInPoints(25);
        colIndex = 0;

        for (String field : titles) {
            Cell cell = titleRow.createCell(colIndex);
            cell.setCellValue(field);
            cell.setCellStyle(titleStyle);
            colIndex++;
        }


        rowIndex++;
        return rowIndex;
    }

    private static int writeRowsToExcel(XSSFWorkbook wb, Sheet sheet, List<List<Object>> rows, int rowIndex,int idIndex,int[] mergeRows) {
        int colIndex = 0;

        Font dataFont = wb.createFont();
        dataFont.setFontName("simsun");
        // dataFont.setFontHeightInPoints((short) 14);
        dataFont.setColor(IndexedColors.BLACK.index);

        XSSFCellStyle dataStyle = wb.createCellStyle();
        dataStyle.setAlignment(HorizontalAlignment.CENTER);
        dataStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        dataStyle.setFont(dataFont);
        dataStyle.setWrapText(true);
        setBorder(dataStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0)));
        String lastCellValue = "$";
        int startRow = 0;
        int endRow = 0;
        for (List<Object> rowData : rows) {
            Row dataRow = sheet.createRow(rowIndex);
            // dataRow.setHeightInPoints(25);
            colIndex = 0;

            for (Object cellData : rowData) {
                Cell cell = dataRow.createCell(colIndex);
                if (cellData != null) {
                    cell.setCellValue(cellData.toString());
                } else {
                    cell.setCellValue("");
                }
                if(mergeRows!=null&&colIndex!=-1&&colIndex==idIndex){
                    if(StringUtils.isNotEmpty(cellData.toString()) && cellData.toString().equals(lastCellValue)){
                        if(startRow==0&&endRow==0){
                            startRow = rowIndex-1;
                            endRow = startRow+1;
                        }else{
                            endRow++;
                        }
                    }else{
                        if(startRow!=0&&endRow!=0){
                            for(int i=0;i<mergeRows.length;i++){
                                CellRangeAddress region = new CellRangeAddress(startRow, endRow, mergeRows[i], mergeRows[i]);
                                sheet.addMergedRegion(region);
                            }
                        }
                        startRow = 0;
                        endRow = 0;
                    }
                    lastCellValue = cellData.toString();
                }

                cell.setCellStyle(dataStyle);
                colIndex++;
            }
            rowIndex++;


        }
        return rowIndex;
    }

    private static void autoSizeColumns(Sheet sheet, int columnNumber) {

        for (int i = 0; i < columnNumber; i++) {
            int orgWidth = sheet.getColumnWidth(i);
            sheet.autoSizeColumn(i, true);
            int newWidth = (int) (sheet.getColumnWidth(i) + 100);
            if (newWidth > orgWidth) {
                sheet.setColumnWidth(i, newWidth);
            } else {
                sheet.setColumnWidth(i, orgWidth);
            }
        }
    }

    private static void setBorder(XSSFCellStyle style, BorderStyle border, XSSFColor color) {
        style.setBorderTop(border);
        style.setBorderLeft(border);
        style.setBorderRight(border);
        style.setBorderBottom(border);
        style.setBorderColor(BorderSide.TOP, color);
        style.setBorderColor(BorderSide.LEFT, color);
        style.setBorderColor(BorderSide.RIGHT, color);
        style.setBorderColor(BorderSide.BOTTOM, color);
    }

    public static List<Object> importExcel(MultipartFile file) throws IOException, RemoteServiceException {
        log.info("【本次导入数据】开始:" + DateUtil.formatDateTime(new Date()));
        List<Object> datas = new ArrayList<>();
        EasyExcelFactory.read(file.getInputStream(), new PageReadListener<Map<Integer, Object>>(v -> {
            for (Map<Integer, Object> map : v) {
                List<Object> list = new ArrayList<>();
                for (Integer key : map.keySet()) {
                    list.add(map.get(key));
                }
                datas.add(list);
            }
        })).sheet().doRead();
        log.info("【本次导入数据】结束:" + DateUtil.formatDateTime(new Date()) + ",一共" + datas.size());
        return datas;
    }

    public static List<Object> importExcel(InputStream inputStream) throws RemoteServiceException {
        log.info("【本次导入数据】开始:" + DateUtil.formatDateTime(new Date()));
        List<Object> datas = new ArrayList<>();
        EasyExcelFactory.read(inputStream, new PageReadListener<Map<Integer, Object>>(v -> {
            for (Map<Integer, Object> map : v) {
                List<Object> list = new ArrayList<>();
                for (Integer key : map.keySet()) {
                    list.add(map.get(key));
                }
                datas.add(list);
            }
        })).sheet().doRead();
        log.info("【本次导入数据】结束:" + DateUtil.formatDateTime(new Date()) + ",一共" + datas.size());
        return datas;
    }





    private static void setResponse(HttpServletRequest request, HttpServletResponse response, String fileName)throws Exception{
        //        fileName = URLEncoder.encode(fileName, "UTF-8");
        // 告诉浏览器用什么软件可以打开此文件
//        response.setHeader("content-Type", "application/vnd.ms-excel");
//        Header("Content-type: application/octet-stream");
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        Browser browser = UserAgent.parseUserAgentString(request.getHeader("user-agent")).getBrowser();
        if (browser != null) {
            if (browser == Browser.IE || browser == Browser.EDGE) {
                response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            } else if (browser == Browser.OPERA || browser == Browser.CHROME) {
                response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);
            } else if (browser == Browser.SAFARI) {
                response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"");
            } else if (browser == Browser.FIREFOX) {
                response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);
            } else {
                response.addHeader("Content-Disposition", "attachment;filename=" + new String((fileName).getBytes("gb2312"), "ISO-8859-1"));
//                response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"; filename*=UTF-8''" + fileName);
//                response.setContentType("application/octet-stream;charset=utf-8");
//                response.setHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes(),"iso-8859-1") + ".xls");
//                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            }
        }
    }

    public static void exportExcel(HttpServletRequest request, HttpServletResponse response, String fileName, ExcelData excelData) throws Exception {
        setResponse(request,response,fileName);
        // 下载文件的默认名称
        exportExcel(excelData, response.getOutputStream(),-1,null);
    }
}
