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

        Map<String,Object> map = new HashMap<>();

        String electricFieldType = electricFieldService.findByStationCode(stationCode).getElectricFieldTypeEnum();

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

        if (null == fileType)
            fileType = "";

        resultList.addAll(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);
        map.put("data",resultList);
        map.put("type",electricFieldType);
        return R.ok(map);
    }

    /**
     * 提取文件名中的时间
     *
     * @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, rCdqKey);
        Map<String, List<String>> map = reportDataService.getFileResults(fileType, startTime, endTime, stationCode);
        List<ParsingLog> parsingLogList = parsingLogService.findByTimeBetweenAndFileTypeAndStationCode(new Date(startTime), new Date(endTime), fileType, stationCode);
        if ("".equals(rCdqKey) || "true".equals(rCdqKey)) {
            map.remove("rcdq");
        }
        if (parsingLogList.size() > 0) {
            resultList.addAll(parsingLogList);
            for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                for (String item : entry.getValue()) {
                    List<ParsingLog> collectList = parsingLogList.stream().filter(f -> f.getFileName().contains(item) && f.getFileType().equals(FileTypeEnum.valueOf(entry.getKey()))//
                    ).collect(Collectors.toList());
                    if (collectList.size() == 0) {
                        resultList.add(collectRecords(entry.getKey(), rCdqKey, stationCode, item));
                    }
                }
            }
        } else if ("".equals(fileType)) {
            for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                List<String> value = entry.getValue();
                for (String item : value) {
                    resultList.add(collectRecords(entry.getKey(), rCdqKey, stationCode, item));
                }
            }
        } else {
            for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                List<String> value = entry.getValue();
                for (String item : value) {
                    resultList.add(collectRecords(fileType, rCdqKey, stationCode, item));
                }
            }
        }

        return resultList;

    }

    /**
     * 拼接未上报文件名
     *
     * @param fileType
     * @param rCdqKey
     * @param stationCode
     * @param str
     * @return
     */
    public ParsingLog collectRecords(String fileType, String rCdqKey, String stationCode, String str) {
        ParsingLog parsingLogs = new ParsingLog();

        List<String> rdqTypes = Arrays.asList("rdq", "dq", "nwp");
        List<String> rcdqTypes = Arrays.asList("rcdq", "cdq", "status", "nbq", "qxz", "rp", "fj", "cft");

        if (rdqTypes.contains(fileType)) {
            parsingLogs.setFileName("sign_" + str + "_0000_" + fileType.toUpperCase() + ".WPD");
        } else if (!"true".equals(rCdqKey) && !"".equals(rCdqKey)) {
            if (rcdqTypes.contains(fileType)) {
                parsingLogs.setFileName("sign_" + str + "_" + fileType.toUpperCase() + ".WPD");
            }
        } else if (rcdqTypes.stream().filter(t -> !"rcdq".equals(t)).collect(Collectors.toList()).contains(fileType)) {
            parsingLogs.setFileName("sign_" + str + "_" + fileType.toUpperCase() + ".WPD");
        }

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

        return parsingLogs;
    }
}
