package com.unis.detectionnum.server.utils;


import com.unis.detectionnum.common.vo.CableVO;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.hssf.util.Region;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Pattern;
/**
 * Created by Administrator on 2017/4/26.
 */
public class ExcelUtils {

    /*====================================Excel导出开始=======================================================*/

    private ExcelUtils() {
        throw new IllegalStateException("Utility class");
    }
    /**
     * null转化为""
     *
     * @param o
     * @return java.lang.String
     * @date 2019/3/28
     */
    public static String nullToString(Object o) {
        if (o == null || o == "null") {
            return "";
        } else {
            return o.toString();
        }
    }

    /**
     * 机械设备（物资器材）保管总账
     * @param list
     * @return
     */
    public static HSSFWorkbook custodyNewBook(String title,List<CableVO> list) {
        // 声明一个工作薄
        HSSFWorkbook workbook;
        HSSFSheet sheet;
        HSSFRow rows;

        workbook = new HSSFWorkbook();
        sheet = workbook.createSheet("测温测水信息表");
        // 表头标题
        HSSFCellStyle titleStyle = getStyle(workbook, 22, 2, true, false);
        HSSFCellStyle titleStyle1 = getStyle(workbook, 11, 1, false, false);
        HSSFCellStyle titleStyle2 = getStyle(workbook, 11, 3, false, false);
        HSSFCellStyle titleStyle3 = getStyle(workbook, 11, 2, false, true);
        //样式自动换行
        titleStyle3.setWrapText(true);

        sheet.setColumnWidth(0, 12 * 283);
        sheet.setColumnWidth(1, 12 * 283);
        sheet.setColumnWidth(2, 12 * 283);
        sheet.setColumnWidth(3, 15 * 283);
        sheet.setColumnWidth(4, 9 * 283);
        sheet.setColumnWidth(5, 9 * 283);
        sheet.setColumnWidth(6, 9 * 283);
        sheet.setColumnWidth(7, 11 * 283);
        sheet.setColumnWidth(8, 11 * 283);
        sheet.setColumnWidth(9, 11 * 283);

        try {
            rows = sheet.createRow(0);
            createCell(workbook, sheet, rows, titleStyle, 50 * 20, "测温测水信息表", 0, 0, 0, 7);
            /* createCell(workbook, sheet, rows, titleStyle1, 28 * 20, " ", 1, 1, 9, 9);*/
            rows = sheet.createRow(1);
            createCell(workbook, sheet, rows, titleStyle3, 14 * 20, "电缆号", 1, 3, 0, 0);
            createCell(workbook, sheet, rows, titleStyle3, 14 * 20, "层数", 1, 3, 1, 1);
            createCell(workbook, sheet, rows, titleStyle3, 14 * 20, "第一组(温度)", 1, 3, 2, 2);
            createCell(workbook, sheet, rows, titleStyle3, 14 * 20, "第一组(水分)", 1, 3, 3, 3);
            createCell(workbook, sheet, rows, titleStyle3, 14 * 20, "第二组(温度)", 1, 3, 4, 4);
            createCell(workbook, sheet, rows, titleStyle3, 14 * 20, "第二组(水分)", 1, 3, 5, 5);
            createCell(workbook, sheet, rows, titleStyle3, 14 * 20, "第三组(温度)", 1, 3, 6, 6);
            createCell(workbook, sheet, rows, titleStyle3, 14 * 20, "第三组(水分)", 1, 3, 7, 7);
            for (int i = 0; i < list.size(); i++) {
                rows = sheet.createRow(4 + i);
                createCell(workbook, sheet, rows, titleStyle3, 18 * 20, list.get(i).getCableName(), 4 + i, 4 + i, 0, 0);
                createCell(workbook, sheet, rows, titleStyle3, 18 * 20, "温度/水分", 4 + i, 4 + i, 1, 1);

                createCell(workbook, sheet, rows, titleStyle3, 18 * 20, String.valueOf(list.get(i).getDatas().get(0).getTemperature()), 4 + i, 4 + i, 2, 2);
                createCell(workbook, sheet, rows, titleStyle3, 18 * 20, String.valueOf(list.get(i).getDatas().get(0).getHumidity()), 4 + i, 4 + i, 3, 3);

                createCell(workbook, sheet, rows, titleStyle3, 18 * 20, String.valueOf(list.get(i).getDatas().get(1).getTemperature()), 4 + i, 4 + i, 4, 4);
                createCell(workbook, sheet, rows, titleStyle3, 18 * 20, String.valueOf(list.get(i).getDatas().get(1).getHumidity()), 4 + i, 4 + i, 5, 5);

                createCell(workbook, sheet, rows, titleStyle3, 18 * 20, String.valueOf(list.get(i).getDatas().get(2).getTemperature()), 4 + i, 4 + i, 6, 6);
                createCell(workbook, sheet, rows, titleStyle3, 18 * 20, String.valueOf(list.get(i).getDatas().get(2).getHumidity()), 4 + i, 4 + i, 7, 7);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return workbook;
    }








    public static InputStream getInputStream(String path) {
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(path);
            if (url == null) {
                httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setConnectTimeout(3000);
                httpURLConnection.setRequestMethod("POST");
                int responseCode = httpURLConnection.getResponseCode();
                if (responseCode == 200) {
                    inputStream = httpURLConnection.getInputStream();
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        return inputStream;

    }





    //str 是单元格需要放入的 字符串 fontCountInline 是该单元格每行多少个汉字 全角为1 英文或符号为0.5
    public static float getExcelCellAutoHeight(String str, float fontCountInline) {
        float defaultRowHeight = 12.00f;//每一行的高度指定
        float defaultCount = 0.00f;
        for (int i = 0; i < str.length(); i++) {
            float ff = getregex(str.substring(i, i + 1));
            defaultCount = defaultCount + ff;
        }
        return ((int) (defaultCount / fontCountInline) + 1) * defaultRowHeight;//计算
    }

    public static float getregex(String charStr) {

        if (charStr == " ") {
            return 0.5f;
        }
        // 判断是否为字母或字符
        if (Pattern.compile("^[A-Za-z0-9]+$").matcher(charStr).matches()) {
            return 0.5f;
        }
        // 判断是否为全角

        if (Pattern.compile("[\u4e00-\u9fa5]+$").matcher(charStr).matches()) {
            return 1.00f;
        }
        //全角符号 及中文
        if (Pattern.compile("[^x00-xff]").matcher(charStr).matches()) {
            return 1.00f;
        }
        return 0.5f;

    }

    /*====================================Excel导出结束=======================================================*/
    /* 自用工具类 */



    /**
     * 创建行元素
     *
     * @param height 行高
     * @param row1   起始行
     * @param row2   结束行
     * @param col1   起始列
     * @param col2   结束列
     */
    public static void createCell(HSSFWorkbook wb, HSSFSheet sheet, HSSFRow rows, HSSFCellStyle titleStyle, int height, String name, int row1, int row2, int col1, int col2) {
        //设置行高
        rows.setHeight((short) height);
        HSSFCell cell = rows.createCell(col1);
        cell.setCellValue(name);
        //设置从第row1行合并到第row2行，第col1列合并到col2列
        CellRangeAddress cra = new CellRangeAddress(row1, row2, col1, col2);
        sheet.addMergedRegion(cra);
        if (row1 != row2 || col1 != col2) {
            // 使用RegionUtil类为合并后的单元格添加边框
            if(titleStyle.getBorderBottom()>0){
                RegionUtil.setBorderBottom(1, cra, sheet, wb); // 下边框
            }else{
                RegionUtil.setBorderBottom(0, cra, sheet, wb); // 下边框
            }
            if(titleStyle.getBorderLeft()>0){
                RegionUtil.setBorderLeft(1, cra, sheet, wb); // 左边框
            }else{
                RegionUtil.setBorderLeft(0, cra, sheet, wb); // 左边框
            }
            if(titleStyle.getBorderTop()>0){
                RegionUtil.setBorderTop(1, cra, sheet, wb); // 上边框
            }else{
                RegionUtil.setBorderTop(0, cra, sheet, wb); // 上边框
            }
            if(titleStyle.getBorderRight()>0){
                RegionUtil.setBorderRight(1, cra, sheet, wb); // 右边框
            }else{
                RegionUtil.setBorderRight(0, cra, sheet, wb); // 右边框
            }

        }
        cell.setCellStyle(titleStyle);
    }

    /**
     * 创建样式
     *
     * @param fontSize 字体大小
     * @param align    水平位置  默认1居左 左右居中2 居右3 垂直均为居中
     * @param bold     是否加粗
     * @return
     */
    public static HSSFCellStyle getStyle(HSSFWorkbook workbook, int fontSize, int align, boolean bold, boolean border) {
        HSSFFont font = workbook.createFont();
        font.setFontName("宋体");
        // 字体大小
        font.setFontHeightInPoints((short) fontSize);
        if (bold) {
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        }
        HSSFCellStyle style = workbook.createCellStyle();
//        //自动换行
//        style.setRotation((short) 255);
        //设置字体
        style.setFont(font);
        // 左右居中2 居右3 默认居左
        style.setAlignment((short) align);
        // 上下居中1
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        if (border) {
            style.setBorderRight((short) 1);
            style.setBorderLeft((short) 1);
            style.setBorderBottom((short) 1);
            style.setBorderTop((short) 1);
            style.setLocked(true);
        }
        return style;
    }

    /**
     * 创建表体数据
     *
     * @param data      表体数据
     * @param cellStyle 样式
     * @param height    行高
     * @param startRow  开始行
     * @param colKeys   值对应map的key
     */
    public static void setCellData(List<Map> data, HSSFSheet sheet, HSSFCellStyle cellStyle, int height, int startRow, String[] colKeys) {
        // 创建数据
        HSSFRow row = null;
        HSSFCell cell = null;
        int i = startRow;

        if (data != null && data.size() > 0) {
            for (Map<String, String> rowData : data) {
                row = sheet.createRow(i);
                row.setHeight((short) height);
                int j = 0;
                for (String key : colKeys) {
                    Object colValue = rowData.get(key);
                    cell = row.createCell(j);
                    cell.setCellStyle(cellStyle);
                    if (colValue != null) {
                        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                        cell.setCellValue(colValue.toString());
                    }
                    j++;
                }
                i++;
            }
        }
    }

    /*====================================Excel导入读取=======================================================*/
    public static Workbook createWorkBookByType(File myFile) throws Exception {
        String fileName = myFile.getName();
        String fileType = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length());
        InputStream is = null;
        try {
            is = new FileInputStream(myFile);
            if (fileType.equals("xls")) {
                return new HSSFWorkbook(is);
            } else if (fileType.equals("xlsx")) {
                return new XSSFWorkbook(is);
            }
        } catch (Exception e) {
            throw new Exception();
        } finally {
            if (is != null) {
                is.close();
            }
        }
        return null;
    }

    public static Workbook createWorkBookByType(MultipartFile myFile) throws Exception {
        String fileName = myFile.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length());
        InputStream is = null;
        try {
            is = myFile.getInputStream();
            if (fileType.equals("xls")) {
                return new HSSFWorkbook(is);
            } else if (fileType.equals("xlsx")) {
                return new XSSFWorkbook(is);
            }
        } catch (Exception e) {
            throw new Exception();
        } finally {
            if (is != null) {
                is.close();
            }
        }
        return null;
    }

    /**
     * 获取单元格的值
     *
     * @param sheet
     * @param row
     * @param rowNum
     * @param j
     * @return
     */
    public static String getCellValue(Sheet sheet, Row row, int rowNum, int j) {
        if (null == row.getCell(j)) {
            return " ";
        }
        // 判断单元格是否是合并单元格
        boolean isMerge = isMergedRegion(sheet, rowNum, row.getCell(j).getColumnIndex());
        // 单元格的值
        String cellVal = null;
        if (isMerge) {
            cellVal = getMergedRegionValue(sheet, row.getRowNum(), row.getCell(j).getColumnIndex());
        } else {
            cellVal = row.getCell(j) == null ? " " : getCellValue(row.getCell(j));
        }
        return cellVal;
    }
    
    public static String getMergedRegionValue(Sheet sheet, int row, int column) {
        // 获得一个sheet中合并单元格的数量
        int sheetMergeCount = sheet.getNumMergedRegions();

        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress ca = sheet.getMergedRegion(i);
            int firstColumn = ca.getFirstColumn();
            int lastColumn = ca.getLastColumn();
            int firstRow = ca.getFirstRow();
            int lastRow = ca.getLastRow();
            if (row >= firstRow && row <= lastRow) {
                if (column >= firstColumn && column <= lastColumn) {
                    Row fRow = sheet.getRow(firstRow);
                    Cell fCell = fRow.getCell(firstColumn);
                    return getCellValue(fCell);
                }
            }
        }
        return " ";
    }

    public static String getCellValue(Cell cell) {

        if (cell == null)
            return " ";

        if (cell.getCellType() == Cell.CELL_TYPE_STRING) {

            return cell.getStringCellValue();

        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {

            return String.valueOf(cell.getBooleanCellValue());

        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {

            return cell.getCellFormula();

        } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            DecimalFormat df = new DecimalFormat("#0.00");
            return df.format(cell.getNumericCellValue()).indexOf(".00") > 0
                    ? df.format(cell.getNumericCellValue()).split("\\.00")[0] : df.format(cell.getNumericCellValue());
        }
        return "";
    }

    /**
     * 判断指定的单元格是否是合并单元格
     *
     * @param sheet
     * @param row    行下标
     * @param column 列下标
     * @return
     */
    private static boolean isMergedRegion(Sheet sheet, int row, int column) {
        int sheetMergeCount = sheet.getNumMergedRegions();
        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress range = sheet.getMergedRegion(i);
            int firstColumn = range.getFirstColumn();
            int lastColumn = range.getLastColumn();
            int firstRow = range.getFirstRow();
            int lastRow = range.getLastRow();
            if (row >= firstRow && row <= lastRow) {
                if (column >= firstColumn && column <= lastColumn) {
                    return true;
                }
            }
        }
        return false;
    }


    /*====================================Excel导入读取结束=======================================================*/
}
