package com.jiayue.insu.inclientqn.pulldata;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jiayue.insu.inclientqn.constant.CommonStant;
import com.jiayue.insu.inclientqn.entity.*;
import com.jiayue.insu.inclientqn.inenum.StatusEnum;
import com.jiayue.insu.inclientqn.service.*;
import com.jiayue.insu.inclientqn.util.DateTimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 拉取飔合科技修正数据from一体化云端（飔合科技）
 *
 * @author yh
 * @version 1.0
 * @since 2022/5/22 11:29
 */
@Component
@Slf4j
@RefreshScope
public class PullInitDataSH implements IPullInitForecastDataSH {

    @Autowired
    private RecordService recordService;
    @Autowired
    private CorrforeStService corrforeStService;
    @Value("${minio.pull.url}")
    String url;
    @Value("${minio.pull.fileurl}")
    String fileurl;
    @Value("${minio.fileurl}")
    String fileDir;

    /**
     * 拉取短期修正数据（飔合科技）
     *
     * @param station 场站信息
     */
    @Override
    public List<CorrforeSt> pullDQData(Station station) {

        Record record = new Record();
        LocalDateTime localDateTime = LocalDateTimeUtil.beginOfDay(LocalDateTime.now());
        record.setStationCode(station.getStationCode());
        record.setTime(localDateTime);
        record.setCreateTime(LocalDateTime.now());
        record.setType(CommonStant.RECORD_TYPE_PULL_INIT);
        log.info("开始从一体化云请求飔合科技修正数据 --> {}" + station.getStationCode());
        // 下载地址
        String postUrl = station.getDownloadurl();
        List<CorrforeSt> list = new ArrayList<>();
        Map<String, Object> mapBody = new HashMap<>();
        mapBody.put("wfId", station.getStationCode());
        mapBody.put("init_time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(DateTimeUtils.getDayStartTime(System.currentTimeMillis()))).toString());
        try {
            HttpRequest httpRequest = HttpRequest.post(postUrl)
                    .header("Content-Type", "application/json")
                            .header("Authorization",station.getUsername()+":"+station.getComKey());
            httpRequest.setGlobalTimeout(20000);
            String body = httpRequest.body(JSONUtil.toJsonStr(mapBody)).execute().body();
            JSONObject json = JSONUtil.parseObj(body);
            String code = json.get("code").toString();
            String data = json.get("data").toString();
            if (code.equals("200") && data.length() > 0) {
                // 如果data = null 则用原始数据进行上报
                if (!"[]".equals(data)) {
                    list = correctData(data);
                    // 如果修正后短期数据不为0
                    if (list.size() > 0) {
                        // 将修正数据存库
                        corrforeStService.updateBetweenForecastTime(list.get(0).getTimeFormat(), list.get(list.size() - 1).getTimeFormat(),list);
                    }
                } else {
                    // 存入记录
                    record.setState(StatusEnum.CONNECT_RESPONSE_CONTENT_NULL.getCode());
                    record.setStateContent(StatusEnum.CONNECT_RESPONSE_CONTENT_NULL.getMsg());
                }

            } else {
                record.setState(StatusEnum.RESPONSE_FAIL.getCode());
                log.error("请求飔合科技修正数据 --> {} 失败，失败原因:{}", station.getStationCode(), StatusEnum.RESPONSE_FAIL.getMsg());
            }
        } catch (Exception e) {
            record.setState(StatusEnum.RESPONSE_FAIL.getCode());
            log.error("请求飔合科技修正数据 --> {} 失败，失败原因:{}", station.getStationCode(), StatusEnum.RESPONSE_FAIL.getMsg());
            e.printStackTrace();

        }

        recordService.save(record);
        return list;
    }


    /**
     * 数据解析
     *
     * @param data 待解析数据
     * @return
     * @throws Exception
     */
    public List<CorrforeSt> correctData(String data) throws Exception {

        List<CorrforeSt> list = new ArrayList<>();
        data = data.substring(1, data.length() - 1);
        String[] content = data.split("(?<=})\\s*,\\s*");

        for (int i = 0; i < content.length; i++) {
            CorrforeSt corrforeSt = new CorrforeSt();
            String column = content[i];
            //JSON 字符串转换为一个树状结构
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(column);
            // 通过键名获取相应的值
            String forecastTime = rootNode.get("time").asText();
            double ageValue = rootNode.get("power").asDouble();
            // 将预测时间转换为时间戳格式
            Long forecast = DateUtil.parse(forecastTime, "yyyy-MM-dd HH:mm:ss").getTime();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String forecastDateFormat = dateFormat.format(new Date(forecast));
            // 存入实体
            corrforeSt.setForecastTime(forecast);
            corrforeSt.setCorrectTime(DateUtil.parse(dateFormat.format(new Date()), "yyyy-MM-dd HH:mm:ss").toTimestamp().toLocalDateTime());
            corrforeSt.setTimeFormat(DateUtil.parse(forecastDateFormat, "yyyy-MM-dd HH:mm:ss").toTimestamp().toLocalDateTime());
            corrforeSt.setFpValue(isNumberOrNull(String.valueOf(ageValue)));
            list.add(corrforeSt);
        }
        // 排序
        Collections.sort(list, Comparator.comparing(CorrforeSt::getForecastTime));
        return list;
    }


    /**
     * 判断是否是NULL 和是否是数值
     *
     * @param data
     * @return
     */
    public BigDecimal isNumberOrNull(String data) {
        BigDecimal bigDecimal = new BigDecimal("-99");
        if (!data.contains("null") && !data.contains("NULL")) {
            Pattern pattern = Pattern.compile("-[0-9]+(.[0-9]+)?|[0-9]+(.[0-9]+)?");
            Matcher isNum = pattern.matcher(data);
            try {
                if (isNum.matches()) {
                    bigDecimal = new BigDecimal(data).setScale(2, BigDecimal.ROUND_DOWN);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return bigDecimal;
    }

    /**
     * 关闭文件流
     *
     * @param bufferedReader 字符数据
     * @param read           字节流
     */
    private void close(BufferedReader bufferedReader, InputStreamReader read) {
        try {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
            if (read != null) {
                read.close();
            }
        } catch (IOException e) {
            log.error("关闭文件流失败:", e);
        }
    }


}
