package com.ruoyi;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.quartz.handler.IJobHandler;
import com.ruoyi.ucp.entity.*;
import com.ruoyi.ucp.feign.AdapterApi;
import com.ruoyi.ucp.service.*;
import com.ruoyi.ucp.util.CalcCache;
import org.apache.commons.math3.fitting.PolynomialCurveFitter;
import org.apache.commons.math3.fitting.WeightedObservedPoints;
import org.junit.Test;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.URI;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class JavaFunctionJobHandler extends IJobHandler {

/*    @Resource
    private PointInfo pointInfo;*/

    @Resource
    private AdapterApi adapter;
    @Resource
    private IPointInfoService pointService;
    @Resource
    private IStationInfoHourService stationInfoHourService;
    @Resource
    private IStationInfoDayService stationInfoDayService;
    @Resource
    private ILineInfoDayService lineInfoDayService;
    @Resource
    private IStateAiService stateAiService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IEquipmentModelService equipmentModelService;
    @Resource
    private ITurbineInfoDayService turbineInfoDayService;
    @Resource
    private IProEconReportIndicatorPoolService reportIndicatorPoolService;

    @Override
    public void execute() throws Exception {

    }

    @Override
    public IJobHandler getFunctionHandler() {
        return null;
    }

    @Override
    public void setFunctionHandler(IJobHandler jobHandler) {

    }

    public URI taosGoldenUriTest() {
        return URI.create("http://127.0.0.1:8011/ts");
    }

    public String pointInfos2Keys(List<PointInfo> entity) {
        return entity.stream().map(PointInfo::getPointKey).collect(Collectors.joining(","));
    }

    public List<StationInfoHour> getStationinfoByHour(Date hour) {
        QueryWrapper<StationInfoHour> wrapper = new QueryWrapper<>();
        wrapper.eq("record_date", DateUtil.beginOfHour(hour));
        return stationInfoHourService.list(wrapper);
    }

    public List<StationInfoDay> getStationinfoByDate(Date date) {
        QueryWrapper<StationInfoDay> wrapper = new QueryWrapper<>();
        wrapper.eq("record_date", date);
        return stationInfoDayService.list(wrapper);
    }

    public List<LineInfoDay> getLineinfoByDate(Date date) {
        QueryWrapper<LineInfoDay> wrapper = new QueryWrapper<>();
        wrapper.eq("record_date", date);
        return lineInfoDayService.list(wrapper);
    }

    public URI taosUri() {
        return URI.create("http://172.16.12.101:8012/ts");
    }

    public URI goldenUri() {
        return URI.create("http://172.16.12.103:8011/ts");
    }

    public Map<String, String> getEntityMap(String uniformCode, String institutionType) {
        PointInfo pi = new PointInfo();
        pi.setUniformCode(uniformCode);
        pi.setInstitutionType(institutionType);
        List<PointInfo> entity = pointService.getByEntity(pi);
        switch (institutionType) {
            case "turbine":
            case "state":
                return entity.stream().collect(Collectors.toMap(PointInfo::getTurbineId, PointInfo::getPointKey));
            case "station":
                return entity.stream().collect(Collectors.toMap(PointInfo::getStationId, PointInfo::getPointKey));
        }
        return new HashMap<>();
    }

    public Map<String, TurbineInfoDay> getTurbineinfoMap(Date date, List<PointInfo> entity) {
        QueryWrapper<TurbineInfoDay> wrapper = new QueryWrapper<>();
        wrapper.eq("record_date", date);
        List<TurbineInfoDay> list = turbineInfoDayService.list(wrapper);
        if (list.isEmpty()) {
            entity.forEach(pi -> {
                TurbineInfoDay day = new TurbineInfoDay();
                day.setStationId(pi.getStationId());
                day.setProjectId(pi.getProjectId());
                day.setLineId(pi.getLineId());
                day.setTurbineId(pi.getTurbineId());
                day.setRecordDate(date);
                list.add(day);
            });
        }
        return list.stream().collect(Collectors.toMap(TurbineInfoDay::getTurbineId, Function.identity()));
    }

    public List<PointInfo> getEntity(String uniformCode, String institutionType) {
        PointInfo pi = new PointInfo();
        pi.setUniformCode(uniformCode);
        pi.setInstitutionType(institutionType);
        return pointService.getByEntity(pi);
    }

    public Map<String, Double> getTurbinePowerLoss(double rfdl, PointInfo piZt, List<PointData> fsList, List<PointData> glList) {
        String tbId = piZt.getTurbineId();
//        Map<Double, Long> collect = piZt.getPointDatas().stream().collect(Collectors.groupingBy(PointData::getValue, Collectors.counting()));
        double sum1 = glList.stream().mapToDouble(PointData::getValue).sum();
        double xs = rfdl / (sum1 / 240);
//        double sum2 = fsList.stream().mapToDouble(pd -> {
//            Double v = CalcCache.fitcoef.get(tbId).get(pd.getValue());
//            if (v == null) v = 0.0;
//            return v;
//        }).sum();
//        sum2=sum2/240;

        List<PointData> collectZt = piZt.getPointDatas();
        double jxss = 0, sdtj = 0, gzss = 0, djss = 0, xnss = 0, fdjcl = 0, xdjcl = 0, xdtj = 0;
        Map<String, Double> map = new HashMap<>();
        if (collectZt.size() == fsList.size() && fsList.size() == glList.size()) {
            for (int i = 0; i < collectZt.size(); i++) {
                Double v = CalcCache.fitcoef.get(tbId).get(fsList.get(i).getValue());
                if (v == null) v = 0.0;
                switch ((int) collectZt.get(i).getValue()) {
                    //计划检修损失：
                    case 6:
                        //检修
                        jxss += v;
                        break;
                    case 1:
                        //手动停机
                        sdtj += v;
                        break;
                    //非计划检修损失：
                    case 4:
                        //故障
                        gzss += v;
                        break;
                    case 0:
                        //待机
                        djss += v;
                        break;
                    //性能损失：
                    case 2:
                        //性能
                        xnss += v - glList.get(i).getValue();
                        break;
                    case 3:
                        //发电降出力
                        fdjcl += v - glList.get(i).getValue();
                        break;
                    //限电损失：
                    case 8:
                        //限电降出力
                        xdjcl += v - glList.get(i).getValue();
                        break;
                    case 9:
                        //限电停机
                        xdtj += v;
                        break;
                }
            }
        }
        //15秒*60分钟
        map.put("jxss", jxss > 0 ? jxss / 240 * xs : 0);
        map.put("sdtj", sdtj > 0 ? sdtj / 240 * xs : 0);
        map.put("gzss", gzss > 0 ? gzss / 240 * xs : 0);
        map.put("djss", djss > 0 ? djss / 240 * xs : 0);
        map.put("xnss", xnss > 0 ? xnss / 240 * xs : 0);
        map.put("fdjcl", fdjcl > 0 ? fdjcl / 240 * xs : 0);
        map.put("xdjcl", xdjcl > 0 ? xdjcl / 240 * xs : 0);
        map.put("xdtj", xdtj > 0 ? xdtj / 240 * xs : 0);
        return map;
    }

    public void calcAQTS(Date date) {
        QueryWrapper<StationInfoDay> wrapper = new QueryWrapper<>();
        wrapper.select("min(record_date) record_date");
        StationInfoDay one = stationInfoDayService.getOne(wrapper);
        wrapper = new QueryWrapper<>();
        wrapper.eq("record_date", one.getRecordDate());
        //最早时间的列表
        List<StationInfoDay> list = stationInfoDayService.list(wrapper);
        List<StationInfoDay> today = getStationinfoByDate(date);
        if (today.isEmpty()) {
            for (StationInfoDay infoDay : list) {
                StationInfoDay day = new StationInfoDay();
                day.setStationId(infoDay.getStationId());
                day.setRecordDate(date);
                day.setAqts(infoDay.getAqts() + (int) DateUtil.betweenDay(infoDay.getRecordDate(), date, true));
                today.add(day);
            }
        } else {
            Map<String, StationInfoDay> collect = list.stream().collect(Collectors.toMap(StationInfoDay::getStationId, Function.identity()));
            for (StationInfoDay day : today) {
                StationInfoDay day1 = collect.get(day.getStationId());
                day.setAqts(day1.getAqts() + (int) DateUtil.betweenDay(day1.getRecordDate(), date, true));
            }
        }
        stationInfoDayService.saveOrUpdateBatch(today);
    }

    public void calcStationSwGwCyDl(Date date) {
        //date当天零点
        DateTime time = DateUtil.beginOfDay(date);
        //date昨天零点
        DateTime time0 = DateUtil.offsetDay(time, -1);
        //date当天零点加三分钟
        DateTime time2 = DateUtil.offsetMinute(time, 3);
        //date昨天零点加三分钟
        DateTime time1 = DateUtil.offsetMinute(time0, 3);

        PointInfo swdlPi = new PointInfo();
        swdlPi.setUniformCode("Z-ZXYG-CX");
        PointInfo gwdlPi = new PointInfo();
        gwdlPi.setUniformCode("Z-FXYG-CX");
        PointInfo cydlPi = new PointInfo();
        cydlPi.setUniformCode("Z-ZXYG-ZYB");

        List<PointInfo> swdlEt = pointService.getByEntity(swdlPi);
        List<PointInfo> gwdlEt = pointService.getByEntity(gwdlPi);
        Map<String, PointInfo> gwdlMap = gwdlEt.stream().collect(Collectors.toMap(PointInfo::getStationId, Function.identity()));
        List<PointInfo> cydlEt = pointService.getByEntity(cydlPi);
        Map<String, PointInfo> cydlMap = cydlEt.stream().collect(Collectors.toMap(PointInfo::getStationId, Function.identity()));

        String swdlK = pointInfos2Keys(swdlEt);
        String gwdlK = pointInfos2Keys(gwdlEt);
        String cydlK = pointInfos2Keys(cydlEt);

        Map<String, PointData> swdlL2 = adapter.getHistorySection(goldenUri(), swdlK, time2.getTime());
        Map<String, PointData> swdlL1 = adapter.getHistorySection(goldenUri(), swdlK, time1.getTime());
        Map<String, PointData> gwdlL2 = adapter.getHistorySection(goldenUri(), gwdlK, time2.getTime());
        Map<String, PointData> gwdlL1 = adapter.getHistorySection(goldenUri(), gwdlK, time1.getTime());
        Map<String, PointData> cydlL2 = adapter.getHistorySection(goldenUri(), cydlK, time2.getTime());
        Map<String, PointData> cydlL1 = adapter.getHistorySection(goldenUri(), cydlK, time1.getTime());

        List<StationInfoDay> byDate = getStationinfoByDate(time0.toJdkDate());
        Map<String, StationInfoDay> collect = new HashMap<>();
        if (!byDate.isEmpty()) {
            collect = byDate.stream().collect(Collectors.toMap(StationInfoDay::getStationId, Function.identity()));
        }
        StationInfoDay infoDay;
        String stationId;
        PointInfo gwdlKey, cydlKey;
        List<StationInfoDay> infoDays = new ArrayList<>();
        for (PointInfo info : swdlEt) {
            stationId = info.getStationId();
            if (byDate.isEmpty()) {
                infoDay = new StationInfoDay();
                infoDay.setStationId(stationId);
                infoDay.setRecordDate(time0.toJdkDate());
            } else {
                infoDay = collect.get(stationId);
            }
            infoDay.setSwdl((int) ((swdlL2.get(info.getPointKey()).getValue() -
                    swdlL1.get(info.getPointKey()).getValue()) * info.getCoef()));
            gwdlKey = gwdlMap.get(stationId);
            infoDay.setGwdl((int) ((gwdlL2.get(gwdlKey.getPointKey()).getValue() -
                    gwdlL1.get(gwdlKey.getPointKey()).getValue()) * gwdlKey.getCoef()));
            cydlKey = cydlMap.get(stationId);
            infoDay.setCydl((int) ((cydlL2.get(cydlKey.getPointKey()).getValue() -
                    cydlL1.get(cydlKey.getPointKey()).getValue()) * cydlKey.getCoef()));
            infoDays.add(infoDay);
        }
        stationInfoDayService.saveOrUpdateBatch(infoDays);
    }

    public void calcStationHourRFDL(Date hour) {
        PointInfo pointInfo = new PointInfo();
        pointInfo.setInstitutionType("station");
        pointInfo.setUniformCode("RFDLSYZ");
        List<PointInfo> entity = pointService.getByEntity(pointInfo);
        Map<String, PointData> section = adapter.getHistorySection(taosUri(), pointInfos2Keys(entity), hour.getTime());
        List<StationInfoHour> byHours = getStationinfoByHour(hour);
        if (byHours.isEmpty()) {
            for (PointInfo point : entity) {
                StationInfoHour info = new StationInfoHour();
                info.setStationId(point.getStationId());
                info.setRecordDate(DateUtil.beginOfHour(hour));
                info.setRfdl(section.get(point.getPointKey()).getValue());
                byHours.add(info);
            }
        } else {
            Map<String, String> collect = entity.stream().collect(Collectors.toMap(PointInfo::getStationId, PointInfo::getPointKey));
            for (StationInfoHour byHour : byHours) {
                byHour.setRfdl(section.get(collect.get(byHour.getStationId())).getValue());
            }
        }
        stationInfoHourService.saveOrUpdateBatch(byHours);
    }

    public void writeReportPool(Date date) {
        //date当天零点
        DateTime time = DateUtil.beginOfDay(date);
        //date昨天零点
        DateTime time0 = DateUtil.offsetDay(time, -1);
        DateTime beginOfMonth = DateUtil.beginOfMonth(time0);
        DateTime beginOfYear = DateUtil.beginOfYear(time0);

        QueryWrapper<StationInfoDay> wrapper = new QueryWrapper<>();
        wrapper.eq("record_date", time0);
        List<StationInfoDay> days = stationInfoDayService.list(wrapper);
        Map<String, StationInfoDay> dayMap = days.stream().collect(Collectors.toMap(StationInfoDay::getStationId, Function.identity()));
        wrapper = new QueryWrapper<>();
        wrapper.select("sum(rfdl) rfdl,sum(swdl) swdl,sum(gwdl) gwdl,sum(cydl) cydl,sum(zhcydl) zhcydl,station_id")
                .between("record_date", beginOfMonth.toJdkDate(), time0.toJdkDate())
                .groupBy("station_id");
        List<StationInfoDay> monthDays = stationInfoDayService.list(wrapper);
        Map<String, StationInfoDay> monthMap = monthDays.stream().collect(Collectors.toMap(StationInfoDay::getStationId, Function.identity()));
        wrapper = new QueryWrapper<>();
        wrapper.select("sum(rfdl) rfdl,sum(swdl) swdl,sum(gwdl) gwdl,sum(cydl) cydl,sum(zhcydl) zhcydl,station_id")
                .between("record_date", beginOfYear.toJdkDate(), time0.toJdkDate())
                .groupBy("station_id");
        List<StationInfoDay> yearDays = stationInfoDayService.list(wrapper);
        Map<String, StationInfoDay> yearMap = yearDays.stream().collect(Collectors.toMap(StationInfoDay::getStationId, Function.identity()));
        QueryWrapper<ProEconReportIndicatorPool> wrapperrp = new QueryWrapper<>();
        wrapperrp.eq("record_date", time0).last("and foreign_key_id = windpowerstation_id");
        List<ProEconReportIndicatorPool> pools = reportIndicatorPoolService.list(wrapperrp);
//        pools = pools.stream().filter(p -> p.getWindpowerstationId().equals("GJNY_SXGS_ZZ_FDC_STA")).collect(Collectors.toList());

        StationInfoDay day, month, year;
        List<ProEconReportIndicatorPool> poolList = new ArrayList<>();
        for (ProEconReportIndicatorPool pool : pools) {
            String stationId = pool.getWindpowerstationId();
            day = dayMap.get(stationId);
            pool.setRfdldb(day.getRfdl().doubleValue());
            pool.setRswdldb(day.getSwdl().doubleValue());
            pool.setRgwgwdldb(day.getGwdl().doubleValue());
            pool.setRfdcydldb(day.getCydl().doubleValue());
            pool.setRzhcydldb(day.getZhcydl().doubleValue());
            month = monthMap.get(stationId);
            pool.setYfdldb(month.getRfdl().doubleValue());
            pool.setYswdldb(month.getSwdl().doubleValue());
            pool.setYgwgwdldb(month.getGwdl().doubleValue());
            pool.setYfdcydldb(month.getCydl().doubleValue());
            pool.setYzhcydldb(month.getZhcydl().doubleValue());
            year = yearMap.get(stationId);
            pool.setNfdldb(year.getRfdl().doubleValue());
            pool.setNswdldb(year.getSwdl().doubleValue());
            pool.setNgwgwdldb(year.getGwdl().doubleValue());
            pool.setNfdcydldb(year.getCydl().doubleValue());
            pool.setNzhcydldb(year.getZhcydl().doubleValue());
            poolList.add(pool);
        }
        reportIndicatorPoolService.saveOrUpdateBatch(poolList);
    }

    public void calcLineDjlRfdl(Date date) {
        //date当天零点
        DateTime time = DateUtil.beginOfDay(date);
        //date昨天零点
        DateTime time0 = DateUtil.offsetDay(time, -1);
        //date当天零点加三分钟
        DateTime time2 = DateUtil.offsetMinute(time, 3);
        //date昨天零点加三分钟
        DateTime time1 = DateUtil.offsetMinute(time0, 3);

        PointInfo pi = new PointInfo();
        pi.setUniformCode("Z-ZXYG-JX");
        pi.setLineId("all");
        List<PointInfo> entity = pointService.getByEntity(pi);
//        entity = entity.stream().filter(e -> e.getStationId().equals("GJNY_SXGS_ZZ_FDC_STA")).collect(Collectors.toList());
        String keys = pointInfos2Keys(entity);
        Map<String, PointData> latest2 = adapter.getHistorySection(goldenUri(), keys, time2.getTime());
        Map<String, PointData> latest1 = adapter.getHistorySection(goldenUri(), keys, time1.getTime());

        List<LineInfoDay> byDate = getLineinfoByDate(time0.toJdkDate());
        Map<String, LineInfoDay> collect = new HashMap<>();
        if (!byDate.isEmpty()) {
            collect = byDate.stream().collect(Collectors.toMap(LineInfoDay::getLineId, Function.identity()));
        }

        List<LineInfoDay> list = new ArrayList<>();
        for (PointInfo info : entity) {
            LineInfoDay day;
            if (byDate.isEmpty()) {
                day = new LineInfoDay();
                day.setStationId(info.getStationId());
                day.setProjectId(info.getProjectId());
                day.setLineId(info.getLineId());
                day.setRecordDate(time0.toJdkDate());
            } else {
                day = collect.get(info.getLineId());
            }
            day.setRfdl((int) ((latest2.get(info.getPointKey()).getValue() -
                    latest1.get(info.getPointKey()).getValue()) * info.getCoef()));
            if (day.getRfdl() <= 0 || day.getRfdl() > 30000000) {
                day.setRfdl(0);
            }
            list.add(day);
        }
        lineInfoDayService.saveOrUpdateBatch(list);
    }

    public void calcStationZhcydl(Date date) {
        //date当天零点
        DateTime time = DateUtil.beginOfDay(date);
        //date昨天零点
        DateTime time0 = DateUtil.offsetDay(time, -1);

        QueryWrapper<LineInfoDay> wrapper = new QueryWrapper<>();
        wrapper.select("sum(rfdl) rfdl,station_id").eq("record_date", time0.toJdkDate())
                .groupBy("station_id");
        List<LineInfoDay> list = lineInfoDayService.list(wrapper);
        List<StationInfoDay> byDate = getStationinfoByDate(time0.toJdkDate());
//        list = list.stream().filter(b -> b.getStationId().equals("GJNY_SXGS_ZZ_FDC_STA")).collect(Collectors.toList());

        Map<String, StationInfoDay> collect = new HashMap<>();
        if (!byDate.isEmpty()) {
            collect = byDate.stream().collect(Collectors.toMap(StationInfoDay::getStationId, Function.identity()));
        }

        StationInfoDay infoDay;
        List<StationInfoDay> infoDays = new ArrayList<>();
        for (LineInfoDay day : list) {
            if (byDate.isEmpty()) {
                infoDay = new StationInfoDay();
                infoDay.setStationId(day.getStationId());
                infoDay.setRecordDate(time0.toJdkDate());
            } else {
                infoDay = collect.get(day.getStationId());
            }
            infoDay.setRfdl(day.getRfdl());
            infoDay.setZhcydl(infoDay.getRfdl() + infoDay.getGwdl() - infoDay.getSwdl());
            infoDays.add(infoDay);
        }
        stationInfoDayService.saveOrUpdateBatch(infoDays);
    }

    public void calcStationHourPJGL(Date hour) {
        PointInfo pointInfo = new PointInfo();
        pointInfo.setInstitutionType("station");
        pointInfo.setUniformCode("SSZGL");
        List<PointInfo> entity = pointService.getByEntity(pointInfo);
        List<StationInfoHour> byHours = getStationinfoByHour(hour);
        Map<String, StationInfoHour> collect = new HashMap<>();
        if (!byHours.isEmpty()) {
            collect = byHours.stream().collect(
                    Collectors.toMap(StationInfoHour::getStationId, Function.identity()));
        }
        DoubleStatData stat;
        List<StationInfoHour> byHours2 = new ArrayList<>();
        for (PointInfo point : entity) {
            stat = adapter.getHistoryStat(taosGoldenUriTest(),
                    point.getPointKey(), DateUtil.offsetHour(hour, -1).getTime(), hour.getTime());
            if (byHours.isEmpty()) {
                StationInfoHour info = new StationInfoHour();
                info.setStationId(point.getStationId());
                info.setRecordDate(DateUtil.beginOfHour(hour));
                if (stat == null || stat.getAvg() == null) info.setPjgl(0.0);
                info.setPjgl(stat.getAvg().getDoubleValue());
                byHours2.add(info);
            } else {
                collect.get(point.getStationId()).setPjgl(stat.getAvg().getDoubleValue());
            }
        }
        stationInfoHourService.saveOrUpdateBatch(byHours.isEmpty() ? byHours2 : byHours);
    }

    public void calcStationRfdlFj(Date date) {
        //date当天零点
        DateTime time = DateUtil.beginOfDay(date);
        //date昨天零点
        DateTime time0 = DateUtil.offsetDay(time, -1);

        QueryWrapper<TurbineInfoDay> wrapper = new QueryWrapper<>();
        wrapper.select("sum(rfdl) rfdl,station_id").eq("record_date", time0.toJdkDate())
                .groupBy("station_id");
        List<TurbineInfoDay> list = turbineInfoDayService.list(wrapper);
        List<StationInfoDay> byDate = getStationinfoByDate(time0.toJdkDate());

        Map<String, StationInfoDay> collect = new HashMap<>();
        if (!byDate.isEmpty()) {
            collect = byDate.stream().collect(Collectors.toMap(StationInfoDay::getStationId, Function.identity()));
        }

        StationInfoDay infoDay;
        List<StationInfoDay> infoDays = new ArrayList<>();
        for (TurbineInfoDay day : list) {
            if (byDate.isEmpty()) {
                infoDay = new StationInfoDay();
                infoDay.setStationId(day.getStationId());
                infoDay.setRecordDate(time0.toJdkDate());
            } else {
                infoDay = collect.get(day.getStationId());
            }
            infoDay.setRfdlFj(day.getRfdl());
            infoDays.add(infoDay);
        }
        stationInfoDayService.saveOrUpdateBatch(infoDays);
    }

    public void calcTurbineRFDL(Date date) {
        //date当天零点
        DateTime time = DateUtil.beginOfDay(date);
        //date昨天零点
        DateTime time0 = DateUtil.offsetDay(time, -1);
        //date当天零点加三分钟
        DateTime time2 = DateUtil.offsetMinute(time, 3);
        //date昨天零点加三分钟
        DateTime time1 = DateUtil.offsetMinute(time0, 3);


        PointInfo pi = new PointInfo();
        pi.setUniformCode("AI121");
        pi.setInstitutionType("turbine");
        List<PointInfo> entity = getEntity("AI121", "turbine");
        Map<String, String> turMap = entity.stream().collect(Collectors.toMap(PointInfo::getTurbineId, PointInfo::getPointKey));
        Map<String, String> fsMap = getEntityMap("AI066", "turbine");

        String keys = pointInfos2Keys(entity);

        Map<String, PointData> swdlL2 = adapter.getHistorySection(goldenUri(), keys, time2.getTime());
        Map<String, PointData> swdlL1 = adapter.getHistorySection(goldenUri(), keys, time1.getTime());

        Map<String, TurbineInfoDay> byDate = getTurbineinfoMap(time0.toJdkDate(), entity);

        TurbineInfoDay infoDay;
        String turbineId, key;
        List<TurbineInfoDay> infoDays = new ArrayList<>();
        DoubleStatData stat;
        for (PointInfo info : entity) {
            turbineId = info.getTurbineId();
            infoDay = byDate.get(turbineId);

            key = turMap.get(turbineId);
            double v = (swdlL2.get(key).getValue() - swdlL1.get(key).getValue()) * info.getCoef();
            if (v < 0 || v > 1000000) {
                v = 0;
            } else if (v > 30000) {
                v = v / (v % 30000 + 3);
            }
            infoDay.setRfdl(v);
            stat = adapter.getHistoryStat(goldenUri(), fsMap.get(turbineId), time1.getTime(), time2.getTime());
            if (stat == null) {
                infoDay.setPjfs(0.0);
            } else {
                infoDay.setPjfs(stat.getAvg().getValue());
            }

            infoDays.add(infoDay);
        }
        turbineInfoDayService.saveOrUpdateBatch(infoDays);
    }

    /*public void calcTurbine5s(Date date) {
        //date当天零点
        DateTime time = DateUtil.beginOfDay(date);
        //date昨天零点
        DateTime time0 = DateUtil.offsetDay(time, -1);

        //状态
        List<PointInfo> entityZt = getEntity("MXZT", "turbine");
        //功率
        Map<String, String> collectGl = getEntityMap("AI114", "turbine");
        //风速
        Map<String, String> collectFs = getEntityMap("AI066", "turbine");

        Map<String, TurbineInfoDay> dayMap = getTurbineinfoMap(time0.toJdkDate(), entityZt);

        String tbId;
        TurbineInfoDay infoDay;
        List<TurbineInfoDay> infoDays = new ArrayList<>();
        for (PointInfo info : entityZt) {
            tbId = info.getTurbineId();
            List<PointData> snapZt = adapter.getHistorySnap(taosUri(), info.getPointKey(), time0.getTime(), time.getTime(), 60);
            //0 待机，1 手动停机，2 正常发电，3 发电降出力，4 故障，5 故障受累，6 检修，7 检修受累，8 限电降出力，
            // 9 限电停机，10 电网受累，11 环境受累，12 通讯中断，13 设备离线

            List<DoubleStatData> statGl = adapter.getHistoryStat2(goldenUri(), collectGl.get(tbId), time0.getTime(), time.getTime(), 60);
            List<DoubleStatData> statFs = adapter.getHistoryStat2(goldenUri(), collectFs.get(tbId), time0.getTime(), time.getTime(), 60);
            List<PointData> glList = statGl.stream().map(DoubleStatData::getAvg).collect(Collectors.toList());
            List<PointData> fsList = statFs.stream().map(DoubleStatData::getAvg)
                    .peek(fs -> {
                        if (fs.getValue() < 25) {
                            fs.setDoubleValue(NumberUtil.round(fs.getValue(), 2).doubleValue());
                        } else {
                            fs.setDoubleValue(25.0);
                        }
                    }).collect(Collectors.toList());

//            Map<String, Double> loss = getTurbinePowerLoss(snapZt, fsList, tbId, glList);
            Map<String, Double> loss = new HashMap<>();

            infoDay = dayMap.get(tbId);
            infoDay.setJhjxss(loss.get("jxss") + loss.get("sdtj"));
            infoDay.setFjhjxss(loss.get("gzss") + loss.get("djss") + loss.get("fdjcl"));
            infoDay.setXdss(loss.get("xdjcl") + loss.get("xdtj"));
            infoDay.setSlss(0.0);
            if (infoDay.getRfdl() == 0) {
                infoDay.setXnss(0.0);
            } else {
                infoDay.setXnss(loss.get("xnss") * 0.1);
            }
            infoDay.setLlfdl(infoDay.getRfdl() + infoDay.getJhjxss() + infoDay.getFjhjxss() +
                    infoDay.getXdss() + infoDay.getSlss() + infoDay.getXnss());
            infoDays.add(infoDay);
        }
        turbineInfoDayService.saveOrUpdateBatch(infoDays);
    }*/

    //此处加公式
    public void calcStationSspjfs() {
        List<PointInfo> fsEntity = getEntity("AI066", "turbine");
        String keys = pointInfos2Keys(fsEntity);
        Map<String, PointData> latest = adapter.getLatest(goldenUri(), keys);
        Map<String, List<String>> listMap = fsEntity.stream().collect(Collectors.groupingBy(PointInfo::getStationId, Collectors.mapping(PointInfo::getPointKey, Collectors.toList())));

        Map<String, String> entityMap = getEntityMap("SSPJFS", "station");

        List<PointData> tsData = new ArrayList<>();
        listMap.forEach((stId, keyList) -> {
            double v = keyList.stream().mapToDouble(key -> latest.get(key).getValue()).average().orElse(0.0);
            PointData data = new PointData();
            data.setTs(System.currentTimeMillis());
            data.setTagName(entityMap.get(stId));
            data.setDoubleValue(v);
            tsData.add(data);
        });
        adapter.writeHistoryBatch(taosUri(), tsData);
    }


    public void calcTurbine5s2(Date date) {
        //date当天零点
        DateTime time = DateUtil.beginOfDay(date);
        //date昨天零点
        DateTime time0 = DateUtil.offsetDay(time, -1);
        //风速
        List<PointInfo> entityFs = getEntity("AI066", "turbine");
        //功率
        List<PointInfo> entityGl = getEntity("AI114", "turbine");
        getSnapDataByEntity(entityFs, time0, time, 15);
        getSnapDataByEntity(entityGl, time0, time, 15);

        List<PointInfo> ztMapMap = calcTurbineZt(time0, time, entityFs, entityGl);
        Map<String, Map<String, PointInfo>> ztMapMapInfos = ztMapMap.stream().collect(
                Collectors.groupingBy(PointInfo::getStationId, Collectors.toMap(PointInfo::getTurbineId, Function.identity())));
        Map<String, TurbineInfoDay> dayMap = getTurbineinfoMap(time0, entityFs);

        List<TurbineInfoDay> infoDays = new ArrayList<>();
        Map<String, Map<String, List<PointData>>> fsMapMap = entityFs.stream().collect(Collectors.groupingBy(PointInfo::getStationId,
                Collectors.toMap(PointInfo::getTurbineId, PointInfo::getPointDatas)));
        Map<String, Map<String, List<PointData>>> glMapMap = entityGl.stream().collect(Collectors.groupingBy(PointInfo::getStationId,
                Collectors.toMap(PointInfo::getTurbineId, PointInfo::getPointDatas)));

        ztMapMapInfos.forEach((stId, ztMapInfo) -> ztMapInfo.forEach((wtId, ztInfo) -> {
            //0 待机，1 手动停机，2 正常发电，3 发电降出力，4 故障，5 故障受累，6 检修，7 检修受累，8 限电降出力，
            // 9 限电停机，10 电网受累，11 环境受累，12 通讯中断，13 设备离线
            TurbineInfoDay infoDay = dayMap.get(wtId);
            Map<String, Double> loss = getTurbinePowerLoss(infoDay.getRfdl(), ztMapMapInfos.get(stId).get(wtId), fsMapMap.get(stId).get(wtId), glMapMap.get(stId).get(wtId));
            infoDay.setJhjxss(loss.get("jxss") + loss.get("sdtj"));
            infoDay.setFjhjxss(loss.get("gzss") + loss.get("djss") + loss.get("fdjcl"));
            infoDay.setXdss(loss.get("xdjcl") + loss.get("xdtj"));
            infoDay.setSlss(0.0);
            if (infoDay.getRfdl() == 0) {
                infoDay.setXnss(0.0);
            } else {
                infoDay.setXnss(loss.get("xnss"));
            }
            infoDay.setLlfdl(infoDay.getRfdl() + infoDay.getJhjxss() + infoDay.getFjhjxss() +
                    infoDay.getXdss() + infoDay.getSlss() + infoDay.getXnss());
            infoDays.add(infoDay);
        }));
        turbineInfoDayService.saveOrUpdateBatch(infoDays);
    }

    public List<PointInfo> calcTurbineZt(Date start, Date end, List<PointInfo> fsInfos, List<PointInfo> glInfos) {

        List<PointInfo> turbineZt = calcTurbineDizt(start, end, 15);
        List<PointInfo> turbineAizt = calcTurbineAizt(start, end, 15);
        turbineZt.addAll(turbineAizt);
        Map<String, Map<String, PointInfo>> ztMapMap = turbineZt.stream().collect(Collectors.groupingBy(PointInfo::getStationId,
                Collectors.toMap(PointInfo::getTurbineId, Function.identity())));

        //AGC
        List<PointInfo> entityAgc = getEntity("AGC002", "booster");
        getSnapDataByEntity(entityAgc, start, end, 15);
        //出线
        List<PointInfo> entityCx = getEntity("AGC001", "booster");
        getSnapDataByEntity(entityCx, start, end, 15);
        //叶轮转速给定
        List<PointInfo> entityYlzsgd = getEntity("AI110", "turbine");
        getSnapDataByEntity(entityYlzsgd, start, end, 15);

        Map<String, PointInfo> collectAgc = entityAgc.stream().collect(Collectors.toMap(PointInfo::getStationId, Function.identity()));
        Map<String, PointInfo> collectCx = entityCx.stream().collect(Collectors.toMap(PointInfo::getStationId, Function.identity()));
        Map<String, Map<String, List<PointData>>> collectYlzsgd = entityYlzsgd.stream().collect(Collectors.groupingBy(PointInfo::getStationId,
                Collectors.toMap(PointInfo::getTurbineId, PointInfo::getPointDatas)));
        Map<String, Map<String, PointInfo>> fsMapMap = fsInfos.stream().collect(Collectors.groupingBy(PointInfo::getStationId,
                Collectors.toMap(PointInfo::getTurbineId, Function.identity())));
        Map<String, Map<String, List<PointData>>> glMapMap = glInfos.stream().collect(Collectors.groupingBy(PointInfo::getStationId,
                Collectors.toMap(PointInfo::getTurbineId, PointInfo::getPointDatas)));

        ztMapMap.forEach((stId, ztMap) -> {
            PointInfo agcInfo = collectAgc.get(stId);
            PointInfo cxInfo = collectCx.get(stId);
            Map<String, PointInfo> fsMap = fsMapMap.get(stId);

            Map<String, List<PointData>> pdsZsglMap = new HashMap<>();
            ztMap.forEach((wtId, zt) -> {
                List<PointData> peek = fsMap.get(wtId).getPointDatas().stream().peek(pd -> pd.setDoubleValue(NumberUtil.round(pd.getValue() > 25 ? 25.0
                        : pd.getValue(), 2).doubleValue())).collect(Collectors.toList());
                fsMap.get(wtId).setPointDatas(peek);
                List<PointData> zsglSnap = fsMap.get(wtId).getPointDatas().stream().map(pd -> {
                    Double v = CalcCache.fitcoef.get(wtId).get(pd.getValue());
                    return new PointData(pd.getTs(), v == null ? 0 : v);
                }).collect(Collectors.toList());
                pdsZsglMap.put(wtId, zsglSnap);
            });
            List<PointData> agcc = agcInfo.getPointDatas().stream().peek(agc -> {
                agc.setDoubleValue(agc.getValue() * agcInfo.getCoef());
                agc.setLongValue(0L);
            }).collect(Collectors.toList());
            agcInfo.setPointDatas(agcc);
            List<PointData> cxc = cxInfo.getPointDatas().stream().peek(cx -> {
                cx.setDoubleValue(cx.getValue() * cxInfo.getCoef());
                cx.setLongValue(0L);
            }).collect(Collectors.toList());
            cxInfo.setPointDatas(cxc);

            //风机风速、功率->场站风速、功率
//            List<PointData> firstFs = new ArrayList<>();
//            List<PointData> firstGl = new ArrayList<>();
            List<PointData> firstZsgl = new ArrayList<>();
            double v1, v2, v3;
            for (int i = 0; i < 5760; i++) {
                int finalI = i;
                long ts = start.getTime() + i * 15000;
//                v1 = fsMap.values().stream().mapToDouble(pds -> pds.getPointDatas().get(finalI).getValue()).average().orElse(0.0);
//                v2 = glMap.values().stream().mapToDouble(pds -> pds.getPointDatas().get(finalI).getValue()).sum();
                v3 = pdsZsglMap.values().stream().mapToDouble(pds -> pds.get(finalI).getValue()).sum();
//                firstFs.add(new PointData(ts, v1));
//                firstGl.add(new PointData(ts, v2));
                firstZsgl.add(new PointData(ts, v3));
            }

            List<PointData> czxd = calcStationXd2(agcInfo, cxInfo.getPointDatas(), firstZsgl);
            ztMap.forEach((wtId, ztInfo) -> {
                List<PointData> fss = fsMap.get(wtId).getPointDatas();
                List<PointData> gls = glMapMap.get(stId).get(wtId);
                //叶轮转速给定
                List<PointData> ylzsgds = collectYlzsgd.get(stId).get(wtId);
                calcTurbineXd(ztInfo, gls, fss, ylzsgds, czxd);
            });
        });
        return turbineZt;
    }

    public void calcTurbineXd(PointInfo ztInfo, List<PointData> gls, List<PointData> fss, List<PointData> ylzsgds, List<PointData> czxd) {
        Map<String, EquipmentModel> map = equipmentModelService.map();
        Double capacity = map.get(ztInfo.getSpare()).getPowerProduction();
        List<PointData> zts = ztInfo.getPointDatas();
        for (int i = 0; i < 5760; i++) {
            double ssgl = gls.get(i).getValue();
            double ssfs = fss.get(i).getValue();
            double ylzsgd = ylzsgds.get(i).getValue();

            if (czxd.get(i).isBooleanValue() && ssgl < capacity * 0.9) {
                if (ssfs >= 12) {
                    zts.get(i).setDoubleValue(8.0);
                }
                if (ylzsgd != 0 && ylzsgd < 17.3) {//降出力
                    zts.get(i).setDoubleValue(8.0);
                }
            }
        }
    }

    //此处加公式
    public List<PointData> calcStationXd2(PointInfo agcInfo, List<PointData> cxSnap, List<PointData> zsglSnap) {
        String stId = agcInfo.getStationId();

        List<PointData> agcSnap = agcInfo.getPointDatas();
        List<PointData> zsgl5s = get5Avg(zsglSnap);
        List<PointData> agc5s = get5Avg(agcSnap);
        List<PointData> cx5s = get5Avg(cxSnap);
        //场站限电
        List<PointData> czxd = zsglSnap.stream().map(s -> new PointData(s.getTs(), 0.0)).collect(Collectors.toList());
        //之前是否限电
        boolean iszqxd = false;
        for (int i = 0; i < 5760; i++) {
            boolean isxd = false;
            double zsgl = zsglSnap.get(i).getValue();
            double zsgl5 = zsgl5s.get(i).getValue();
            double agc = agcSnap.get(i).getValue();
            double agc5 = agc5s.get(i).getValue();
            double cxgl = cxSnap.get(i).getValue();
            double cxgl5 = cx5s.get(i).getValue();

            boolean k;   //agc一直不变
            //第一次初始化复制实时数据到缓存
            if (CalcCache.powerCache.get(stId) == null || CalcCache.powerCache.get(stId) != agc) {
                CalcCache.powerCache.put(stId, agc);
                k = false;
            } else {
                k = true;
            }
            if (agc != 0) {
                //如果场站限电状态为不限电
                if (zsgl5 >= agcInfo.getSpare2() * 40) {
                    if (agc5 <= cxgl5) {
                        isxd = true;
                    } else if (iszqxd) {
                        if (zsgl / agc > 1.15) {
                            isxd = true;
                        } else if (zsgl > agc && agc5 - cxgl5 < 400) {
                            isxd = true;
                        }
                    } else if (zsgl / agc >= 1.2 && agc - cxgl <= 200) {
                        isxd = true;
                    }
                } else if (k) {
                    if (zsgl / agc >= 1.1 && agc5 - cxgl5 <= 200) {
                        isxd = true;
                    }
                }
            }
            czxd.get(i).setBooleanValue(isxd);
            iszqxd = isxd;
        }
        return czxd;
    }

    private List<PointData> get5Avg(List<PointData> pointData) {
        List<PointData> result = new ArrayList<>();
        for (int i = 0; i < pointData.size(); i++) {
            PointData data = new PointData();
            data.setTs(pointData.get(i).getTs());
            double v;
            if (i > 4) {
                v = (pointData.get(i).getValue() + pointData.get(i - 1).getValue() + pointData.get(i - 2).getValue() + pointData.get(i - 3).getValue() + pointData.get(i - 4).getValue()) / 5;
            } else {
                v = pointData.get(i).getValue();
            }
            data.setDoubleValue(v);
            result.add(data);
        }
        return result;
    }


    public List<PointInfo> calcTurbineAizt(Date start, Date end, int interval) {
        List<PointInfo> entityAiZt = getEntity("AI422", "state");
        List<StateAi> list = stateAiService.list();
        Map<String, Map<Integer, Integer>> collectAi = list.stream().collect(Collectors.groupingBy(
                StateAi::getModel, Collectors.toMap(StateAi::getOriginalState, StateAi::getMappingState)));
        getSnapDataByEntity(entityAiZt, start, end, interval);
        for (PointInfo info : entityAiZt) {
            List<PointData> peek = info.getPointDatas().stream().peek(pd -> {
                Integer m = collectAi.get(info.getSpare()).get((int) pd.getValue());
                if (m == null) m = 2;
                pd.setDoubleValue(m);
            }).collect(Collectors.toList());
            info.setPointDatas(peek);
        }
        return entityAiZt;
    }

    public List<PointInfo> calcTurbineDizt(Date start, Date end, int interval) {
        List<PointInfo> entity = new ArrayList<>();
        List<PointInfo> entity0 = getEntity("MX000", "state");
        List<PointInfo> entity1 = getEntity("MX001", "state");
        List<PointInfo> entity2 = getEntity("MX002", "state");
        List<PointInfo> entity4 = getEntity("MX004", "state");
        List<PointInfo> entity6 = getEntity("MX006", "state");
        entity.addAll(entity0);
        entity.addAll(entity1);
        entity.addAll(entity2);
        entity.addAll(entity4);
        entity.addAll(entity6);
        List<String> keys = entity.stream().map(PointInfo::getPointKey).collect(Collectors.toList());
        Map<String, PointData> latest = adapter.getHistorySection(goldenUri(), String.join(",", keys), start.getTime());

        Map<String, Map<String, PointInfo>> wtUcPis = entity.stream().collect(Collectors.groupingBy(PointInfo::getTurbineId, Collectors.toMap(PointInfo::getUniformCode, Function.identity())));
        wtUcPis.forEach((wtId, map) -> {
            map.forEach((uc, pi) -> {
                List<PointData> raw = adapter.getHistoryRaw(goldenUri(), pi.getPointKey(), start.getTime(), end.getTime());
                List<PointData> ds = boolPointDatasFull(latest.get(pi.getPointKey()).isBooleanValue(), raw, start.getTime(), end.getTime(), interval);
                pi.setPointDatas(ds);
                ThreadUtil.sleep(20);
            });
            List<PointData> mx000 = map.get("MX000").getPointDatas();
            PointData data0;
            for (int i = 0; i < mx000.size(); i++) {
                data0 = mx000.get(i);
                if (data0.getValue() == 1.0) {
                    data0.setDoubleValue(0.0);
                    data0.setBooleanValue(false);
                } else if (map.get("MX001").getPointDatas().get(i).getValue() == 1.0) {
                    data0.setDoubleValue(1.0);
                } else if (map.get("MX002").getPointDatas().get(i).getValue() == 1.0) {
                    data0.setDoubleValue(2.0);
                } else if (map.get("MX004").getPointDatas().get(i).getValue() == 1.0) {
                    data0.setDoubleValue(4.0);
                } else if (map.get("MX006").getPointDatas().get(i).getValue() == 1.0) {
                    data0.setDoubleValue(6.0);
                } else {
//                    System.out.println(wtId + data0.getTs() + "：di无对应状态！");
                    data0.setDoubleValue(2.0);
                }
            }
            map.get("MX001").setPointDatas(null);
            map.get("MX002").setPointDatas(null);
            map.get("MX004").setPointDatas(null);
            map.get("MX006").setPointDatas(null);
        });
        return entity0;
    }

    public PointInfo calcTurbineAizt2(PointInfo entityAiZt, Map<String, Map<Integer, Integer>> collectAi, Date start, Date end, int interval) {
        if (entityAiZt == null) return null;
        getSnapDataByEntity(entityAiZt, start, end, interval);
        Map<Integer, Integer> integerMap = collectAi.get(entityAiZt.getSpare());
        List<PointData> data = entityAiZt.getPointDatas().stream().peek(pd -> {
            Integer m = integerMap.get((int) pd.getValue());
            if (m == null) m = 2;
            pd.setDoubleValue(m);
        }).collect(Collectors.toList());
        entityAiZt.setPointDatas(data);
        return entityAiZt;
    }

    public PointInfo calcTurbineDizt2(Map<String, PointInfo> wtucpi, Map<String, PointData> latest, Date start, Date end, int interval) {
        if (wtucpi == null) return null;
        wtucpi.forEach((uc, pi) -> {
            List<PointData> raw = adapter.getHistoryRaw(goldenUri(), pi.getPointKey(), start.getTime(), end.getTime());
            List<PointData> ds = boolPointDatasFull(latest.get(pi.getPointKey()).isBooleanValue(), raw, start.getTime(), end.getTime(), interval);
            pi.setPointDatas(ds);
            ThreadUtil.sleep(20);
        });
        PointInfo mx000 = wtucpi.get("MX000");
        PointData data0;
        for (int i = 0; i < mx000.getPointDatas().size(); i++) {
            data0 = mx000.getPointDatas().get(i);
            if (data0.getValue() == 1.0) {
                data0.setDoubleValue(0.0);
                data0.setBooleanValue(false);
            } else if (wtucpi.get("MX001").getPointDatas().get(i).getValue() == 1.0) {
                data0.setDoubleValue(1.0);
            } else if (wtucpi.get("MX002").getPointDatas().get(i).getValue() == 1.0) {
                data0.setDoubleValue(2.0);
            } else if (wtucpi.get("MX004").getPointDatas().get(i).getValue() == 1.0) {
                data0.setDoubleValue(4.0);
            } else if (wtucpi.get("MX006").getPointDatas().get(i).getValue() == 1.0) {
                data0.setDoubleValue(6.0);
            } else {
                System.out.println(mx000.getTurbineId() + data0.getTs() + "：di无对应状态！");
                data0.setDoubleValue(2.0);
            }
        }
        wtucpi.get("MX001").setPointDatas(null);
        wtucpi.get("MX002").setPointDatas(null);
        wtucpi.get("MX004").setPointDatas(null);
        wtucpi.get("MX006").setPointDatas(null);
        return mx000;
    }

    public List<PointData> boolPointDatasFull(boolean v, List<PointData> data, long startTime, long endTime, int interval) {
        int j = 0, m = 0;
        List<PointData> data2 = new ArrayList<>();
        for (long i = startTime; i < endTime; i += interval * 1000L) {
            PointData dt = new PointData();
            dt.setTs(i);
            data2.add(dt);
            //超出范围
            if (j >= data.size() - 1) continue;
            if (i < data.get(j).getTs()) {
                if (m == 0) {
                    dt.setBooleanValue(v);
                } else {
                    dt.setBooleanValue(data.get(j - 1).isBooleanValue());
                }
            } else {
                dt.setBooleanValue(data.get(j).isBooleanValue());
                j++;
                m++;
            }
        }
        return data2;
    }

    public void calcGlqxnh(Date start, Date end) {
        //风速
        List<PointInfo> entityFs = getEntity("AI066", "turbine");
        //功率
        List<PointInfo> entityGl = getEntity("AI114", "turbine");
        Map<String, PointInfo> glMap = entityGl.stream().collect(Collectors.toMap(PointInfo::getTurbineId, Function.identity()));

        Map<String, EquipmentModel> map = equipmentModelService.map();

        List<PointInfo> entity = new ArrayList<>();
        List<PointInfo> entity0 = getEntity("MX000", "state");
        List<PointInfo> entity1 = getEntity("MX001", "state");
        List<PointInfo> entity2 = getEntity("MX002", "state");
        List<PointInfo> entity4 = getEntity("MX004", "state");
        List<PointInfo> entity6 = getEntity("MX006", "state");
        entity.addAll(entity0);
        entity.addAll(entity1);
        entity.addAll(entity2);
        entity.addAll(entity4);
        entity.addAll(entity6);
        List<String> keys = entity.stream().map(PointInfo::getPointKey).collect(Collectors.toList());
        Map<String, PointData> latest = adapter.getHistorySection(goldenUri(), String.join(",", keys), start.getTime());
        Map<String, Map<String, PointInfo>> wtUcPis = entity.stream().collect(Collectors.groupingBy(PointInfo::getTurbineId, Collectors.toMap(PointInfo::getUniformCode, Function.identity())));

        List<PointInfo> entityAiZt = getEntity("AI422", "state");
        Map<String, PointInfo> aiztMap = entityAiZt.stream().collect(Collectors.toMap(PointInfo::getTurbineId, Function.identity()));
        List<StateAi> list = stateAiService.list();
        Map<String, Map<Integer, Integer>> collectAi = list.stream().collect(Collectors.groupingBy(
                StateAi::getModel, Collectors.toMap(StateAi::getOriginalState, StateAi::getMappingState)));

//        Map<String, Map<Double,Double>> fitMap = new HashMap<>();
        for (PointInfo ef : entityFs) {
            String wtId = ef.getTurbineId();
            PointInfo glInfo = glMap.get(wtId);
            getSnapDataByEntity(ef, start, end, 60);
            getSnapDataByEntity(glInfo, start, end, 60);
            List<PointData> peek = ef.getPointDatas().stream().peek(pd -> pd.setDoubleValue(
                    NumberUtil.round(pd.getValue(), 2).doubleValue())).collect(Collectors.toList());
            ef.setPointDatas(peek);

            PointInfo turbineZt = calcTurbineDizt2(wtUcPis.get(wtId), latest, start, end, 60);
            PointInfo turbineAizt = calcTurbineAizt2(aiztMap.get(wtId), collectAi, start, end, 60);
            Map<Double, Double> fit = new TreeMap<>();
            if (turbineZt != null) {
                double capacity = map.get(turbineZt.getSpare()).getPowerProduction();
                fit = dataProcessAndFit(ef, glInfo, turbineZt, CalcCache.bzgl.get(turbineZt.getSpare()), capacity);
//                fitMap.put(wtId, fit);
                turbineZt.setPointDatas(null);
            }
            if (turbineAizt != null) {
                double capacity = map.get(turbineAizt.getSpare()).getPowerProduction();
                fit = dataProcessAndFit(ef, glInfo, turbineAizt, CalcCache.bzgl.get(turbineAizt.getSpare()), capacity);
//                fitMap.put(wtId, fit);
                turbineAizt.setPointDatas(null);
            }
            ef.setPointDatas(null);
            glInfo.setPointDatas(null);
            stringRedisTemplate.opsForValue().set("edfs:" + end.getMonth() + ":" + wtId, JSON.toJSONString(fit));
        }
        System.out.println("苹果天涯");
//        stringRedisTemplate.opsForValue().set("glqxnh", JSON.toJSONString(fitMap));
    }


    public Map<Double, Double> dataProcessAndFit(PointInfo fsPI, PointInfo glPI, PointInfo ztPI, Map<Double, Double> modelPowerMap, double capacity) {
        List<PointData> fsPds = fsPI.getPointDatas();
        List<PointData> glPds = glPI.getPointDatas();
        List<PointData> ztPds = ztPI.getPointDatas();
        WeightedObservedPoints points = new WeightedObservedPoints();
        //数据过滤 0正常，1过滤掉
        if (fsPds.size() != glPds.size() || glPds.size() != ztPds.size()) return new HashMap<>();

        Double bzv;
        for (int i = 0; i < ztPds.size(); i++) {
            double fs = fsPds.get(i).getValue();
            double gl = glPds.get(i).getValue();
            // 过滤非并网值  风机状态不等于2
            if (ztPds.get(i).getValue() != 2.0) {
                //
            } else if (fs < 0 || fs > 25 || gl < 0 || gl > capacity * 1.05) {// 按给定风速功率过滤
                //
            } else {
                bzv = modelPowerMap.get(fs);
                if (bzv == null || bzv == 0.0) {
                    points.add(fs, gl);
                    continue;
                }
                double k = gl / bzv;  //功率曲线偏差: 保证功率/实际功率   k:偏差百分比
                if (k < 0.61 || k > 1.25) {
                    //
                } else {
                    points.add(fs, gl);
                }
            }
        }
        Map<Double, Double> glyc = new TreeMap<>();
        PolynomialCurveFitter fitter = PolynomialCurveFitter.create(4);
        try {
            double[] result = fitter.fit(points.toList());


            double min = calcMin(result);
            System.out.println(ztPI.getTurbineId());
            System.out.println(ztPI.getSpare());
            System.out.println(min);
            double[] max = calcMax(result);
            if (min == 0 || max[0] == 0 || max[1] == 0) {
                System.out.println();
            }
            System.out.println(max[0] + "," + max[1]);
            double ru;
            for (double i = 0; i < 25; i += 0.01) {
                i = NumberUtil.round(i, 2).doubleValue();
                if (i < 3) {
                    ru = 0.0;
                } else if (i < min) {
                    ru = modelPowerMap.get(i);
                } else if (i < max[0]) {
                    ru = calcPoly(i, result);
                } else {
                    ru = max[1];
                }
                glyc.put(i, NumberUtil.round(ru, 2).doubleValue());
            }

        } catch (Exception e) {
            System.out.println(ztPI.getTurbineId());
            System.out.println(ztPI.getSpare());
            System.out.println(e.getMessage());
        }
        return glyc;
    }

    public double calcMin(double[] coef) {
        double minX = 0, minY = 9000;
        for (double x = 0; x < 8; x += 0.01) {
            double y = calcPoly(x, coef);
            if (y < minY) {
                minY = y;
                minX = x;
            }
        }
        return minX;
    }

    public double[] calcMax(double[] coef) {
        double[] a = new double[2];
        for (double x = 8; x < 16; x += 0.01) {
            double y = calcPoly(x, coef);
            if (y > a[1]) {
                a[0] = x;
                a[1] = y;
            }
        }
        return a;
    }

    public void printResult(double[] r, double accuracy) {

        for (double index = 0; index < 25; index += accuracy) {
            System.out.println("[" + index + "," + calcPoly(index, r) + "],");
        }
    }

    public void getSnapDataByEntity(List<PointInfo> entity, URI uri, Date start, Date end, int interval) {
        for (PointInfo info : entity) {
            List<PointData> snap = adapter.getHistorySnap(uri, info.getPointKey(), start.getTime(), end.getTime(), interval);
            ThreadUtil.sleep(20);
            info.setPointDatas(snap);
        }
    }

    public void getSnapDataByEntity(PointInfo entity, URI uri, Date start, Date end, int interval) {
        getSnapDataByEntity(Collections.singletonList(entity), uri, start, end, interval);
    }

    public void getSnapDataByEntity(List<PointInfo> entity, Date start, Date end, int interval) {
        getSnapDataByEntity(entity, goldenUri(), start, end, interval);
    }

    public void getSnapDataByEntity(PointInfo entity, Date start, Date end, int interval) {
        getSnapDataByEntity(entity, goldenUri(), start, end, interval);
    }


    public double calcPoly(String wtId, double value) {
        return CalcCache.fitcoef.get(wtId).get(value);
    }

    public double calcPoly(double x, double[] factor) {
        double y = 0;
        for (int deg = 0; deg < factor.length; deg++) {
            y += Math.pow(x, deg) * factor[deg];
        }
        return y;
    }


    //切入切出风速

    public void cutInWindSpeed() {
        //date当天零点
        DateTime timeNow = DateUtil.beginOfDay(new Date());
        //date昨天零点
        DateTime timeBegin = DateUtil.offsetDay(timeNow, -1);
        List<PointInfo> turbineZt = calcTurbineAizt(timeBegin, timeNow, 60);
        List<PointInfo> turbineZtDI = calcTurbineDizt(timeBegin, timeNow, 60);
        turbineZt.addAll(turbineZtDI);

        //所有风机的风速测点
        QueryWrapper<PointInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uniform_code", "AI066");

        List<PointInfo> pointInfos = getEntity("AI066", "turbine");
//        List<PointInfo> pointInfos = pointInfo.selectList(queryWrapper);

        //定义切入风速map集合
        ConcurrentHashMap<String, ConcurrentHashMap<String, Double>> mapIn = new ConcurrentHashMap<>();

        //定义切出风速集合
        ConcurrentHashMap<String, ConcurrentHashMap<String, Double>> mapOut = new ConcurrentHashMap<>();


        //插入集合
        List<TurbineInfoDay > interest = new ArrayList<>();
        //更新集合
        List<TurbineInfoDay > update = new ArrayList<>();
        //遍历每台风机，取出每台风机的pointDatas
        for (PointInfo turbine : turbineZt) {

            mapIn.put(turbine.getTurbineId(), new ConcurrentHashMap<>());
            mapOut.put(turbine.getTurbineId(), new ConcurrentHashMap<>());

            List<PointData> pointDatas = turbine.getPointDatas();

            //风速测点key
            String windSpeedKey = null;


            //遍历pointInfos，找出pointData1的id和pointInfos中相等的，取出pointInfo的pointKey
            for (PointInfo info : pointInfos) {
                if (Objects.equals(turbine.getTurbineId(), info.getTurbineId())) {
                    windSpeedKey = info.getPointKey();
                }
            }


            //遍历pointDatas,取出当前状态和后一个状态
            for (int k = 1; k < pointDatas.size(); k++) {
                PointData pointData1 = pointDatas.get(k - 1);
                PointData pointData2 = pointDatas.get(k);
                double value1 = pointData1.getValue();
                double value2 = pointData2.getValue();
                //切入时间
                long ts1;
                //切出时间
                long ts2;

                //如果1的值为0,2的值为2，则为切入状态
                if (value1 == 0 && value2 == 2) {
                    ts1 = pointData2.getTs();
//                    String stringDate = DateUtil.date(ts1).toString("yyyy-MM-dd HH:mm:ss");
//                    System.out.println(turbine.getTurbineId() + "切入" + stringDate);
                    //切入时间前5分钟
                    long ts11 = ts1 - 300000;
                    //根据风速key,从适配器取切入前5分钟的所有风速
                    List<PointData> pointDatas1 = adapter.getHistorySnap(goldenUri(), windSpeedKey, ts11, ts1, 10);
                    //平均所有风速即为平均切入风速
                    double avgCutInWindSpeed = pointDatas1.stream().mapToDouble(PointData::getValue).average().orElse(0);
//                    System.out.println(turbine.getTurbineId() + "切入风速" + avgCutInWindSpeed);

                    //存入map集合，外层key为turbineId，内层key为ts1，value为平均切入风速

                    mapIn.get(turbine.getTurbineId()).put(String.valueOf(ts1), avgCutInWindSpeed);

                }

                //切出
                if (value1 == 2 && value2 != 2) {
                    ts2 = pointData2.getTs();
                    String stringDate = DateUtil.date(ts2).toString("yyyy-MM-dd HH:mm:ss");
//                    System.out.println(turbine.getTurbineId() + "切出" + stringDate);
                    //切出时间前5分钟
                    long ts22 = ts2 - 300000;
                    List<PointData> pointDatas2 = adapter.getHistorySnap(goldenUri(), windSpeedKey, ts22, ts2, 10);
                    double avgCutOutWindSpeed = pointDatas2.stream().mapToDouble(PointData::getValue).average().orElse(0);
//                    System.out.println(turbine.getTurbineId() + "切出风速" + avgCutOutWindSpeed);

                    //存入map集合，外层key为turbineId，内层key为ts2，value为平均切出风速

                    mapOut.get(turbine.getTurbineId()).put(String.valueOf(ts2), avgCutOutWindSpeed);
                }

            }
            //遍历map集合，取出每个风机的所有切入风速，算一个平均值
            ConcurrentHashMap<String, Double> mapTurbineValues = mapIn.get(turbine.getTurbineId());
            //平均切入风速
            double avgCutInWindSpeed = 0;
            if (mapTurbineValues != null) {
                AtomicReference<Double> sum = new AtomicReference<>(0.0);
                //遍历mapTurbineValues，V大于5的舍弃，剩余算平均值
                for (String key : mapTurbineValues.keySet()) {
                    if (mapTurbineValues.get(key) > 5) {
                        mapTurbineValues.remove(key);
                    }
                }
                mapTurbineValues.forEach((k1, v) -> {
                    sum.updateAndGet(v1 -> v1 + v);
                });

                //如果值为空则置0
                if (sum.get() == 0) {
                    avgCutInWindSpeed = 0;
                } else {
                    avgCutInWindSpeed = sum.get() / mapTurbineValues.size();
                }
                System.out.println(turbine.getTurbineId() + "切入平均风速" + avgCutInWindSpeed + "时间" + timeBegin);
            }

            //遍历map集合，取出每个风机的所有切出风速，算一个平均值
            ConcurrentHashMap<String, Double> mapTurbineValues2 = mapOut.get(turbine.getTurbineId());

            double avgCutOutWindSpeed;
            if (mapTurbineValues2 != null) {
                AtomicReference<Double> sum = new AtomicReference<>(0.0);

                for (String key : mapTurbineValues2.keySet()) {
                    if (mapTurbineValues2.get(key) > 5) {
                        mapTurbineValues2.remove(key);
                    }
                }
                mapTurbineValues2.forEach((k2, v) -> {
                    sum.updateAndGet(v1 -> v1 + v);
                });

                if (sum.get() == 0) {
                    avgCutOutWindSpeed = 0;
                } else {
                    avgCutOutWindSpeed = sum.get() / mapTurbineValues2.size();
                }
                System.out.println(turbine.getTurbineId() + "切出平均风速" + avgCutOutWindSpeed + "时间" + timeBegin);
            }

            //存入数据库
            String turbineId = turbine.getTurbineId();
            Date jdkDate = timeBegin.toJdkDate();
            System.out.println(turbineId + " " + jdkDate);
            QueryWrapper<TurbineInfoDay> turbineInfoDayQueryWrapper = new QueryWrapper<>();
            turbineInfoDayQueryWrapper.eq("turbine_id", turbine.getTurbineId());
            turbineInfoDayQueryWrapper.eq("record_date", timeBegin.toJdkDate());
            TurbineInfoDay one = turbineInfoDayService.getOne(turbineInfoDayQueryWrapper);
            System.out.println(one);
            if (one == null) {
                TurbineInfoDay turbineInfoDay = new TurbineInfoDay();
                turbineInfoDay.setTurbineId(turbine.getTurbineId());
                turbineInfoDay.setRecordDate(timeBegin.toJdkDate());
                turbineInfoDay.setXfqrfs(avgCutInWindSpeed);
                System.out.println(turbineInfoDay);

                interest.add(turbineInfoDay);
//                turbineInfoDayService.save(turbineInfoDay);
            } else {
                one.setXfqrfs(avgCutInWindSpeed);
                System.out.println(one);
//                turbineInfoDayService.updateById(one);
                update.add(one);
            }

        }

        //        //批量插入
//        turbineInfoDayService.saveBatch(interest);
//        //批量更新
//        turbineInfoDayService.updateBatchById(update);
//        //批量插入或更新
        turbineInfoDayService.saveOrUpdateBatch(interest);
        turbineInfoDayService.saveOrUpdateBatch(update);
    }

    //算额定风速
    public void calcGlqxnh_edfs() {

        //date当天零点
        Date end = DateUtil.beginOfDay(new Date()).toJdkDate();
        //date昨天零点
        Date start = DateUtil.offsetDay(end, -1).toJdkDate();

        //风速
        List<PointInfo> entityFs = getEntity("AI066", "turbine");
        //功率
        List<PointInfo> entityGl = getEntity("AI114", "turbine");
        Map<String, PointInfo> glMap = entityGl.stream().collect(Collectors.toMap(PointInfo::getTurbineId, Function.identity()));

        Map<String, EquipmentModel> map = equipmentModelService.map();

        List<PointInfo> entity = new ArrayList<>();
        List<PointInfo> entity0 = getEntity("MX000", "state");
        List<PointInfo> entity1 = getEntity("MX001", "state");
        List<PointInfo> entity2 = getEntity("MX002", "state");
        List<PointInfo> entity4 = getEntity("MX004", "state");
        List<PointInfo> entity6 = getEntity("MX006", "state");
        entity.addAll(entity0);
        entity.addAll(entity1);
        entity.addAll(entity2);
        entity.addAll(entity4);
        entity.addAll(entity6);
        List<String> keys = entity.stream().map(PointInfo::getPointKey).collect(Collectors.toList());
        Map<String, PointData> latest = adapter.getHistorySection(goldenUri(), String.join(",", keys), start.getTime());
        Map<String, Map<String, PointInfo>> wtUcPis = entity.stream().collect(Collectors.groupingBy(PointInfo::getTurbineId, Collectors.toMap(PointInfo::getUniformCode, Function.identity())));

        List<PointInfo> entityAiZt = getEntity("AI422", "state");
        Map<String, PointInfo> aiztMap = entityAiZt.stream().collect(Collectors.toMap(PointInfo::getTurbineId, Function.identity()));
        List<StateAi> list = stateAiService.list();
        Map<String, Map<Integer, Integer>> collectAi = list.stream().collect(Collectors.groupingBy(
                StateAi::getModel, Collectors.toMap(StateAi::getOriginalState, StateAi::getMappingState)));

//        Map<String, Map<Double,Double>> fitMap = new HashMap<>();
        int i = 0;

        //插入集合
        List<TurbineInfoDay > interest = new ArrayList<>();
        //更新集合
        List<TurbineInfoDay > update = new ArrayList<>();



        for (PointInfo ef : entityFs) {
            String wtId = ef.getTurbineId();
            PointInfo glInfo = glMap.get(wtId);
            getSnapDataByEntity(ef, start, end, 60);
            getSnapDataByEntity(glInfo, start, end, 60);
            List<PointData> peek = ef.getPointDatas().stream().peek(pd -> pd.setDoubleValue(
                    NumberUtil.round(pd.getValue(), 2).doubleValue())).collect(Collectors.toList());
            ef.setPointDatas(peek);

            try {
                PointInfo turbineZt = calcTurbineDizt2(wtUcPis.get(wtId), latest, start, end, 60);
                PointInfo turbineAizt = calcTurbineAizt2(aiztMap.get(wtId), collectAi, start, end, 60);
                Map<Double, Double> fit = new TreeMap<>();
                double capacity = 2000;
                if (turbineZt != null) {
                    capacity = map.get(turbineZt.getSpare()).getPowerProduction();
                    fit = dataProcessAndFit(ef, glInfo, turbineZt, CalcCache.bzgl.get(turbineZt.getSpare()), capacity);
//                fitMap.put(wtId, fit);
                    turbineZt.setPointDatas(null);
                }
                if (turbineAizt != null) {
                    capacity = map.get(turbineAizt.getSpare()).getPowerProduction();
                    fit = dataProcessAndFit(ef, glInfo, turbineAizt, CalcCache.bzgl.get(turbineAizt.getSpare()), capacity);
//                fitMap.put(wtId, fit);
                    turbineAizt.setPointDatas(null);
                }
                ef.setPointDatas(null);
                glInfo.setPointDatas(null);

                //存redis
//            stringRedisTemplate.opsForValue().set("glqxnh:" + end.getMonth() + ":" + wtId, JSON.toJSONString(fit));


                //符合条件的风速和
                List<Double> listDouble = new ArrayList<>();
                //遍历fit集合，取出值与capacity相等的key
                if (!fit.isEmpty()) {
                    for (double key : fit.keySet()) {
                        Double v = fit.get(key);
                        //如果v-capacity的值小于10大于-10，则把key加入listDouble
                        if ((Math.abs(v - capacity) <= 10) && Math.abs(v - capacity) >= -10) {
                            listDouble.add(key);
                        }
                    }
                }
                //取出listDouble的值求平均值
                double agValue = 0;
                if (!listDouble.isEmpty()) {
                    for (Double aDouble : listDouble) {
                        agValue += aDouble;
                    }
                    agValue = agValue / listDouble.size();
                }
                System.out.println("wtId:" + wtId + "agValue平均额定风速:" + agValue);


                //存入数据库
                System.out.println(wtId + " " + start);
                QueryWrapper<TurbineInfoDay> turbineInfoDayQueryWrapper = new QueryWrapper<>();
                turbineInfoDayQueryWrapper.eq("turbine_id", wtId);
                turbineInfoDayQueryWrapper.eq("record_date", start);
                TurbineInfoDay one = turbineInfoDayService.getOne(turbineInfoDayQueryWrapper);
                System.out.println(one);
                if (one == null) {
                    TurbineInfoDay turbineInfoDay = new TurbineInfoDay();
                    turbineInfoDay.setTurbineId(wtId);
                    turbineInfoDay.setRecordDate(start);
                    turbineInfoDay.setEdfs(agValue);
                    System.out.println(turbineInfoDay);
//                    turbineInfoDayService.save(turbineInfoDay);
                    interest.add(turbineInfoDay);
                } else {
                    one.setEdfs(agValue);
                    System.out.println(one);
//                    turbineInfoDayService.updateById(one);
                    update.add(one);
                }

            }catch (Exception e) {
                System.out.println(wtId + " " + start);
            }



        }


        //        //批量插入
//        turbineInfoDayService.saveBatch(interest);
//        //批量更新
//        turbineInfoDayService.updateBatchById(update);
//        //批量插入或更新
        turbineInfoDayService.saveOrUpdateBatch(interest);
        turbineInfoDayService.saveOrUpdateBatch(update);




//        stringRedisTemplate.opsForValue().set("glqxnh", JSON.toJSONString(fitMap));
    }

    //环境温度
    public void ambientTemperature() {
        //date当天零点
        DateTime timeNow = DateUtil.beginOfDay(new Date());
        //date昨天零点
        DateTime timeBegin = DateUtil.offsetDay(timeNow, -1);


        //所有风机的温度
        QueryWrapper<PointInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uniform_code", "AI072");

        List<PointInfo> pointInfos = getEntity("AI072", "turbine");

        //插入集合
        List<TurbineInfoDay > interest = new ArrayList<>();
        //更新集合
        List<TurbineInfoDay > update = new ArrayList<>();


        //遍历pointInfos
        for (PointInfo turbine : pointInfos) {
            List<PointData> pointDatas = adapter.getHistorySnap(goldenUri(), turbine.getPointKey(), timeBegin.getTime(), timeNow.getTime(), 10);
            //遍历pointDatas,取出数据算平均值
            double avgCutInWindSpeed = 0;
            for (PointData pointData : pointDatas) {
                avgCutInWindSpeed += pointData.getValue();
            }
            avgCutInWindSpeed /= pointDatas.size();

            //存入数据库
            String turbineId = turbine.getTurbineId();
            Date jdkDate = timeBegin.toJdkDate();
            System.out.println(turbineId + " " + jdkDate);
            QueryWrapper<TurbineInfoDay> turbineInfoDayQueryWrapper = new QueryWrapper<>();
            turbineInfoDayQueryWrapper.eq("turbine_id", turbine.getTurbineId());
            turbineInfoDayQueryWrapper.eq("record_date", timeBegin.toJdkDate());
            TurbineInfoDay one = turbineInfoDayService.getOne(turbineInfoDayQueryWrapper);
            System.out.println(one);
            if (one == null) {
                TurbineInfoDay turbineInfoDay = new TurbineInfoDay();
                turbineInfoDay.setTurbineId(turbine.getTurbineId());
                turbineInfoDay.setRecordDate(timeBegin.toJdkDate());
                turbineInfoDay.setHjwd(avgCutInWindSpeed);
                System.out.println(turbineInfoDay);
                interest.add(turbineInfoDay);
//                turbineInfoDayService.save(turbineInfoDay);
            } else {
                one.setHjwd(avgCutInWindSpeed);
                System.out.println(one);
                update.add(one);
//                turbineInfoDayService.updateById(one);
            }

        }
//        //批量插入
//        turbineInfoDayService.saveBatch(interest);
//        //批量更新
//        turbineInfoDayService.updateBatchById(update);
//        //批量插入或更新
        turbineInfoDayService.saveOrUpdateBatch(interest);
        turbineInfoDayService.saveOrUpdateBatch(update);


    }



}



