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


import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.apache.commons.lang3.StringUtils;
import com.gree.mall.manager.bean.ExcelData;
import com.gree.mall.manager.bean.ExcelExamData;
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.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.Font;
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.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.Color;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ExcelExamUtils {


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

    public static void exportExcel(ExcelExamData data, OutputStream out) 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);

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

    private static void writeExcel(XSSFWorkbook wb, Sheet sheet, ExcelExamData data) {

        int rowIndex = 0;

        rowIndex = writeTitlesToExcel(wb, sheet, data.getExcelTitleBean());
        writeRowsToExcel(wb, sheet, data.getRows(), rowIndex);
        //todo 待处理....
        autoSizeColumns(sheet, data.getExcelTitleBean().size()+(6*20) + 1);

    }

    private static int writeTitlesToExcel(XSSFWorkbook wb, Sheet sheet, List<ExcelExamData.ExcelTitle> 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(HorizontalAlignment.CENTER);
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        titleStyle.setFont(titleFont);
        titleStyle.setWrapText(true);
        setBorder(titleStyle, BorderStyle.THIN, new XSSFColor(new Color(182, 184, 192)));

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

        for (ExcelExamData.ExcelTitle excelTitle : titles) {

            Cell cell = titleRow.createCell(colIndex);
            cell.setCellValue(excelTitle.getTitle());

            if(excelTitle.getChildTitle() != null){
                List<String> childTitle = excelTitle.getChildTitle();
                int startColIndex = colIndex;

                for(String childValue : childTitle){
                    Cell cell2 = row2.createCell(colIndex);
                    cell2.setCellValue(childValue);
                    cell2.setCellStyle(titleStyle);
                    colIndex ++;
                }

                //设置背景色
                if(excelTitle.getColorIndex() != null) {
                    XSSFCellStyle cellStyle = wb.createCellStyle();
                    cellStyle.setAlignment(HorizontalAlignment.CENTER);
                    cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                    cellStyle.setFillForegroundColor(excelTitle.getColorIndex());
                    cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                    cellStyle.setFont(titleFont);
                    cellStyle.setWrapText(true);
                    cell.setCellStyle(cellStyle);
                }

                //跨列
                CellRangeAddress regiontitletitle = new CellRangeAddress(0, 0, startColIndex, colIndex-1);
                sheet.addMergedRegion(regiontitletitle);

            }else{
                cell.setCellStyle(titleStyle);
                //跨行
                CellRangeAddress regiontitletitle = new CellRangeAddress(0, 1, colIndex, colIndex);
                sheet.addMergedRegion(regiontitletitle);
                colIndex++;
            }

        }
        //这里占用了2行
        rowIndex+=2;
        return rowIndex;
    }

    private static int writeRowsToExcel(XSSFWorkbook wb, Sheet sheet, List<List<Object>> rows, int rowIndex) {
        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)));

        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("");
                }

                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);
    }





    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");
        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");

            }
        }
    }



}
