package com.gyee.generation.service;//package com.gyee.generation.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gyee.common.contant.ContantXk;
import com.gyee.common.model.PointData;
import com.gyee.common.model.StringUtils;
import com.gyee.generation.init.CacheContext;
import com.gyee.generation.model.auto.*;
import com.gyee.generation.service.auto.*;
import com.gyee.generation.task.thread.EconWtAlysisDayThread;
import com.gyee.generation.util.DateUtils;
import com.gyee.generation.util.SnowflakeGenerator;
import com.gyee.generation.util.realtimesource.IEdosUtil;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class WtAlysisDayService {

    //    private static final Logger logger = LoggerFactory.getLogger(EquipmentInfo1Service.class);
    @Resource
    private IEdosUtil edosUtil;

    @Resource
    private IProEconWtAlysisDayService proEconWtAlysisDayService;

    @Resource
    private IProEconEquipmentInfoDay1Service proEconEquipmentInfoDay1Service;
    @Resource
    private IProEconEquipmentInfoDay2Service proEconEquipmentInfoDay2Service;
    @Resource
    private IProEconEquipmentInfoDay3Service proEconEquipmentInfoDay3Service;
    @Resource
    private IProEconEquipmentInfoDay4Service proEconEquipmentInfoDay4Service;

    @Resource
    @Qualifier("applicationTaskExecutor")
    private Executor executor;

    private Map<String, ProEconEquipmentInfoDay1> queryEquipmentInfoDay1(Date recordDate) {

        QueryWrapper<ProEconEquipmentInfoDay1> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("record_date", DateUtils.truncate(recordDate));
        List<ProEconEquipmentInfoDay1> iostls = proEconEquipmentInfoDay1Service.list(queryWrapper);
        //                .stream().filter(i-> i.getRecordDate().compareTo(DateUtils.truncate(recordDate)) == 0
        //                )
        //                .collect(Collectors.toList());
        //List转map
        Map<String, ProEconEquipmentInfoDay1> iostmap = iostls.stream().
                collect(Collectors.toMap(ProEconEquipmentInfoDay1::getWindturbineId, Function.identity(), (key1, key2) -> key2));
        return iostmap;
    }

    private Map<String, ProEconEquipmentInfoDay2> queryEquipmentInfoDay2(Date recordDate) {
        QueryWrapper<ProEconEquipmentInfoDay2> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("record_date", DateUtils.truncate(recordDate));
        List<ProEconEquipmentInfoDay2> iostls = proEconEquipmentInfoDay2Service.list(queryWrapper);
        //                .stream().filter(i-> i.getRecordDate().compareTo(DateUtils.truncate(recordDate)) == 0
        //                )
        //                .collect(Collectors.toList());
        //List转map
        Map<String, ProEconEquipmentInfoDay2> iostmap = iostls.stream().
                collect(Collectors.toMap(ProEconEquipmentInfoDay2::getWindturbineId, Function.identity(), (key1, key2) -> key2));
        return iostmap;
    }

    private Map<String, ProEconEquipmentInfoDay3> queryEquipmentInfoDay3(Date recordDate) {

        QueryWrapper<ProEconEquipmentInfoDay3> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("record_date", DateUtils.truncate(recordDate));
        List<ProEconEquipmentInfoDay3> iostls = proEconEquipmentInfoDay3Service.list(queryWrapper);
        //                .stream().filter(i-> i.getRecordDate().compareTo(DateUtils.truncate(recordDate)) == 0
        //                )
        //                .collect(Collectors.toList());
        //List转map
        Map<String, ProEconEquipmentInfoDay3> iostmap = iostls.stream().
                collect(Collectors.toMap(ProEconEquipmentInfoDay3::getWindturbineId, Function.identity(), (key1, key2) -> key2));
        return iostmap;
    }

    private Map<String, ProEconEquipmentInfoDay4> queryEquipmentInfoDay4(Date recordDate) {

        QueryWrapper<ProEconEquipmentInfoDay4> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("record_date", DateUtils.truncate(recordDate));
        List<ProEconEquipmentInfoDay4> iostls = proEconEquipmentInfoDay4Service.list(queryWrapper);
        //                .stream().filter(i-> i.getRecordDate().compareTo(DateUtils.truncate(recordDate)) == 0
        //                )
        //                .collect(Collectors.toList());
        //List转map
        Map<String, ProEconEquipmentInfoDay4> iostmap = iostls.stream().
                collect(Collectors.toMap(ProEconEquipmentInfoDay4::getWindturbineId, Function.identity(), (key1, key2) -> key2));
        return iostmap;
    }

    /**
     * 计算设备日信息
     */
    public void calEquipmentInfoDay(Date recordDate) throws Exception {
        Calendar c = Calendar.getInstance();
        c.setTime(recordDate);

        Date end = c.getTime();

        Date begin = DateUtils.truncate(c.getTime());

        //        //判断是否有重复记录，
        //        QueryWrapper<ProEconWtAlysisDay> queryWrapper = new QueryWrapper<>();
        //        queryWrapper.eq("record_date",DateUtils.truncate(recordDate));
        //        List<Long> idls = proEconWtAlysisDayService.list(queryWrapper).stream()
        ////                .filter(i -> i.getRecordDate().compareTo(DateUtils.truncate(recordDate))==0
        ////                        && CacheContext.wtmap.containsKey(i.getWindturbineId()))
        //                .map(ProEconWtAlysisDay::getId)
        //                .collect(Collectors.toList());
        //
        ////        if (idls.size() > 0) {
        ////
        ////            proEconWtAlysisDayService.removeByIds(idls);
        ////
        ////        }
        //
        //        List<Long> tempids=new ArrayList<>();
        //
        //        for(int i=0;i<idls.size();i++)
        //        {
        //            tempids.add(idls.get(i));
        //            if(tempids.size()==1000)
        //            {
        //                proEconWtAlysisDayService.removeByIds(tempids);
        //                tempids=new ArrayList<>();
        //            }
        //        }
        //
        //        if(!tempids.isEmpty())
        //        {
        //            proEconWtAlysisDayService.removeByIds(tempids);
        //        }

        Map<String, ProEconEquipmentInfoDay1> eqday1map = queryEquipmentInfoDay1(recordDate);
        Map<String, ProEconEquipmentInfoDay2> eqday2map = queryEquipmentInfoDay2(recordDate);
        Map<String, ProEconEquipmentInfoDay3> eqday3map = queryEquipmentInfoDay3(recordDate);
        Map<String, ProEconEquipmentInfoDay4> eqday4map = queryEquipmentInfoDay4(recordDate);

        List<ProEconWtAlysisDay> dayls = new ArrayList<>();


        List<ProBasicEquipment> wttemps = new ArrayList<>();

        for (ProBasicEquipment wt : CacheContext.wt_fjls) {


            wttemps.add(wt);
            if (wttemps.size() == 120) {

                final CountDownLatch latch = new CountDownLatch(120);
                for (ProBasicEquipment wt1 : wttemps) {
                    new Thread(new EconWtAlysisDayThread(executor, wt1, eqday1map,
                            eqday2map,
                            eqday3map,
                            eqday4map,
                            recordDate, end, begin, dayls,
                            edosUtil, c, proEconWtAlysisDayService, latch)).start();
                }
                latch.await();
                Thread.sleep(120);
                wttemps = new ArrayList<>();
            }

        }

        if (!wttemps.isEmpty()) {

            final CountDownLatch latch = new CountDownLatch(wttemps.size());
            for (ProBasicEquipment wt1 : wttemps) {
                new Thread(new EconWtAlysisDayThread(executor, wt1, eqday1map,
                        eqday2map,
                        eqday3map,
                        eqday4map,
                        recordDate, end, begin, dayls,
                        edosUtil, c, proEconWtAlysisDayService, latch)).start();
            }
            latch.await();
        }

        //判断是否有重复记录，
        QueryWrapper<ProEconWtAlysisDay> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("record_date", DateUtils.truncate(recordDate));
        List<Long> idls = proEconWtAlysisDayService.list(queryWrapper).stream()
                //                .filter(i -> i.getRecordDate().compareTo(DateUtils.truncate(recordDate))==0
                //                        && CacheContext.wtmap.containsKey(i.getWindturbineId()))
                .map(ProEconWtAlysisDay::getId)
                .collect(Collectors.toList());

        //        if (idls.size() > 0) {
        //
        //            proEconWtAlysisDayService.removeByIds(idls);
        //
        //        }

        List<Long> tempids = new ArrayList<>();

        for (int i = 0; i < idls.size(); i++) {
            tempids.add(idls.get(i));
            if (tempids.size() == 1000) {
                proEconWtAlysisDayService.removeByIds(tempids);
                tempids = new ArrayList<>();
            }
        }

        if (!tempids.isEmpty()) {
            proEconWtAlysisDayService.removeByIds(tempids);
        }


        List<ProEconWtAlysisDay> templs = new ArrayList<>();
        for (ProEconWtAlysisDay vo : dayls) {
            if (StringUtils.notEmp(vo)) {
                vo.setId(SnowflakeGenerator.generateId());
                templs.add(vo);
                if (templs.size() == 1000) {
                    proEconWtAlysisDayService.saveBatch(templs);
                    templs = new ArrayList<>();
                }
            }

        }

        if (!templs.isEmpty()) {
            proEconWtAlysisDayService.saveBatch(templs);
        }
        //        proEconWtAlysisDayService.saveBatch(dayls);
    }

    private void calSimple(ProEconWtAlysisDay pewp, Date end, Date begin, ProBasicEquipment wt, List<ProEconWtAlysisDay> pepidls) throws Exception {

        //*******************************************日信息统计*********************************************************/

        double lastState = -1;//上一分钟状态


        double bbhcs = 0;//不饱和次数

        Map<String, Map<String, ProBasicEquipmentPoint>> wtpAimap = CacheContext.wtpAimap;


        Map<String, ProBasicEquipmentPoint> aimap = wtpAimap.get(wt.getId());
        if (aimap.containsKey(ContantXk.SSQFZT)) {

            ProBasicEquipmentPoint point = aimap.get(ContantXk.SSQFZT);
            //按照分钟时间进行统计状态快照值
            List<PointData> pointls = edosUtil.getHistoryDatasSnap(point.getNemCode(), begin.getTime() / 1000, end.getTime() / 1000);
            if (!pointls.isEmpty()) {
                for (PointData po : pointls) {

                    if (po.getPointValueInDouble() >= 3) {
                        if (lastState != po.getPointValueInDouble()) {

                            //将当前状态保存到上一分钟状态
                            lastState = po.getPointValueInDouble();
                            //实时欠发大于等于3的次数加1
                            bbhcs++;
                        }

                    }

                }

            }

        }
        //日不饱和次数
        pewp.setRbbhcs(bbhcs);

        //*******************************************日信息统计*********************************************************/

        //*******************************************月信息统计*********************************************************/
        if (pepidls.isEmpty()) {
            pewp.setYbbhcs(pewp.getRbbhcs());

        } else {
            ProEconWtAlysisDay pepid = pepidls.get(0);

            pewp.setYbbhcs(StringUtils.round(pepid.getYbbhcs() + pewp.getRbbhcs(), 2));

        }
        //*******************************************月信息统计*********************************************************/

        //*******************************************年信息统计*********************************************************/
        if (pepidls.isEmpty()) {
            pewp.setNbbhcs(pewp.getRbbhcs());

        } else {


            ProEconWtAlysisDay pepid = pepidls.get(0);
            pewp.setNbbhcs(StringUtils.round(pepid.getNbbhcs() + pewp.getRbbhcs(), 2));

        }
        //*******************************************年信息统计*********************************************************/
    }

}







