package com.bonus.sgzb.base.service.impl;// ExcelServiceImpl.java
import com.bonus.sgzb.base.domain.MaPartType;
import com.bonus.sgzb.base.domain.MapType;
import com.bonus.sgzb.base.mapper.ExcelMapper;
import com.bonus.sgzb.base.service.ExcelService;
import com.bonus.sgzb.common.security.utils.SecurityUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@Service
public class ExcelServiceImpl implements ExcelService {

    @Autowired
    ExcelMapper excelMapper;


    /*
     * 将读取的excel文件转为
     * */
    @Override
    public Map<String, Map<String, List<MapType>>> readExcelFile(String filePath) {

        FileInputStream excelFile = null;
        Workbook workbook = null;
        try {
            excelFile = new FileInputStream(new File(filePath));
            workbook = new XSSFWorkbook(excelFile);
            Sheet datatypeSheet = workbook.getSheetAt(0);
            Iterator<Row> iterator = datatypeSheet.iterator();

            Map<String, Map<String, List<MapType>>> level3Relation = new HashMap<>();

            while (iterator.hasNext()) {
                Row currentRow = iterator.next();
                if (currentRow.getRowNum() == 0) {
                    // 校验模板
                    Cell zeroLevelCell = currentRow.getCell(0);
                    Cell firstLevelCell = currentRow.getCell(1);
                    Cell secondLevelCell = currentRow.getCell(2);
                    Cell thirdLevelCell = currentRow.getCell(3);
                    Cell fourthLevelCell = currentRow.getCell(4);
                    Cell fifthLevelCell = currentRow.getCell(5);
                    String zeroLevel = getCellValueAsString(zeroLevelCell);
                    String firstLevel = getCellValueAsString(firstLevelCell);
                    String secondLevel = getCellValueAsString(secondLevelCell);
                    String thirdLevel = getCellValueAsString(thirdLevelCell);
                    String fourthLevel = getCellValueAsString(fourthLevelCell);
                    String fifthLevel = getCellValueAsString(fifthLevelCell);
                    if (!(zeroLevel.equals("序号"))){
                        throw new RuntimeException("导入模板不正确");
                    }
                    if (!(firstLevel.equals("配件类型"))){
                        throw new RuntimeException("导入模板不正确");
                    }
                    if (!(secondLevel.equals("配件名称"))){
                        throw new RuntimeException("导入模板不正确");
                    }
                    if (!(thirdLevel.equals("规格型号"))){
                        throw new RuntimeException("导入模板不正确");
                    }
                    if (!(fourthLevel.equals("单位"))){
                        throw new RuntimeException("导入模板不正确");
                    }
                    if (!(fifthLevel.equals("价格"))){
                        throw new RuntimeException("导入模板不正确");
                    }
                    continue;
                }

                Cell firstLevelCell = currentRow.getCell(1);
                Cell secondLevelCell = currentRow.getCell(2);
                Cell thirdLevelCell = currentRow.getCell(3);
                Cell fourthLevelCell = currentRow.getCell(4);
                Cell fifthLevelCell = currentRow.getCell(5);
                Cell sixthLevelCell = currentRow.getCell(6);
                if (sixthLevelCell != null){
                    throw new RuntimeException("导入模板不正确");
                }

                String firstLevel = getCellValueAsString(firstLevelCell);
                String secondLevel = getCellValueAsString(secondLevelCell);

                MapType thirdLevel = new MapType();
                thirdLevel.setPaName(getCellValueAsString(thirdLevelCell));
                thirdLevel.setUnitId(getCellValueAsString(fourthLevelCell));
                thirdLevel.setBuyPrice(new BigDecimal(getCellValueAsString(fifthLevelCell)));

                // 检查是否所有三个级别都是空白
                if (firstLevel.isEmpty() || secondLevel.isEmpty() || thirdLevel == null) {
                    continue; // 跳过这一行
                }

                // 检查是否已经存在相同的组合
                boolean isDuplicate = false;
                for (String key : level3Relation.keySet()) {
                    Map<String, List<MapType>> secondLevelMap = level3Relation.get(key);
                    for (String key2 : secondLevelMap.keySet()) {
                        List<MapType> thirdLevelList = secondLevelMap.get(key2);
                        if (key.equals(firstLevel) && key2.equals(secondLevel) && thirdLevelList.contains(thirdLevel)) {
                            isDuplicate = true;
                            break;
                        }
                    }
                    if (isDuplicate) break;
                }

                if (!isDuplicate) {
                    // 如果不是重复项，则添加到映射中
                    Map<String, List<MapType>> secondLevelMap = level3Relation.computeIfAbsent(firstLevel, k -> new HashMap<>());
                    List<MapType> thirdLevelList = secondLevelMap.computeIfAbsent(secondLevel, k -> new ArrayList<>());
                    thirdLevelList.add(thirdLevel);
                }
            }
            printLevel3Relation(level3Relation);

            return level3Relation;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("Error reading Excel file", e);
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (excelFile != null) {
                try {
                    excelFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private String getCellValueAsString(Cell cell) {
        if (cell == null) return "";
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return String.valueOf(cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            case BLANK:
                return "";
            default:
                return "";
        }
    }

    private void printLevel3Relation(Map<String, Map<String, List<MapType>>> level3Relation) {
        for (Map.Entry<String, Map<String, List<MapType>>> firstLevel : level3Relation.entrySet()) {
            System.out.println("level_1: " + firstLevel.getKey());
            MaPartType maPartType_level1 = excelMapper.selectMa(firstLevel.getKey(),0);
            if (Objects.nonNull(maPartType_level1)) {
                loopInner(firstLevel, maPartType_level1.getPaId());
            } else {
                MaPartType maPartType = new MaPartType();
                maPartType.setPaName(firstLevel.getKey());
                maPartType.setCreateBy(SecurityUtils.getLoginUser().getUserid().toString());
                maPartType.setParentId(0L);
                maPartType.setLevel("1");
                excelMapper.insertPaName(maPartType);//如果第一层在数据库中查询不到则插入数据，并且读取到parent_id
                loopInner(firstLevel, maPartType.getPaId());
            }
        }
    }

    private void loopInner(Map.Entry<String, Map<String, List<MapType>>> firstLevel, long firstLevelId) {
        for (Map.Entry<String, List<MapType>> secondLevel : firstLevel.getValue().entrySet()) {
            System.out.println("\tlevel_2: " + secondLevel.getKey());
            MaPartType maPartType_level2 = excelMapper.selectMa(secondLevel.getKey(),firstLevelId);
            if (Objects.nonNull(maPartType_level2)) {
                looplevel3(secondLevel, maPartType_level2.getPaId());
            } else {
                MaPartType maPartType = new MaPartType();
                maPartType.setPaName(secondLevel.getKey());
                maPartType.setCreateBy(SecurityUtils.getLoginUser().getUserid().toString());
                maPartType.setParentId(firstLevelId);
                maPartType.setLevel("2");
                excelMapper.insertPaName(maPartType);//如果第一层在数据库中查询不到则插入数据，并且读取到parent_id
                looplevel3(secondLevel, maPartType.getPaId());
            }
        }
    }

    private void looplevel3(Map.Entry<String, List<MapType>> secondLevel, long secondLevelId) {
        for (MapType thirdLevel : secondLevel.getValue()) {
            System.out.println("\t\tlevel_3: " + thirdLevel);
            MaPartType maPartType_level3 = excelMapper.selectMa(thirdLevel.getPaName(),secondLevelId);
            if (Objects.isNull(maPartType_level3)) {
                MaPartType maPartType = new MaPartType();
                maPartType.setPaName(thirdLevel.getPaName());
                maPartType.setCreateBy(SecurityUtils.getLoginUser().getUserid().toString());
                maPartType.setUnitId(thirdLevel.getUnitId());
                maPartType.setBuyPrice(thirdLevel.getBuyPrice());
                maPartType.setParentId(secondLevelId);
                maPartType.setLevel("3");
                excelMapper.insertPaName(maPartType);//如果第一层在数据库中查询不到则插入数据，并且读取到parent_id
            }
        }
    }

}
