package com.testor.module.partner.model.dto;

/**
 * @title TestDemo1
 * @description <TODO description class purpose>
 * @Author: qiao
 * @version:1.0.0
 * @create：4/14/23 4:19 PM
 */
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.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class TestDemo1 {
    public static void main(String[] args) throws Exception {
        readExcelFile();
    }

    private static void readExcelFile() throws Exception {
        File file = new File("/Users/baifugui/Downloads/相关方人员批量导入模版（证件照片可先不导出，客户要求再说）的副本.xlsx");
        if (!file.exists()) {
            throw new Exception("文件不存在!");
        }
        InputStream in = Files.newInputStream(file.toPath());

        // 读取整个Excel
        XSSFWorkbook sheets = new XSSFWorkbook(in);
        // 获取第一个表单Sheet
        XSSFSheet sheetAt = sheets.getSheetAt(0);

        //默认第一行为标题行，i = 0
        XSSFRow titleRow = sheetAt.getRow(0);
        Map<String, String> teacherIdAwardMoney = new HashMap<>();
        Map<String, ArrayList<String>> teacherCenterMap = new HashMap<>();
        ArrayList<String> centers = new ArrayList<>();

        String money = null;
        // 读取每一行
        for (int i = 1; i < sheetAt.getPhysicalNumberOfRows(); i++) {
            XSSFRow row = sheetAt.getRow(i);
            // 说明第一次添加
            if (null == teacherIdAwardMoney.get(String.valueOf(row.getCell(1)))) {
                money =String.valueOf(row.getCell(2));
                centers.add(String.valueOf(row.getCell(3)));
            } else {
                money =String.valueOf(row.getCell(2)) + teacherIdAwardMoney.get(String.valueOf(row.getCell(1)));
                centers = mergeTwoList(teacherCenterMap.get(String.valueOf(row.getCell(1))), String.valueOf(row.getCell(3)));
            }
            teacherCenterMap.put(String.valueOf(row.getCell(1)), centers);
            teacherIdAwardMoney.put(String.valueOf(row.getCell(1)), money);
//            // 奖励老师
//            String teacherId = getCellValue(row.getCell(1));
//            // 奖励金额
//            String awordMoney = getCellValue(row.getCell(2));
            // 是否是合并单元格
            boolean isMerge = isMergedRegion(sheetAt, i, 3);
            String team = "";
            if (isMerge) {
                team = getMergedRegionValue(sheetAt, row.getRowNum(), 3);
            } else {
                team = getCellValue(row.getCell(3)).toString();
            }
            System.out.print(team);
            System.out.println();
        }
    }

    private static ArrayList<String> mergeTwoList(ArrayList<String> strings, String center) {
        ArrayList<String> combineList = new ArrayList<>(strings);
        combineList.add(center);
        return combineList;
    }

    /**
     * 判断指定的单元格是否是合并单元格
     *
     * @param sheet
     * @param row    行下标
     * @param column 列下标
     * @return
     */
    private static boolean isMergedRegion(Sheet sheet, int row, int column) {
        //获取该sheet所有合并的单元格
        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;
    }

    /**
     * 获取合并单元格的值
     *
     * @param sheet  sheet索引 从0开始
     * @param row    行索引 从0开始
     * @param column 列索引  从0开始
     * @return
     */
    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 getCellValue(fCell);
                }
            }
        }
        return null;
    }

    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) {

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

        }
        return "";
    }


}

