package com.jiayue.insu.inclientqn.service.client;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.BJZYYJYSDCorrfore;
import com.jiayue.insu.inclientqn.entity.CorrectUltraShortTerm;
import com.jiayue.insu.inclientqn.entity.Record;
import com.jiayue.insu.inclientqn.entity.Station;
import com.jiayue.insu.inclientqn.inenum.QNHLEnum;
import com.jiayue.insu.inclientqn.inenum.StatusEnum;
import com.jiayue.insu.inclientqn.mapper.BJZYYJYSDCorrforeMapper;
import com.jiayue.insu.inclientqn.model.WXResponseVo;
import com.jiayue.insu.inclientqn.permisson.com.BJZYYJYSDComPermisson;
import com.jiayue.insu.inclientqn.permisson.com.WXComPermisson;
import com.jiayue.insu.inclientqn.pulldata.IPullInitForecastData;
import com.jiayue.insu.inclientqn.service.BJZYYJYSDCorrforeService;
import com.jiayue.insu.inclientqn.service.CorrectUltraShortTermService;
import com.jiayue.insu.inclientqn.service.RecordService;
import com.jiayue.insu.inclientqn.service.StationService;
import com.jiayue.insu.inclientqn.util.DateTimeUtils;
import com.jiayue.insu.inclientqn.util.SystermUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @description:
 * @author: yuanhao
 * @createDate: 2021/9/27
 * @version: 1.0
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class WXCorrforeService extends ServiceImpl<BJZYYJYSDCorrforeMapper, BJZYYJYSDCorrfore> {

    private final RecordService recordService;
    private final StationService stationService;
    private final VelocityEngine velocityEngine;
    private final CorrectUltraShortTermService correctUltraShortTermService;
    private final WXComPermisson wxComPermisson;

    /**
     * 武穴一体化请求超短期修正数据
     *
     * @param station
     * @return
     */
    public boolean downLoadCorrforeData(Station station, Long time) {
        //标记为要生成超短期的时刻
        LocalDateTime signLDT = LocalDateTimeUtil.of(time).plusMinutes(15L);

        // 初始化操作记录
        Record record = new Record();
        record.setType(CommonStant.RECORD_TYPE_PULL_CORRECT);
        // 此处借用清能枚举，不新增武穴枚举
        record.setContent(QNHLEnum.DATA_CORRULTRSHOR_TYPE.getCode());
        record.setStationCode(station.getStationCode());
        record.setTime(signLDT);
        record.setCreateTime(LocalDateTime.now());

        // 获取下载路径
        String dataPullUrl = station.getDownloadurl();
        // 获取token地址
        String token = station.getComKey();
        // 如果token为空或者token失效，从新获取token
        LocalDateTime tokenTime = station.getKeyTime();
        if (StrUtil.isEmpty(token) || LocalDateTime.now().isAfter(tokenTime)) {
            if (wxComPermisson.generateKey(station)) {
                station = stationService.findThis();
                token = station.getComKey();
                tokenTime = station.getKeyTime();
            }
        }

        boolean result = false;
        boolean isUpload = false;
        String response;
        List<CorrectUltraShortTerm> list = new ArrayList<>();
        // 如果token为不为空并且者token未失效
        if (StrUtil.isNotEmpty(token) && LocalDateTime.now().isBefore(tokenTime)) {
            try {
                // 实装请求参数
                Long datetime = DateTimeUtils.getMomentTime(System.currentTimeMillis(), 2, 15 * 60 * 1000L);
                String stationId = station.getStationCode();
                Map<String, Object> map = new HashMap<>();
                map.put("stationId",stationId);
                map.put("datetime", datetime.toString());
                // 发送请求
                HttpRequest httpRequest = HttpRequest.post(dataPullUrl)
                        .header("Content-Type", "application/json")
                        .header("loginToken", token);
                httpRequest.setGlobalTimeout(120000);
                // 因本地测试相应时间30s左右，故设置读取超时间50s
                httpRequest.setReadTimeout(50000);

                response = httpRequest.body(JSONUtil.toJsonStr(map)).execute().body();
                // 如果响应不为空
                if (StrUtil.isNotEmpty(response)) {
                    boolean isJson = JSONUtil.isJsonObj(response);
                    // 如果返回结果是json类型
                    if (isJson) {
                        WXResponseVo wxResponseVo = JSONUtil.toBean(response, WXResponseVo.class);
                        String code = wxResponseVo.getStatusCode();
                        // 如果调用结果成功
                        if (code.equals("1000")) {
                            log.info(station.getStationCode() + " 武穴超短期请求修正内容为:{}", response);
                            try {
                                // 如果data = null 则用原始数据进行上报
                                if (!"{}".equals(wxResponseVo.getData())) {
                                    list = correctData(wxResponseVo.getData(), signLDT);
                                    /**************检测解析数据完整性*******************/
                                    // 如果修正后超短期数据不为0
                                    if (list.size() > 0) {
                                        // 生成超短期修正后文件
                                        if (genFile(station, list)) {
                                            result = true;
                                            // 存入记录文件已经生成过
                                            record.setState(CommonStant.RECORD_TYPE_PULL_CORRECT);
                                            record.setStateContent(StatusEnum.SUCCESS.getCode());
                                        }
                                    }
                                } else {
                                    // 存入记录
                                    record.setState(StatusEnum.CONNECT_RESPONSE_CONTENT_NULL.getCode());
                                    record.setStateContent(StatusEnum.CONNECT_RESPONSE_CONTENT_NULL.getMsg());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                record.setState(StatusEnum.CONNECT_RESPONSE_FORMAT_ERROR.getSign());
                                record.setStateContent("解析超短期或生成文件失败");
                                log.error("========== 解析超短期或生成文件失败 ");
                            }

                            if (result) {
                                log.info("========== 拉取超短期修正数据成功！ ==========");
                                record.setState(StatusEnum.SUCCESS.getSign());
                                record.setStateContent(String.valueOf(list.size()));
                            }

                        } else {
                            record.setState(StatusEnum.RESPONSE_FAIL.getSign());
                            record.setStateContent(StatusEnum.RESPONSE_FAIL.getMsg());
                            log.error("========== 拉取超短期修正数据失败 响应码异常 " + station.getStationCode() + " :请求超短期修正数据返回内容:" + response);
                        }
                    } else {
                        record.setState(StatusEnum.CONNECT_RESPONSE_FORMAT_ERROR.getSign());
                        record.setStateContent(StatusEnum.CONNECT_RESPONSE_FORMAT_ERROR.getMsg());
                        log.error("========== 拉取超短期修正数据失败 接收响应字符串非json格式 ");
                    }
                } else {
                    record.setState(StatusEnum.CONNECT_RESPONSE_CONTENT_NULL.getSign());
                    record.setStateContent(StatusEnum.CONNECT_RESPONSE_CONTENT_NULL.getMsg());
                    log.error("========== 拉取超短期修正数据失败  返回响应内容为空 ==========");
                }

            } catch (Exception e) {
                record.setState(StatusEnum.CONNECT_ERROR.getSign());
                record.setStateContent(StatusEnum.CONNECT_ERROR.getMsg());
                log.error("========== 请求超短期修正数据失败 连接断开或请求超时 ==========");
                e.printStackTrace();

            }
        }
        recordService.save(record);
        return isUpload;
    }


    /**
     * 数据解析
     *
     * @param data 待解析数据
     * @return
     * @throws Exception
     */
    public List<CorrectUltraShortTerm> correctData(String data, LocalDateTime signTime){
        List<CorrectUltraShortTerm> list = new ArrayList<>();
        // 解析JSON字符串为JSONObject
        JSONObject jsonObject = new JSONObject(data);

        // 获取stationId和datetime
        String stationId = jsonObject.getStr("stationId");
        String datetime = jsonObject.getStr("datetime");

        // 获取fix数组并遍历
        JSONArray fixArray = jsonObject.getJSONArray("fix");
        for (int i = 0; i < fixArray.size(); i++) {
            JSONObject fixObject = fixArray.getJSONObject(i);
            Iterator<String> keys = fixObject.keySet().iterator();
            while (keys.hasNext()) {
                CorrectUltraShortTerm correctUltraShortTerm = new CorrectUltraShortTerm();
                String key = keys.next(); // 时间戳
                correctUltraShortTerm.setForecastTime(LocalDateTimeUtil.of(Long.valueOf(key)));
                correctUltraShortTerm.setSignTime(signTime);
                correctUltraShortTerm.setPassTime(LocalDateTime.now());
                correctUltraShortTerm.setRequestTime(LocalDateTime.now());
                correctUltraShortTerm.setStationCode(String.valueOf(stationId));
                Double value = fixObject.getDouble(key);
                // 武穴返回来的数据是需要上报的值，不是系数
                correctUltraShortTerm.setCorrectValue(new BigDecimal(value));
//                correctUltraShortTerm.setRatio(new BigDecimal(1));
                list.add(correctUltraShortTerm);
            }
        }
        JSONArray scaleArray = jsonObject.getJSONArray("scale");
        for (int i = 0; i < scaleArray.size(); i++) {
            JSONObject scaleObject = scaleArray.getJSONObject(i);
            Iterator<String> keys = scaleObject.keySet().iterator();
            while (keys.hasNext()) {
                CorrectUltraShortTerm correctUltraShortTerm = new CorrectUltraShortTerm();
                String key = keys.next();
                correctUltraShortTerm.setForecastTime(LocalDateTimeUtil.of(Long.valueOf(key)));
                correctUltraShortTerm.setSignTime(signTime);
                correctUltraShortTerm.setPassTime(LocalDateTime.now());
                correctUltraShortTerm.setRequestTime(LocalDateTime.now());
                correctUltraShortTerm.setStationCode(String.valueOf(stationId));
                // 武穴返回来的数据是需要上报的值，不是系数
                Double value = scaleObject.getDouble(key);
                correctUltraShortTerm.setCorrectValue(new BigDecimal(value));
//                correctUltraShortTerm.setRatio(new BigDecimal(value));
                list.add(correctUltraShortTerm);
            }
        }
        list.stream().sorted(Comparator.comparing(CorrectUltraShortTerm::getForecastTime));
        correctUltraShortTermService.saveOrUpdateBatch(list);
        return list;
    }

    /**
     * 生成修正后的短期文件(武穴一体化)
     *
     * @param station
     * @param list
     * @return
     */
    public boolean genFile(Station station, List<CorrectUltraShortTerm> list) {
        boolean result = true;
        // 初始化模板
        String vmsPath = SystermUtils.getResourceBasePath() + "/vms/CDQ.vm";
        File file;
        Template template = this.velocityEngine.getTemplate(vmsPath);
        // 如果模板不为空
        if (template != null) {
            VelocityContext velocityContext;
            StringWriter writer;
            // 将修正后的短期数据按照预测时间排序
            list.sort(Comparator.comparing(CorrectUltraShortTerm::getForecastTime));
            // 根据修正后的数据，拼接需要的数据
            List<Map<String, Object>> vList = new ArrayList<>();
            for (CorrectUltraShortTerm a : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("ratio", a.getCorrectValue());
                map.put("forecastTime", DateUtil.format(a.getForecastTime(), "yyyy-MM-dd HH:mm:ss"));
                vList.add(map);
            }
            // 格式化模板数据
            writer = new StringWriter();
            velocityContext = new VelocityContext();
            velocityContext.put("efiLabel", station.getStationCode());
            velocityContext.put("currentTime", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            velocityContext.put("vList", vList);
            template.merge(velocityContext, writer);
            String[] filePath = station.getLocalFilePath().split(";");
            for (int i = 0; i < filePath.length; i++) {
                // 获取文件路径
                File fileUrl = new File(filePath[i]);
                // 判断目录是否存在
                if (!fileUrl.exists()) {
                    fileUrl.mkdirs();
                }
                // 获取文件名
                String fileName = "WXCDQ_" + DateUtil.format(list.get(0).getSignTime(), "yyyyMMddHHmmss") + ".RB";
                file = new File(filePath[i] + File.separatorChar + fileName);
                // 写入文件
                result = writeFile(file, station, writer, fileName, filePath[i]);
            }
        }
        return result;
    }


    /**
     * 写入文件
     *
     * @param file
     * @param station
     * @param writer
     * @param fileName
     * @param filePath
     * @return
     */
    private boolean writeFile(File file, Station station, StringWriter writer, String fileName, String filePath) {
        boolean result = true;
        // 获取文件路径
        File fileUrl = new File(filePath);
        // 判断目录是否存在
        if (!fileUrl.exists()) {
            fileUrl.mkdirs();
        }
        // 检查文件是否存在
        File existingFile = new File(filePath + File.separator + fileName);
        if (existingFile.exists()) {
            // 如果存在同名文件，尝试删除
            boolean deleted = existingFile.delete();
            if (!deleted) {
                // 如果无法删除，记录警告并返回false
                log.warn("无法删除文件：" + fileName);
                return false;
            }
        }

        // 创建流
        FileOutputStream os = null;
        try {
            boolean res = file.createNewFile();
            // 如果创建成功
            if (res) {
                os = new FileOutputStream(file);
                // 采用UTF-8字符集
                os.write(writer.toString().getBytes("UTF-8"));
                os.flush();
                // 创建文件失败
            } else {
                result = false;
                log.warn(station.getStationCode() + "文件名：" + fileName + " 生成失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
            result = false;
            log.warn(station.getStationCode() + " 创建" + "文件名：" + fileName + "失败");
        } finally {
            // 如果流不为空，关闭流
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    log.error("文件生成关闭流失败", e);
                }
            }
            log.info("执行生成文件完毕：" + filePath + File.separatorChar + fileName);
            return result;
        }
    }
}
