package com.gyee.runeconomy.service.Windresourceanalysis;

import com.gyee.common.contant.ContantXk;
import com.gyee.common.model.PointData;
import com.gyee.common.model.StringUtils;
import com.gyee.common.util.DateUtils;
import com.gyee.runeconomy.dto.DataVo;
import com.gyee.runeconomy.dto.WindspeedVo;
import com.gyee.runeconomy.dto.pewpVo;
import com.gyee.runeconomy.dto.speed.PowerPointData;
import com.gyee.runeconomy.dto.speed.WindDirectionALG;
import com.gyee.runeconomy.init.CacheContext;
import com.gyee.runeconomy.model.auto.ProBasicPowerstation;
import com.gyee.runeconomy.model.auto.ProBasicPowerstationPoint;
import com.gyee.runeconomy.model.auto.ProBasicWeatherStation;
import com.gyee.runeconomy.service.auto.IProBasicPowerstationPointService;
import com.gyee.runeconomy.service.auto.IProEconPowerstationInfoDay1Service;
import com.gyee.runeconomy.util.realtimesource.IEdosUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WindresourceanalysisService {

    @Resource
    private IProEconPowerstationInfoDay1Service proEconPowerstationInfoDay1Service;

    @Resource
    private IProBasicPowerstationPointService proBasicPowerstationPointService;

    @Resource
    private IEdosUtil edosUtil;

    public List<WindspeedVo> Comprehensive(String Data) throws Exception {

        List<ProBasicWeatherStation> wplsf = CacheContext.weawpls.stream().filter(w -> w.getWindpowerstationId().endsWith("FDC_STA")).collect(Collectors.toList());

        //转换时间为Date类型
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(Data);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);

        Date startTime = calendar.getTime();

        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(date);
        calendar1.set(Calendar.HOUR_OF_DAY, 23);
        calendar1.set(Calendar.MINUTE, 59);
        calendar1.set(Calendar.SECOND, 59);

        Date endTime = calendar1.getTime();

        ProBasicPowerstationPoint pjfs = null;
        ProBasicPowerstationPoint pjfx = null;

        List<WindspeedVo> vos = new ArrayList<>();

        for (ProBasicWeatherStation wp : wplsf) {
            if (wp.getId().contains("GJYF02") || wp.getId().contains("GJYF03") || wp.getId().contains("MLJ")) continue;


            pjfs = proBasicPowerstationPointService.getPowerstationPoint(wp.getWindpowerstationId(), ContantXk.SSPJFS);

            pjfx = proBasicPowerstationPointService.getPowerstationPoint(wp.getId(), ContantXk.FCCFTFX70);

            List<ProBasicPowerstation> collect = CacheContext.wplsf.stream().filter(c -> c.getId().equals(wp.getWindpowerstationId())).collect(Collectors.toList());

            WindspeedVo vo = new WindspeedVo();

            if (pjfs.getNemCode() != null && !pjfs.getNemCode().equals("INITIAL")) {

                //List<PointData> maxs = edosUtil.getHistStat(pjfs, startTime.getTime() / 1000, endTime.getTime() / 1000, (long) 1, null, 0);
                //List<PointData> mins = edosUtil.getHistStat(pjfs, startTime.getTime() / 1000, endTime.getTime() / 1000, (long) 1, null, 1);
                //List<PointData> ave = edosUtil.getHistStat(pjfs, startTime.getTime() / 1000, endTime.getTime() / 1000, (long) 1, null, 2);
                List<PointData> kkk = edosUtil.getHistoryDatasRaw(pjfs, startTime.getTime() / 1000, endTime.getTime() / 1000);
                DoubleSummaryStatistics summaried = kkk.stream().mapToDouble(PointData::getPointValueInDouble).summaryStatistics();

                double avenum = summaried.getAverage();
                double maxsnum = summaried.getMax();
                double minsnum = summaried.getMin();
                //if (wp.getId().contains("NJLF01")) {
                //    //                    avenum = ave.get(0).getPointValueInDouble() / 10;
                //    //                    maxsnum = maxs.get(0).getPointValueInDouble() / 10;
                //    //                    minsnum = mins.get(0).getPointValueInDouble() /10;
                //    avenum = (ave != null && !ave.isEmpty()) ? ave.get(0).getPointValueInDouble() : 0.0;
                //    maxsnum = (maxs != null && !maxs.isEmpty()) ? maxs.get(0).getPointValueInDouble() : 0.0;
                //    minsnum = (mins != null && !mins.isEmpty()) ? mins.get(0).getPointValueInDouble() : 0.0;
                //
                //} else {
                //    avenum = (ave != null && !ave.isEmpty()) ? ave.get(0).getPointValueInDouble() : 0.0;
                //    maxsnum = (maxs != null && !maxs.isEmpty()) ? maxs.get(0).getPointValueInDouble() : 0.0;
                //    minsnum = (mins != null && !mins.isEmpty()) ? mins.get(0).getPointValueInDouble() : 0.0;
                //}

                vo.setWpid(wp.getWindpowerstationId());
                vo.setName(collect.get(0).getName());
                vo.setPjfs(StringUtils.round(avenum, 2));
                vo.setZdfs(StringUtils.round(maxsnum, 2));
                vo.setZxfs(StringUtils.round(minsnum, 2));


            }
            if (pjfx.getNemCode() != null && !pjfs.getNemCode().equals("INITIAL")) {
                //List<PointData> maxs = edosUtil.getHistStat(pjfx, startTime.getTime() / 1000, endTime.getTime() / 1000, (long) 1, null, 0);
                //List<PointData> mins = edosUtil.getHistStat(pjfx, startTime.getTime() / 1000, endTime.getTime() / 1000, (long) 1, null, 1);
                //List<PointData> ave = edosUtil.getHistStat(pjfx, startTime.getTime() / 1000, endTime.getTime() / 1000, (long) 1, null, 2);
                List<PointData> ave = edosUtil.getHistoryDatasRaw(pjfx, startTime.getTime() / 1000, endTime.getTime() / 1000);
                double avefx = 0.0;
                if (wp.getId().contains("NJLF01")) {
                    avefx = (ave != null && !ave.isEmpty()) ? ave.get(0).getPointValueInDouble() / 10 : 0.0;
                } else {
                    avefx = (ave != null && !ave.isEmpty()) ? ave.stream().mapToDouble(PointData::getPointValueInDouble).average().orElse(0) : 0.0;
                }
                vo.setPjfx(StringUtils.round(avefx, 2));
                vos.add(vo);
            }

        }

        return vos;

    }


    public List<pewpVo> gzComprehensive(String Data) throws Exception {

        List<ProBasicPowerstation> wplsg = CacheContext.wplsG;

        //转换时间为Date类型
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(Data);

        //        Calendar calendar = Calendar.getInstance();
        //        calendar.setTime(date);
        //        calendar.set(Calendar.HOUR_OF_DAY, 0);
        //        calendar.set(Calendar.MINUTE, 0);
        //        calendar.set(Calendar.SECOND, 0);
        //        Date startTime = calendar.getTime();

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);

        Date startTime = calendar.getTime();

        //        calendar.set(Calendar.HOUR_OF_DAY, 23);
        //        calendar.set(Calendar.MINUTE, 59);
        //        calendar.set(Calendar.SECOND, 59);
        //
        //        Date endTime = calendar.getTime();
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(date);
        calendar1.set(Calendar.HOUR_OF_DAY, 23);
        calendar1.set(Calendar.MINUTE, 59);
        calendar1.set(Calendar.SECOND, 59);

        Date endTime = calendar1.getTime();

        ProBasicPowerstationPoint pjfs = null;
        List<pewpVo> vos = new ArrayList<>();
        for (ProBasicPowerstation wp : wplsg) {

            pjfs = proBasicPowerstationPointService.getPowerstationPoint(wp.getId(), ContantXk.GCGZQD);

            if (pjfs != null) {
                List<PointData> pjfsls = edosUtil.getHistoryDatasRaw(pjfs.getNemCode(), startTime.getTime() / 1000, endTime.getTime() / 1000);

                if (pjfsls != null && !pjfsls.isEmpty()) {

                    List<PointData> filterls = new ArrayList<>();
                    for (PointData po : pjfsls) {
                        if (po.getPointValueInDouble() > 10) {
                            filterls.add(po);
                        }
                    }


                    if (!filterls.isEmpty()) {

                        Date beginTime1 = new Date(filterls.get(0).getPointTime());

                        //获取最后一个元素
                        Date endTime1 = new Date(filterls.get(filterls.size() - 1).getPointTime());

                        //获取两个时间差
                        double hours = DateUtils.hoursDiff(beginTime1, endTime1);

                        DoubleSummaryStatistics summaryStatistics = filterls.stream().mapToDouble(PointData::getPointValueInDouble).summaryStatistics();

                        double sum = filterls.stream()
                                .mapToDouble(PointData::getPointValueInDouble)
                                .sum();
                        pewpVo vo = new pewpVo();
                        vo.setWpid(wp.getId());
                        vo.setName(wp.getName());

                        //日最大辐照度
                        vo.setZdfdz(StringUtils.round(summaryStatistics.getMax(), 2));
                        vo.setRcsj(beginTime1);
                        vo.setRlsj(endTime1);

                        //持续
                        vo.setCxsj(hours);
                        vos.add(vo);
                        //日最小风速
                        //                    pewp.setRzxfs(StringUtils.round(summaryStatistics.getMin(), 2));

                        double avg = StringUtils.round(summaryStatistics.getAverage(), 2);

                        double result = new BigDecimal(avg * hours).divide(new BigDecimal(1000), 2, RoundingMode.HALF_EVEN).doubleValue();
                        vo.setZfzd(StringUtils.round(result, 2));

                        //日平均风速
                        //                    pewp.setRpjfs(result);


                    }

                }
            }
        }

        return vos;
    }


    public List<DataVo> GroupRealtimevalue(String wpid, String Data) throws Exception {

        List<DataVo> vos = new ArrayList<DataVo>();

        //转换时间为Date类型
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(Data);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);

        Date startTime = calendar.getTime();

        //        Calendar calendar1 = Calendar.getInstance();
        //        calendar1.setTime(date);
        //        calendar1.set(Calendar.HOUR_OF_DAY, 23);
        //        calendar1.set(Calendar.MINUTE, 59);
        //        calendar1.set(Calendar.SECOND, 59);
        //
        //        Date endTime = calendar1.getTime();
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(date);

        // 获取当前日期
        Calendar today = Calendar.getInstance();
        today.set(Calendar.HOUR_OF_DAY, 0);
        today.set(Calendar.MINUTE, 0);
        today.set(Calendar.SECOND, 0);

        // 判断是否是当天
        if (calendar1.get(Calendar.YEAR) == today.get(Calendar.YEAR) &&
                calendar1.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) {
            // 当天，设置endTime为当前时间
            Date now = new Date();
            calendar1.setTime(now);
        } else {
            // 非当天，设置endTime为传入的date的23:59:59
            calendar1.set(Calendar.HOUR_OF_DAY, 23);
            calendar1.set(Calendar.MINUTE, 59);
            calendar1.set(Calendar.SECOND, 59);
        }
        Date endTime = calendar1.getTime();
        ProBasicPowerstationPoint gzzs = null;
        //        List<ProBasicPowerstation> wplsG = CacheContext.wplsG.stream().filter(c->c.getOrderNum().equals(15)).collect(Collectors.toList());
        gzzs = proBasicPowerstationPointService.getPowerstationPoint(wpid, ContantXk.GCGZQD);


        List<PointData> gzzsls = edosUtil.getHistoryDatasRaw(gzzs.getNemCode(), startTime.getTime() / 1000, endTime.getTime() / 1000);
        double temp6 = 0;
        for (int i = 0; i < gzzsls.size(); i++) {
            DataVo vo = new DataVo();
            temp6 = gzzsls.get(i).getPointValueInDouble();
            vo.setValue6(com.gyee.runeconomy.util.StringUtils.round(temp6, 2));
            vo.setTime(gzzsls.get(i).getPointTime());
            vos.add(vo);
        }

        return vos;
    }

    public List<DataVo> fdGroupRealtimevalue(String wpid, String Data) throws Exception {

        List<DataVo> vos = new ArrayList<DataVo>();

        //转换时间为Date类型
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(Data);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);

        Date startTime = calendar.getTime();

        //        Calendar calendar1 = Calendar.getInstance();
        //        calendar1.setTime(date);
        //        calendar1.set(Calendar.HOUR_OF_DAY, 23);
        //        calendar1.set(Calendar.MINUTE, 59);
        //        calendar1.set(Calendar.SECOND, 59);
        //
        //        Date endTime = calendar1.getTime();

        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(date);

        // 获取当前日期
        Calendar today = Calendar.getInstance();
        today.set(Calendar.HOUR_OF_DAY, 0);
        today.set(Calendar.MINUTE, 0);
        today.set(Calendar.SECOND, 0);

        // 判断是否是当天
        if (calendar1.get(Calendar.YEAR) == today.get(Calendar.YEAR) &&
                calendar1.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) {
            // 当天，设置endTime为当前时间
            Date now = new Date();
            calendar1.setTime(now);
        } else {
            // 非当天，设置endTime为传入的date的23:59:59
            calendar1.set(Calendar.HOUR_OF_DAY, 23);
            calendar1.set(Calendar.MINUTE, 59);
            calendar1.set(Calendar.SECOND, 59);
        }
        Date endTime = calendar1.getTime();


        ProBasicPowerstationPoint gzzs = null;
        List<ProBasicWeatherStation> wplsf = null;
        List<ProBasicPowerstation> wplsf1 = null;
        if (wpid.contains("GJY_FDC")) {
            //            wplsf = CacheContext.weawpls.stream().filter(w -> w.getWindpowerstationId().equals(wpid) && w.getId().contains("GJYF01")).collect(Collectors.toList());
            wplsf1 = CacheContext.wplsf.stream().filter(w -> wpid.equals(w.getId())).collect(Collectors.toList());
        } else {
            wplsf = CacheContext.weawpls.stream().filter(w -> w.getWindpowerstationId().equals(wpid)).collect(Collectors.toList());
        }

        if (wpid.contains("GJY_FDC")) {
            gzzs = proBasicPowerstationPointService.getPowerstationPoint(wplsf1.get(0).getId(), ContantXk.SSPJFS);
        } else {
            gzzs = proBasicPowerstationPointService.getPowerstationPoint(wplsf.get(0).getWindpowerstationId(), ContantXk.SSPJFS);
        }


        //        List<PointData> gzzsls = edosUtil.getHistoryDatasRaw(gzzs.getNemCode(), startTime.getTime() / 1000, endTime.getTime() / 1000);
        //        List<PointData> gzzsls = edosUtil.getHistoryDatasSnap(gzzs, startTime.getTime() / 1000, endTime.getTime() / 1000, null, 900L);
        List<PointData> gzzsls = edosUtil.getHistoryDatasSnap(gzzs, startTime.getTime() / 1000, endTime.getTime() / 1000, null, 60L);

        double temp6 = 0;
        for (int i = 0; i < gzzsls.size(); i++) {
            DataVo vo = new DataVo();
            temp6 = gzzsls.get(i).getPointValueInDouble();
            vo.setValue6(StringUtils.round(temp6, 2));
            vo.setTime(gzzsls.get(i).getPointTime());
            vos.add(vo);
        }

        return vos;
    }


    /**
     * 风向玫瑰图\风向频率玫瑰图
     *
     * @param wpid 预处理数据的id
     * @param mode 0:单台风机  1:多台风机合并
     * @return
     */
    public Object fxRoses(String wpid, int mode, String Data) throws Exception {

        List<ProBasicWeatherStation> wplsf = CacheContext.weawpls.stream().filter(w -> w.getWindpowerstationId().equals(wpid)).collect(Collectors.toList());

        //转换时间为Date类型
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(Data);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);

        Date startTime = calendar.getTime();

        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(date);

        // 获取当前日期
        Calendar today = Calendar.getInstance();
        today.set(Calendar.HOUR_OF_DAY, 0);
        today.set(Calendar.MINUTE, 0);
        today.set(Calendar.SECOND, 0);

        // 判断是否是当天
        if (calendar1.get(Calendar.YEAR) == today.get(Calendar.YEAR) &&
                calendar1.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) {
            // 当天，设置endTime为当前时间
            Date now = new Date();
            calendar1.setTime(now);
        } else {
            // 非当天，设置endTime为传入的date的23:59:59
            calendar1.set(Calendar.HOUR_OF_DAY, 23);
            calendar1.set(Calendar.MINUTE, 59);
            calendar1.set(Calendar.SECOND, 59);
        }
        Date endTime = calendar1.getTime();

        ProBasicPowerstationPoint pjfs = null;
        ProBasicPowerstationPoint pjfx = null;

        List<WindspeedVo> vos = new ArrayList<>();

        for (ProBasicWeatherStation ww : wplsf) {
            if (ww.getId().contains("GJYF02")) continue;

            pjfs = proBasicPowerstationPointService.getPowerstationPoint(ww.getId(), ContantXk.FCCFTFS70);
            pjfx = proBasicPowerstationPointService.getPowerstationPoint(ww.getId(), ContantXk.FCCFTFX70);

            List<ProBasicPowerstation> collect = CacheContext.wplsf.stream().filter(c -> c.getId().equals(ww.getWindpowerstationId())).collect(Collectors.toList());

            if (pjfs.getNemCode() != null && !pjfs.getNemCode().equals("INITIAL")) {

                List<PointData> pjfsls = edosUtil.getHistoryDatasSnap(pjfs, startTime.getTime() / 1000, endTime.getTime() / 1000, null, 900L);
                List<PointData> pjfxls = edosUtil.getHistoryDatasSnap(pjfx, startTime.getTime() / 1000, endTime.getTime() / 1000, null, 900L);

                double temp1 = 0;
                for (int i = 0; i < pjfsls.size(); i++) {
                    WindspeedVo vo = new WindspeedVo();
                    temp1 = pjfsls.get(i).getPointValueInDouble();
                    vo.setWpid(ww.getId());
                    vo.setHours(pjfsls.get(i).getPointTime());
                    vo.setPjfs(temp1);
                    vos.add(vo);
                }

                if (pjfxls != null && pjfxls.size() > 1) {
                    vos.stream().forEach(i -> {
                        Optional<PointData> optional = pjfxls.stream()
                                .filter(j -> j.getPointTime().equals(i.getHours()))
                                .findFirst();
                        if (optional.isPresent()) {
                            PointData tqinfoday = optional.get();
                            i.setPjfx(tqinfoday.getPointValueInDouble());
                        }
                    });
                }
            }

        }

        List<Object> result = new ArrayList<>();
        if (mode == 0) {

            Map<String, Object> map = new HashMap<>();
            List<PowerPointData> ls = new ArrayList<>();
            for (WindspeedVo v : vos) {
                PowerPointData data = new PowerPointData();
                data.setFx(v.getPjfx());
                data.setSpeed(v.getPjfs());
                ls.add(data);
            }
            map.put("wt", wpid);
            map.put("roses", WindDirectionALG.fxRoses(ls));
            map.put("count", WindDirectionALG.fxCountRoses(ls));
            //                map.put("radar", WindDirectionALG.fxRadarRoses(ls));
            //                map.put("frequency", WindDirectionALG.windDeviationPoint(ls));
            result.add(map);

        }
        if (mode == 1) {
            List<PowerPointData> ls = new ArrayList<>();
            for (WindspeedVo obj : vos)
                ls.addAll(csvParse(obj));
            Map<String, Object> map = new HashMap<>();
            map.put("wt", "merge");
            map.put("roses", WindDirectionALG.fxRoses(ls));
            map.put("count", WindDirectionALG.fxCountRoses(ls));
            //            map.put("radar", WindDirectionALG.fxRadarRoses(ls));
            //            map.put("frequency", WindDirectionALG.windDeviationPoint(ls));
            result.add(map);
        }

        return result;
    }

    /**
     * csv 文件解析成对象
     *
     * @param obj
     * @return
     */
    private List<PowerPointData> csvParse(WindspeedVo obj) {
        List<PowerPointData> ls = new ArrayList<>();
        //        List<String> content = FileUtil.readFile(obj.getPath(), true);
        //        for (int i = 1; i < content.size(); i++){
        //            String[] split = content.get(i).split(",");
        PowerPointData data = new PowerPointData();
        //            if (data.getSpeed() < 0 || data.getPower() < 0)
        //                continue;
        data.setWtId(obj.getWpid());
        data.setFx(obj.getPjfx());
        data.setSpeed(obj.getPjfs());
        ls.add(data);
        //        }
        return ls;
    }
}