package com.jiayue.insu.incloud.pushdata;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jiayue.insu.incloud.compermisson.BJZYYJYSDComPermisson;
import com.jiayue.insu.incloud.constants.CommonStant;
import com.jiayue.insu.incloud.constants.CompanyConstant;
import com.jiayue.insu.incloud.constants.dto.SHKJLNPushDqDataParamsDto;
import com.jiayue.insu.incloud.constants.enums.StatusEnum;
import com.jiayue.insu.incloud.constants.vo.ResponseSHLNVo;
import com.jiayue.insu.incloud.entity.IntegrationCompany;
import com.jiayue.insu.incloud.entity.Record;
import com.jiayue.insu.incloud.entity.Station;
import com.jiayue.insu.incloud.service.IntegrationCompanyService;
import com.jiayue.insu.incloud.service.RecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 飔合科技（科技）上送数据
 *
 * @author yh
 * @version 1.0
 * @since 2022/5/22 11:29
 */
@Component
@Slf4j
public class PushDataForSH implements IPushInitForecastData {
    @Autowired
    private RecordService recordService;
    @Autowired
    private IntegrationCompanyService integrationCompanyService;
    @Autowired
    BJZYYJYSDComPermisson bjzyyjysdComPermisson;

    @Value("${localFilePath.shFilePath}")
    String shkjlnFilePath;

    /**
     * 推送原始预测数据
     *
     * @param station 场站信息
     * @return 是否成功
     */
    @Override
    public Boolean pushDQAndNWPData(Station station) {
        return null;
    }

