package com.jiayue.insu.incloud.pushdata;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.HMac;
import cn.hutool.crypto.digest.HmacAlgorithm;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
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.BJZYYJYSDPushDqDataParamsDto;
import com.jiayue.insu.incloud.constants.enums.QNHLEnum;
import com.jiayue.insu.incloud.constants.enums.StatusEnum;
import com.jiayue.insu.incloud.constants.vo.ResponseSDVo;
import com.jiayue.insu.incloud.entity.ForecastData;
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 com.jiayue.insu.incloud.utils.FileUtils;
import com.jiayue.insu.incloud.utils.HttpUtils;
import com.jiayue.insu.incloud.utils.SFTPUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.VelocityContext;
import org.checkerframework.checker.units.qual.A;
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.ParseException;
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 PushDataForBJZYYJYSD implements IPushInitForecastData {
    @Autowired
    private RecordService recordService;
    @Autowired
    private IntegrationCompanyService integrationCompanyService;
    @Autowired
    BJZYYJYSDComPermisson bjzyyjysdComPermisson;

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

    /**
     * 推送原始预测数据
     *
     * @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_BJZYYJY_SD);

        if (StrUtil.isNotEmpty(station.getComKey()) && LocalDateTime.now().isBefore(station.getKeyTime())) {
            // 获取场站编号
            String stationCode = station.getStationCode();
            Record record = new Record(CommonStant.RECORD_TYPE_PUSH_INIT, CompanyConstant.COMPANY_BJZYYJY_SD, 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 = bjzyyjysdFilePath + 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");
            List<List<List<Object>>> vList = new ArrayList<>();

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

            List<List<Object>> lists = new ArrayList<>();
            int i = 0;
            // 循环解析原始短期文件
            for (String originalContent : originalContents) {

                // 从有#的数据开始获取 数据示例：#1	帽子山光伏电站	2023-06-22 00:00:00	0.0
                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格式
                    long time;
                    try {
                        String[] dayHuor = originalContentArr[2].split(" ");
                        String day = dayHuor[0];
                        String huor = dayHuor[1];
                        if (!daysList.contains(day) && !huor.equals("00:00:00")) {
                            if (i != 0) {
                                vList.add(lists);
                            }
                            if (station.getDays() == i) {
                                break;
                            }
                            daysList.add(day);
                            lists = new ArrayList<>();
                            i++;
                        }
                        time = simpleDateFormat.parse(originalContentArr[2]).getTime();
                        List<Object> list = new ArrayList<>();
                        list.add(time);
                        list.add(originalContentArr[3]);
                        lists.add(list);

                    } catch (Exception e) {
                        e.printStackTrace();
                        break;
                    }
                }
            }

            BJZYYJYSDPushDqDataParamsDto dto = new BJZYYJYSDPushDqDataParamsDto(station.getSignCode(), daysList.get(0), "syjy", simpleDateFormat.format(new Date()), daysList, vList);

            JSONObject json = JSONUtil.parseObj(dto, false);
            String body = json.toString();

            try {
                String response;
                HttpRequest httpRequest = HttpRequest.post(integrationCompany.getPushUrl())
                        .header("Content-Type", "application/x-www-form-urlencoded")
                        .header("Authorization", "Bearer " + station.getComKey())
                        .header("TENANT-ID", "4").
                                body(body);
                httpRequest.setGlobalTimeout(20000);
                response = httpRequest.execute().body();

                ResponseSDVo responseSDVo = JSONUtil.toBean(response, ResponseSDVo.class);

                if (responseSDVo.getCode().equals("0")) {

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

        return false;
    }

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


}
