package com.zhgd.xmgl.util;

import com.zhgd.jeecg.common.mybatis.EntityMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * @program: wisdomSite
 * @description: excel处理工具类
 * @author: Mr.Peng
 * @create: 2021-08-16 17:42
 **/
@Slf4j
public class ExcelUtils {

    public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        workbook.write(response.getOutputStream());
    }

    public static List<Map<String, String>> jxlExlToList(InputStream is, int index) throws Exception {
        Workbook book = null;
        List<Map<String, String>> list = null;
        String companyId = null;
        //Map<String,Object> map=new HashMap<>();
        try {
            book = WorkbookFactory.create(is);
            //book = new XSSFWorkbook(is);// 创建一个新的写入工作簿
            Sheet sheet = book.getSheetAt(0);
            //int totalRows = sheet.getLastRowNum();
            int totalRows = sheet.getPhysicalNumberOfRows();
            //int totalColumns = sheet.getColumns();
            Row xssfRow = sheet.getRow(index);
            int totalColumns = xssfRow.getLastCellNum();
            if (totalColumns <= 0) {
                return null;
            }
            //读取指定行作为Map中的key
            List<String> tableHeaderlist = new ArrayList<>();
            for (int i = 0; i < totalColumns; i++) {
                String value = getCellValue(sheet, xssfRow.getCell(i));
                if (tableHeaderlist.contains(value)) {
                    value = value + "(1)";
                }
                if (StringUtils.isNotEmpty(value)) {
                    value = value.replaceAll("[\\t\\n\\r]", "");
                }
                tableHeaderlist.add(value);
            }
            //将指定行后面每一行存为Map集合，然后存为list
            list = new ArrayList<>();
            Map<String, String> rowData = new LinkedHashMap<>();
            int start = 1 + index;
            for (int i = start; i < totalRows; i++) {
                xssfRow = sheet.getRow(i);
                rowData = new LinkedHashMap<>(totalColumns);

                for (int j = 0; j < xssfRow.getLastCellNum(); j++) {
                    if (j < totalColumns) {
                        if (StringUtils.isNotEmpty(tableHeaderlist.get(j).toString())) {
                            if (xssfRow.getCell(j) != null) {
                                String value = getCellValue(sheet, xssfRow.getCell(j));
                                rowData.put(tableHeaderlist.get(j).toString(), value);
                            } else {
                                rowData.put(tableHeaderlist.get(j).toString(), "");
                            }
                        }
                    }
                }
                if (rowData.size() > 0) {
                    list.add(rowData);
                }

            }

            log.info("工作簿读取数据成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public static String getMergedRegionValue(Sheet sheet, int row, int column) {
        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 getValue(fCell);
                }
            }
        }
        return null;
    }

    /**
     * 判断指定的单元格是否是合并单元格
     *
     * @param sheet  工作表
     * @param row    行下标
     * @param column 列下标
     * @return
     */
    public 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;
    }

    public static String getValue(Cell hssfCell) {
        if (hssfCell.getCellTypeEnum() == CellType.BOOLEAN) {
            return String.valueOf(hssfCell.getBooleanCellValue());
        } else if (hssfCell.getCellTypeEnum() == CellType.NUMERIC) {
            //if (HSSFDateUtil.isCellDateFormatted(hssfCell)) {
            if (CellDateUtil.isCellDateFormatted(hssfCell)) {
                Date date = hssfCell.getDateCellValue();
                return DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss");
            } else {
                hssfCell.setCellType(CellType.STRING);
                return String.valueOf(hssfCell.getStringCellValue());
            }
        } else if (hssfCell.getCellTypeEnum() == CellType.STRING) {
            return String.valueOf(hssfCell.getStringCellValue());
        } else {
            hssfCell.setCellType(CellType.STRING);
            return String.valueOf(hssfCell.getStringCellValue());
        }
    }

    /**
     * 获取合并单元格的值
     *
     * @param sheet
     * @param cell
     * @return
     */
    public static String getCellValue(Sheet sheet, Cell cell) {
        String value = "";
        if (cell != null) {
            //log.info("-----------row:" +cell.getRowIndex()+"-------column:"+cell.getColumnIndex());
            int row = cell.getRowIndex();
            int column = cell.getColumnIndex();
            boolean temp = isMergedRegion(sheet, row, column);

            if (temp) {
                value = getMergedRegionValue(sheet, row, column);
            } else {
                value = getValue(cell);
            }
        }
        return value;
    }

    public static void exportAttendanceExcel(HttpServletResponse response) {
        try {
            ClassPathResource classPathResource = new ClassPathResource("excel/人员考勤导入模板.xlsx");
            InputStream inputStream = classPathResource.getInputStream();
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            downLoadExcel("人员考勤导入模板.xlsx", response, workbook);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void exportHiddenDangerLibraryExcel(HttpServletResponse response) {
        try {
            ClassPathResource classPathResource = new ClassPathResource("excel/安全隐患库_导入模板.xlsx");
            InputStream inputStream = classPathResource.getInputStream();
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            downLoadExcel("安全隐患库_导入模板.xlsx", response, workbook);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void exportInspectTableLibraryExcel(HttpServletResponse response) {
        try {
            ClassPathResource classPathResource = new ClassPathResource("excel/检查表导入模板.xlsx");
            InputStream inputStream = classPathResource.getInputStream();
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            downLoadExcel("检查表导入模板.xlsx", response, workbook);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void exporExcelWorkerTemplate(HttpServletResponse response, List<EntityMap> teamList, List<EntityMap> departmentList) {
        try {
            ClassPathResource classPathResource = new ClassPathResource("excel/人员导入模板.xlsx");
            InputStream inputStream = classPathResource.getInputStream();
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            if (teamList.size() > 0) {
                XSSFSheet sheet2 = workbook.getSheet("班组");
                for (int i = 0; i < teamList.size(); i++) {
                    XSSFRow row1 = sheet2.createRow(i);
                    XSSFCell cell1 = row1.createCell(0);
                    cell1.setCellType(CellType.STRING);
                    cell1.setCellValue(MapUtils.getString(teamList.get(i), "enterpriseTeamName"));
                    XSSFCell cell2 = row1.createCell(1);
                    cell2.setCellType(CellType.STRING);
                    cell2.setCellValue(MapUtils.getString(teamList.get(i), "enterpriseTeamId"));
                }
            }
            if (departmentList.size() > 0) {
                XSSFSheet sheet2 = workbook.getSheet("部门");
                for (int i = 0; i < departmentList.size(); i++) {
                    XSSFRow row1 = sheet2.createRow(i);
                    XSSFCell cell1 = row1.createCell(0);
                    cell1.setCellType(CellType.STRING);
                    cell1.setCellValue(MapUtils.getString(departmentList.get(i), "enterpriseDepartmentName"));
                    XSSFCell cell2 = row1.createCell(1);
                    cell2.setCellType(CellType.STRING);
                    cell2.setCellValue(MapUtils.getString(departmentList.get(i), "enterpriseDepartmentId"));
                }
            }
            downLoadExcel("人员导入模板.xlsx", response, workbook);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*public static void main(String[] args) {
        try {
            InputStream instream = new FileInputStream("D:/qqq.xlsx");
            XSSFWorkbook workbook = new XSSFWorkbook(instream);
            XSSFSheet sheet = workbook.getSheetAt(0);
            XSSFCell cell=sheet.getRow(0).getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
            log.info("项目："+cell.getStringCellValue());
            XSSFCell cell2=sheet.getRow(3).getCell(8, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
            log.info("评估时间："+getValue(cell2));
            XSSFCell cell3=sheet.getRow(10).getCell(10, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
            log.info("实测实量得分："+getValue(cell3));
            XSSFCell cell4=sheet.getRow(14).getCell(10, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
            log.info("质量风险得分："+getValue(cell4));
            XSSFCell cell5=sheet.getRow(23).getCell(10, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
            log.info("安全文明得分："+getValue(cell5));
            XSSFCell cell6=sheet.getRow(32).getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
            log.info("标段评估结果："+getValue(cell6));
            workbook.close();
            instream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/

}
