package com.xjrsoft.module.classtime.service.impl;

import com.github.yulichang.base.MPJBaseServiceImpl;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.xjrsoft.common.exception.MyException;
import com.xjrsoft.module.classtime.entity.ClassTimeStatistics;
import com.xjrsoft.module.classtime.entity.ClassTimeStatisticsRecord;
import com.xjrsoft.module.classtime.mapper.ClassTimeStatisticsRecordMapper;
import com.xjrsoft.module.classtime.service.IClassTimeStatisticsRecordService;
import com.xjrsoft.module.classtime.service.IClassTimeStatisticsService;
import lombok.AllArgsConstructor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
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.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
* @title: 课时统计
* @Author dzx
* @Date: 2024-09-26
* @Version 1.0
*/
@Service
@AllArgsConstructor
public class ClassTimeStatisticsServiceRecordImpl extends MPJBaseServiceImpl<ClassTimeStatisticsRecordMapper, ClassTimeStatisticsRecord> implements IClassTimeStatisticsRecordService {
    private final IClassTimeStatisticsService statisticsService;
    /**
     * 导出教师的明细
     * @return
     */
    @Override
    public byte[] recordDetailExportQuery(Long id) throws IOException {
        try {

        }catch(Exception e){
            log.error(e.getMessage());
            throw new MyException("导出失败，请联系管理员");
        }

        ClassTimeStatisticsRecord record = this.getById(id);
        ClassTimeStatistics statistics = statisticsService.getById(record.getClassTimeStatisticsId());

        String allClassTimeData = record.getAllClassTimeData();
        JsonParser parser = new JsonParser();
        JsonObject allClassTimeDataJson = parser.parse(allClassTimeData).getAsJsonObject();
        JsonArray data = allClassTimeDataJson.get("data").getAsJsonArray();
        JsonArray rowTitle = allClassTimeDataJson.get("rowTitle").getAsJsonArray();
        int allColumnNumber = rowTitle.size() + 2;//表格最大列号
        //总的数据
        Map<Integer, Map<Integer, JsonObject>> dataMap = new LinkedHashMap<>();

        //1、组装execel表头
        Map<Integer, JsonObject> cellJsonMap = new LinkedHashMap<>();//表头第一行
        Map<Integer, JsonObject> lastRowMap = new LinkedHashMap<>();//最后一行数据
        int rowNumber = 0;

        JsonObject cellJson = new JsonObject();
        cellJson.addProperty("content", "课程名称(计算课时)");
        cellJson.addProperty("adjustType", "title");
        cellJsonMap.put(rowNumber, cellJson);

        JsonObject lastRowJson = new JsonObject();
        lastRowJson.addProperty("content", "合计(课时)");
        lastRowJson.addProperty("adjustType", "");
        lastRowMap.put(rowNumber, lastRowJson);
        rowNumber ++;

        Map<Integer, String> columnNumberMap = new LinkedHashMap<>();

        for (JsonElement jsonElement : rowTitle) {
            JsonObject rowTitleJson = jsonElement.getAsJsonObject();
            String scheduleDate = rowTitleJson.get("scheduleDate").getAsString();
            cellJson = new JsonObject();
            cellJson.addProperty("content", scheduleDate);
            cellJson.addProperty("adjustType", "title");
            cellJsonMap.put(rowNumber, cellJson);

            lastRowJson = new JsonObject();
            lastRowJson.addProperty("content", rowTitleJson.get("content").getAsString());
            lastRowJson.addProperty("adjustType", "");
            lastRowMap.put(rowNumber, lastRowJson);


            columnNumberMap.put(rowNumber, statistics.getYear() +"-" + scheduleDate.replace(".", "-"));
            rowNumber ++;
        }

        cellJson = new JsonObject();
        cellJson.addProperty("content", "合计(课时)");
        cellJson.addProperty("adjustType", "title");
        cellJsonMap.put(rowNumber, cellJson);
        dataMap.put(0, cellJsonMap);

        lastRowJson = new JsonObject();
        lastRowJson.addProperty("content", allClassTimeDataJson.get("allClassTime").getAsString());
        lastRowJson.addProperty("adjustType", "");
        lastRowMap.put(rowNumber, lastRowJson);


        //数据
        JsonArray columnTitle = allClassTimeDataJson.get("columnTitle").getAsJsonArray();
        int allRowNumber = columnTitle.size() + 2;//表格最大行号
        dataMap.put(allRowNumber - 1, lastRowMap);

        for (int i = 0; i < columnTitle.size(); i ++){
            JsonElement columnElement = columnTitle.get(i);
            JsonObject columnJson = columnElement.getAsJsonObject();

            Map<Integer, JsonObject> dataCellJsonMap = new LinkedHashMap<>();
            //左边第一列
            JsonObject dataCellJson = new JsonObject();
            String type = columnJson.get("type").getAsString();
            dataCellJson.addProperty("content", type);
            dataCellJson.addProperty("adjustType", "");
            dataCellJsonMap.put(0, dataCellJson);

            for (Integer j : columnNumberMap.keySet()) {
                String scheduleDate = columnNumberMap.get(j);
                for (JsonElement datum : data) {
                    JsonObject dataJson = datum.getAsJsonObject();
                    if(type.equals(dataJson.get("type").getAsString()) && scheduleDate.equals(dataJson.get("scheduleDate").getAsString())){
                        dataCellJson = new JsonObject();
                        dataCellJson.addProperty("content", dataJson.get("content").getAsString());
                        dataCellJson.addProperty("adjustType", dataJson.get("adjustType").getAsString());
                        dataCellJsonMap.put(j, dataCellJson);
                    }
                }
            }

            //右边最后一列
            dataCellJson = new JsonObject();
            dataCellJson.addProperty("content", columnJson.get("content").getAsString());
            dataCellJson.addProperty("adjustType", "");
            dataCellJsonMap.put(allColumnNumber - 1, dataCellJson);

            dataMap.put(i + 1, dataCellJsonMap);
        }

        // 创建一个新的工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建一个工作表(sheet)
        String sheetName = "数据";
        Sheet sheet = workbook.createSheet(sheetName);


        // 创建一个字体对象
        Font font = workbook.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short)12);

        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());//设置背景颜色
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);//设置填充模式
        cellStyle.setFont(font);
        cellStyle.setBorderTop(BorderStyle.THIN);
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);

        //最一个合计的代码
        CellStyle lastCellStyle = workbook.createCellStyle();
        lastCellStyle.setFillForegroundColor(IndexedColors.SKY_BLUE.getIndex());//设置背景颜色
        lastCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);//设置填充模式
        lastCellStyle.setBorderTop(BorderStyle.THIN);
        lastCellStyle.setBorderBottom(BorderStyle.THIN);
        lastCellStyle.setBorderLeft(BorderStyle.THIN);
        lastCellStyle.setBorderRight(BorderStyle.THIN);
        lastCellStyle.setFont(font);

        for (Integer i : dataMap.keySet()) {
            Row row = sheet.createRow(i);
            Map<Integer, JsonObject> rowData = dataMap.get(i);
            for (int j = 0; j < allColumnNumber; j ++) {
                sheet.autoSizeColumn(j);
                Cell cell = row.createCell(j);
                JsonObject jsonObject = rowData.get(j);
                if(jsonObject == null){
                    cell.setCellValue("");
                    CellStyle contentCellStyle = workbook.createCellStyle();
                    contentCellStyle.setFont(font);
                    contentCellStyle.setWrapText(true);
                    contentCellStyle.setBorderTop(BorderStyle.THIN);
                    contentCellStyle.setBorderBottom(BorderStyle.THIN);
                    contentCellStyle.setBorderLeft(BorderStyle.THIN);
                    contentCellStyle.setBorderRight(BorderStyle.THIN);
                    cell.setCellStyle(contentCellStyle);
                }else{
                    cell.setCellValue(jsonObject.get("content").getAsString().replace(",","\r\n"));
                    String adjustType = jsonObject.get("adjustType").getAsString();
                    if("title".equals(adjustType)){
                        cell.setCellStyle(cellStyle);
                    }else if("course_substitute".equals(adjustType)){
                        CellStyle contentCellStyle = workbook.createCellStyle();
                        contentCellStyle.setFont(font);
                        contentCellStyle.setWrapText(true);
                        contentCellStyle.setBorderTop(BorderStyle.THIN);
                        contentCellStyle.setBorderBottom(BorderStyle.THIN);
                        contentCellStyle.setBorderLeft(BorderStyle.THIN);
                        contentCellStyle.setBorderRight(BorderStyle.THIN);
                        contentCellStyle.setFillForegroundColor(IndexedColors.RED1.getIndex());
                        contentCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);//设置填充模式
                        cell.setCellStyle(contentCellStyle);
                    }else if("course_exchange".equals(adjustType)){
                        CellStyle contentCellStyle = workbook.createCellStyle();
                        contentCellStyle.setFont(font);
                        contentCellStyle.setWrapText(true);
                        contentCellStyle.setBorderTop(BorderStyle.THIN);
                        contentCellStyle.setBorderBottom(BorderStyle.THIN);
                        contentCellStyle.setBorderLeft(BorderStyle.THIN);
                        contentCellStyle.setBorderRight(BorderStyle.THIN);
                        contentCellStyle.setFillForegroundColor(IndexedColors.YELLOW1.getIndex());
                        contentCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);//设置填充模式
                        cell.setCellStyle(contentCellStyle);
                    }else{
                        CellStyle contentCellStyle = workbook.createCellStyle();
                        contentCellStyle.setFont(font);
                        contentCellStyle.setWrapText(true);
                        contentCellStyle.setBorderTop(BorderStyle.THIN);
                        contentCellStyle.setBorderBottom(BorderStyle.THIN);
                        contentCellStyle.setBorderLeft(BorderStyle.THIN);
                        contentCellStyle.setBorderRight(BorderStyle.THIN);
                        cell.setCellStyle(contentCellStyle);
                    }
                }

                if(i == allRowNumber - 1 &&  j == allColumnNumber - 1){
                    cell.setCellStyle(lastCellStyle);
                }
            }
        }

        //写入文件
        ByteArrayOutputStream bot = new ByteArrayOutputStream();
        workbook.write(bot);
        return bot.toByteArray();
    }
}
