package com.cpp.web.controller.reportData;

import com.cpp.common.core.domain.R;
import com.cpp.system.service.ISysConfigService;
import com.cpp.web.domain.datafactory.ParsingLog;
import com.cpp.web.domain.datafactory.enums.FileTypeEnum;
import com.cpp.web.domain.enums.DataSourcesEnum;
import com.cpp.web.domain.station.ElectricField;
import com.cpp.web.service.datafactory.ParsingLogService;
import com.cpp.web.service.reprtdata.ReportDataService;
import com.cpp.web.service.station.ElectricFieldService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequiredArgsConstructor
@RequestMapping("reportData")
public class ReportDataController {

    private final ElectricFieldService electricFieldService;

    private final ParsingLogService parsingLogService;

    private final ReportDataService reportDataService;

    private final ISysConfigService iSysConfigService;

    private static final SimpleDateFormat TIMESTAMP_FORMAT = new SimpleDateFormat("yyyyMMddHHmm");


    /**
     * 获取文件类型
     *
     * @return
     */
    @GetMapping("/getElectricFieldTypeEnum")
    public R getFileType(String stationCode) {
        ElectricField electricField = electricFieldService.findByStationCode(stationCode);
        return R.ok(electricField.getElectricFieldTypeEnum());
    }

    /**
     * 上报数据查询
     *
     * @param stationCode
     * @param fileType
     * @return
     */
    @GetMapping("/getData")
    public R getData(String stationCode, String fileType, Long startTime, Long endTime) {

        // 获取场站类型
        ElectricField electricField = electricFieldService.findByStationCode(stationCode);

        String electricFieldTypeEnum = electricField.getElectricFieldTypeEnum();

        List<FileTypeEnum> fileTypeEnumList = new ArrayList<>();
        List<ParsingLog> resultList = new ArrayList<>();

        if (null == fileType) {
            if (electricFieldTypeEnum.equals("E1")) {
                fileTypeEnumList = FileTypeEnum.getPhotovoltaicFileType();
            } else {
                fileTypeEnumList = FileTypeEnum.getWindFileType();
            }
            List<ParsingLog> parsingLogList = new ArrayList<>();
            for (FileTypeEnum fileTypeEnum : fileTypeEnumList) {
                parsingLogList = getAllFileName(fileTypeEnum.name(), startTime, endTime, stationCode);
                resultList.addAll(parsingLogList);
            }
        } else {
            resultList = getAllFileName(fileType, startTime, endTime, stationCode);
        }

        // 定义比较器
        Comparator<ParsingLog> timestampComparator = new Comparator<ParsingLog>() {
            @Override
            public int compare(ParsingLog o1, ParsingLog o2) {
                try {
                    Date firstDate = TIMESTAMP_FORMAT.parse(extractAndParseTimestamp(o1.getFileName()));
                    Date nextDate = TIMESTAMP_FORMAT.parse(extractAndParseTimestamp(o2.getFileName()));
                    return nextDate.compareTo(firstDate);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
        };
        // 排序
        Collections.sort(resultList, timestampComparator);
        return R.ok(resultList);
    }

    /**
     * 提取文件名中的时间
     *
     * @param fileName
     * @return
     */
    private static String extractAndParseTimestamp(String fileName) {
        String[] fileNameParts = fileName.split("_");
        String correctTimestampStr = "";
        if (fileName.contains("NWP")) {
            correctTimestampStr = fileNameParts[1] + "0000".trim();
        } else {
            correctTimestampStr = fileNameParts[1] + fileNameParts[2];
        }

        return correctTimestampStr;
    }

    public List<ParsingLog> getAllFileName(String fileType, Long startTime, Long endTime, String stationCode) {
        List<ParsingLog> resultList = new ArrayList<>();
        String rCdqKey = iSysConfigService.selectConfigByKey("sync_regulation");
        // 获取应上报文件名
        List<String> shouldFileName = reportDataService.shouldFileName(fileType, startTime, endTime, stationCode,rCdqKey);
        List<ParsingLog> parsingLogList = parsingLogService.findByTimeBetweenAndFileTypeAndStationCode(new Date(startTime), new Date(endTime), fileType, stationCode);
        if (parsingLogList.size() > 0) {
            resultList.addAll(parsingLogList);
            for (String s : shouldFileName) {
                List<ParsingLog> collectList = parsingLogList.stream().filter(f -> f.getFileName().contains(s)).collect(Collectors.toList());
                if (collectList.size() == 0) {
                    ParsingLog parsingLogs = new ParsingLog();

                    if ("rdq".equals(fileType) || "dq".equals(fileType) || "nwp".equals(fileType)) {
                        parsingLogs.setFileName("sign_" + s + "_0000_" + fileType.toUpperCase() + ".WPD");
                    }
                    if (!rCdqKey.equals("true")){
                        if ("rcdq".equals(fileType) || "cdq".equals(fileType) || "status".equals(fileType) || "nbq".equals(fileType) || "qxz".equals(fileType) || "rp".equals(fileType) || "fj".equals(fileType) || "cft".equals(fileType)) {
                            parsingLogs.setFileName("sign_" + s + "_" + fileType.toUpperCase() + ".WPD");
                        }
                    }else {
                        if ("cdq".equals(fileType) || "status".equals(fileType) || "nbq".equals(fileType) || "qxz".equals(fileType) || "rp".equals(fileType) || "fj".equals(fileType) || "cft".equals(fileType)) {
                            parsingLogs.setFileName("sign_" + s + "_" + fileType.toUpperCase() + ".WPD");
                        }
                    }

                    parsingLogs.setFileType(FileTypeEnum.valueOf(fileType));
                    parsingLogs.setParsingFileStatus("失败");
                    parsingLogs.setStationCode(stationCode);
                    parsingLogs.setDataSources(DataSourcesEnum.E1);
                    resultList.add(parsingLogs);

                }
            }
        } else {
            for (int i = 0; i < shouldFileName.size(); i++) {
                ParsingLog parsingLogs = new ParsingLog();
                if ("rdq".equals(fileType) || "dq".equals(fileType) || "nwp".equals(fileType)) {
                    parsingLogs.setFileName("sign_" + shouldFileName.get(i) + "_0000_" + fileType.toUpperCase() + ".WPD");
                }
                if ("rcdq".equals(fileType) || "cdq".equals(fileType) || "status".equals(fileType) || "nbq".equals(fileType) || "qxz".equals(fileType) || "rp".equals(fileType) || "fj".equals(fileType) || "cft".equals(fileType)) {
                    parsingLogs.setFileName("sign_" + shouldFileName.get(i) + "_" + fileType.toUpperCase() + ".WPD");
                }
                parsingLogs.setParsingFileStatus("失败");
                parsingLogs.setStationCode(stationCode);
                parsingLogs.setFileType(FileTypeEnum.valueOf(fileType));
                parsingLogs.setDataSources(DataSourcesEnum.E1);
                resultList.add(parsingLogs);
            }
        }
        return resultList;
    }
}