    /**
     * 将下载好的原始短期文件通过sftp推送
     *
     * @param station
     * @return
     */
    @Override
    public Boolean pushDQData(Station station) {

        IntegrationCompany integrationCompany = integrationCompanyService.findByCode(CompanyConstant.COMPANY_SHKJ_LN);
        // 获取场站编号
        String stationCode = station.getStationCode();
        Record record = new Record(CommonStant.RECORD_TYPE_PUSH_INIT, CompanyConstant.COMPANY_SHKJ_LN, stationCode, null, LocalDateTimeUtil.beginOfDay(LocalDateTime.now()), LocalDateTime.now(), null, null);
        record.setState(StatusEnum.SUCCESS.getSign());
        // 如果场站编号为空，则返回
        if (stationCode == null || "".equals(stationCode)) {
            record.setState(StatusEnum.STATION_CODE_NULL.getSign());
            record.setStateContent(StatusEnum.STATION_CODE_NULL.getMsg());
            recordService.save(record);
            return false;
        }
        // 获取指定目录下的短期原始数据(/jiayue/insu/file/init/J00269/)
        String filePath = shkjlnFilePath + stationCode + File.separatorChar;
        File files = new File(filePath);
        String[] fileNames = files.list();
        // 如果文件名列表为空
        if (fileNames == null || fileNames.length == 0) {
            log.info("指定目录下无文件");
            record.setState(StatusEnum.FILE_NULL.getSign());
            record.setStateContent(StatusEnum.FILE_NULL.getMsg());
            recordService.save(record);
            return false;
        }
        // 获取当天日期
        LocalDateTime today = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        DateTimeFormatter formatterSeparator = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String todaySeparatorStr = today.format(formatterSeparator);
        String tomorrowSeparatorStr = today.plusDays(1).format(formatterSeparator);
        String todayStr = today.format(formatter);
        // 转为list并根据日期筛选排序
        List<String> fileList = Arrays.stream(fileNames).collect(Collectors.toList());
        List<String> filterFileList = fileList.stream().filter(s -> s.contains(todayStr)).filter(s -> s.contains("DQ")).collect(Collectors.toList());
        // 如果筛选后无文件
        if (filterFileList.size() == 0) {
            log.info("无当日文件");
            record.setState(StatusEnum.FILE_NULL.getSign());
            record.setStateContent(StatusEnum.FILE_NULL.getMsg());
            recordService.save(record);
            return false;
        }
        filterFileList.sort(Collections.reverseOrder());
        // 获取原始文件
        File originalFile = new File(filterFileList.get(0));
        // 读取文件
        FileReader fileReader = new FileReader(filePath + originalFile);
        List<String> originalContents = fileReader.readLines();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<SHKJLNPushDqDataParamsDto.DataPointDTO> list = new ArrayList<>();

        List<String> daysList = new ArrayList<>();


        int i = 0;
        // 循环解析原始短期文件
        for (String originalContent : originalContents) {
            // 飔合上送数据开始时间为第二天的00:15:00
            if (originalContent.contains("#")) {
                // 刨除当天的数据
                if (originalContent.contains(todaySeparatorStr) || originalContent.contains(tomorrowSeparatorStr + " 00:00:00")) {
                    continue;
                }
                // 根据分隔符分割，取时间和功率
                String[] originalContentArr = originalContent.split("\t");

                // 如果分割后的数组长度小于4，则数据格式不正确
                if (originalContentArr.length < 4) {
                    continue;
                }
                // 将时间2023-06-22 00:00:00根据分隔分割并组成2023-06-22_00:00:00格式
                try {
                    String[] dayHour = originalContentArr[2].split(" ");
                    String day = dayHour[0];
                    String hour = dayHour[1];
                    if (!daysList.contains(day) && !hour.equals("00:00:00")) {
                        if (station.getDays() == i) {
                            break;
                        }
                        daysList.add(day);
                        i++;
                    }

                    SHKJLNPushDqDataParamsDto.DataPointDTO dto = new SHKJLNPushDqDataParamsDto.DataPointDTO();
                    dto.setPower(Double.valueOf(originalContentArr[3]));
                    if (simpleDateFormat.format(simpleDateFormat.parse(originalContentArr[2]).getTime()).toString().contains("00:00:00")){
                        dto.setTime(timeFormat(simpleDateFormat.parse(originalContentArr[2])));
                    }else {
                        dto.setTime(simpleDateFormat.format(simpleDateFormat.parse(originalContentArr[2]).getTime()));
                    }
                    list.add(dto);
                } catch (Exception e) {
                    e.printStackTrace();
                    break;
                }
            }
        }
        String stationId = station.getSignCode();
        SHKJLNPushDqDataParamsDto dto = new SHKJLNPushDqDataParamsDto(stationId, dateFormat.format(new Date()), list);
//        SHKJLNPushDqDataParamsDto dto = new SHKJLNPushDqDataParamsDto("2109001", dateFormat.format(new Date()), list);

        JSONObject json = JSONUtil.parseObj(dto, false);
        String body = json.toString();
        String dataPushUrl = integrationCompany.getPushUrl();
//        String dataPushUrl = "http://127.0.0.1:4523/m1/3002439-0-default/dataservice.tradingthink.cn/api/thirdDatasourceSync/syjy/push_power_forecast";
        try {
            String response;
            HttpRequest httpRequest = HttpRequest.post(dataPushUrl)
                    .header("Content-Type", "application/json")
                    .header("DATA_SERVICE_TOKEN","eed451be-fe36-4d2a-a3b0-85cc440b406f");
            httpRequest.setGlobalTimeout(20000);
            response = httpRequest.body(body).execute().body();

            ResponseSHLNVo responseSHLNVo = JSONUtil.toBean(response, ResponseSHLNVo.class);
            if (responseSHLNVo.getCode().equals("200")) {
                record.setState(StatusEnum.SUCCESS.getSign());
                record.setStateContent(responseSHLNVo.getMessage());
                log.info("=========={}:{} ==>上送短期原始数据成功  {}天==========", integrationCompany.getName(), station.getStationCode(), daysList.size());
//                log.info("{} 原始数据:{}", stationCode, body);
                recordService.save(record);
                return true;
            } else {
                log.error("=========={}:{} ==>上送数据失败 失败标识:{} ,失败原因：{} ==========", integrationCompany.getName(), station.getStationCode(), responseSHLNVo.getCode(), responseSHLNVo.getMessage());
//                log.info("{} 原始数据:{}", stationCode, body);
                record.setState(StatusEnum.FILE_NULL.getSign());
                record.setStateContent(responseSHLNVo.getMessage());
                recordService.save(record);
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Boolean pushNWPData(Station station) {
        return null;
    }


    public String timeFormat(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        if (calendar.get(Calendar.HOUR_OF_DAY) == 0 && calendar.get(Calendar.MINUTE) == 0 && calendar.get(Calendar.SECOND) == 0) {
            // 回到前一天
            calendar.add(Calendar.DAY_OF_MONTH, -1);

            // 设置时间为前一天的23:59:59
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
        }
        // 格式化日期时间为字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String endTimeString = sdf.format(calendar.getTime());


        String nonStandardEndTimeString = endTimeString.replaceFirst("23:59:59", "24:00:00");
        return nonStandardEndTimeString;
    }

}
