package cn.gyee.tamplate.service.operation;

import cn.gyee.tamplate.contant.OpeContant;
import cn.gyee.tamplate.init.CacheContext;
import cn.gyee.tamplate.model.auto.Dutyschedule;
import cn.gyee.tamplate.model.auto.Operationrecord;
import cn.gyee.tamplate.model.auto.Windturbine;
import cn.gyee.tamplate.model.auto.Windturbinetestingpointai2;
import cn.gyee.tamplate.model.custom.PointData;
import cn.gyee.tamplate.model.operation.Operation;
import cn.gyee.tamplate.model.vo.OpeVo;
import cn.gyee.tamplate.service.IDutyscheduleService;
import cn.gyee.tamplate.service.IOperationrecordService;
import cn.gyee.tamplate.service.IWindturbineService;
import cn.gyee.tamplate.util.DateUtils;
import cn.gyee.tamplate.util.common.StringUtils;
import cn.gyee.tamplate.util.golden.EdosUtil;
import cn.gyee.tamplate.util.golden.IEdosUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sun.media.jfxmedia.logging.Logger;
import org.apache.catalina.Session;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName : OperationService
 * @Author : xieshengjie
 * @Date: 2021/1/18 15:56
 * @Description : 值际service
 */
@Service
public class OperationService {
    private static IEdosUtil edosUtil = new EdosUtil();
    @Resource
    private IDutyscheduleService dutyscheduleService;
    @Resource
    private IWindturbineService windturbineService;
    @Resource
    private IOperationrecordService operationrecordService;

    public Map<String,List<OpeVo>> opeMap(String beginDate, String endDate) throws ParseException{
        Date begin = DateUtils.parseDate(beginDate);
        Date end = DateUtils.parseDate(endDate);
        List<Dutyschedule> dutyList = dutyscheduleService.list();
        Map<String, Map<String, Windturbinetestingpointai2>> wtpointMap = CacheContext.wtpointMap;
        String[] points = OpeContant.opePoints.split(",");
        List<Windturbine> wtls = windturbineService.list();
        List<OpeVo> resuList = new ArrayList<>();
        for (Windturbine wt : wtls) {
            if (wt.getWindpowerstationid().endsWith("GDC")){
                continue;
            }
            for (String point : points) {
                Windturbinetestingpointai2 windturbinetestingpointai2 = wtpointMap.get(wt.getId()).get(point);
                try {
                    List<PointData> pointDatas = edosUtil.getHistoryDatasRaw(windturbinetestingpointai2.getId(), begin.getTime(), end.getTime());
                    pointDatas.stream().forEach(pointData -> {
                        OpeVo vo = new OpeVo();
                        vo.setWtid(wt.getId());
                        vo.setTime(new Date(pointData.getPointTime()));
                        vo.setValue(pointData.getPointValueInDouble());
                        resuList.add(vo);
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
        Map<String,List<OpeVo>> map = new HashMap<>();
        for (Dutyschedule duty : dutyList) {
            List<OpeVo> subList = new ArrayList<>();
            for (OpeVo vo : resuList) {
                if (isTimeRange(duty,vo.getTime())) {
                    subList.add(vo);
                }
            }
            map.put(duty.getName(),subList);
        }



        return map;
    }


    private boolean isTimeRange(Dutyschedule duty,Date time) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");
        Date now = df.parse(df.format(time));
        String[] begins=duty.getBegin().split(",");
        String[] ends=duty.getEnd().split(",");
        for (int i=0 ; i<begins.length;i++) {
            Date begin = df.parse(begins[i]);
            Date end = df.parse(ends[i]);
            Calendar nowTime = Calendar.getInstance();
            nowTime.setTime(now);
            Calendar beginTime = Calendar.getInstance();
            beginTime.setTime(begin);
            Calendar endTime = Calendar.getInstance();
            endTime.setTime(end);
            if (nowTime.before(endTime) && nowTime.after(beginTime)) {
                return true;
            }
        }
        return false;

    }


    public void opeMapTask() throws ParseException{
        Date yesterdayStart = DateUtils.getYesterdayStart();
        Date yesterdayEnd = DateUtils.getYesterdayEnd();
        String yeseterdayStr = DateUtils.getYesterdayStr("yyyy-MM-dd");
        Map<String, Object> params1 = new HashMap<>();
        params1.put("createdate", DateUtils.parseDate(yeseterdayStr));
        List<Dutyschedule> dutyList = dutyscheduleService.listByMap(params1);
        Map<String, Map<String, Windturbinetestingpointai2>> wtpointMap = CacheContext.wtpointMap;
        String[] points = OpeContant.opePoints.split(",");
        List<Windturbine> wtls = windturbineService.list();
        List<OpeVo> resuList = new ArrayList<>();
        for (Windturbine wt : wtls) {
            if (wt.getWindpowerstationid().endsWith("GDC")){
                continue;
            }
            for (String point : points) {
                Windturbinetestingpointai2 windturbinetestingpointai2 = wtpointMap.get(wt.getId()).get(point);
                try {
                    List<PointData> pointDatas = edosUtil.getHistoryDatasRaw(windturbinetestingpointai2.getId(), yesterdayStart.getTime()/1000, yesterdayEnd.getTime()/1000);
                    pointDatas.stream().forEach(pointData -> {
                        OpeVo vo = new OpeVo();
                        vo.setWtid(wt.getId());
                        vo.setTime(DateUtils.parseLongToDate(pointData.getPointTime()*1000));
                        vo.setValue(pointData.getPointValueInDouble());
                        resuList.add(vo);
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

        Map<String,List<OpeVo>> map = new HashMap<>();
        for (Dutyschedule duty : dutyList) {
            List<OpeVo> subList = new ArrayList<>();
            for (OpeVo vo : resuList) {
                if (isTimeRange(duty,vo.getTime())) {
                    Operationrecord operationrecord = new Operationrecord();
                    operationrecord.setDutyname(duty.getName());
                    operationrecord.setWtid(vo.getWtid());
                    operationrecord.setTime(vo.getTime());
                    operationrecord.setValue(vo.getValue());
                    operationrecordService.save(operationrecord);
                }
            }
        }
    }


    public List<Operation> findOperecords(String beginDate, String endDate) {
        List<Operation> resultList = new ArrayList<>();
        Date begin = DateUtils.parseDate(beginDate);
        Date end = DateUtils.getEndOfDay(DateUtils.parseDate(endDate));
        List<Operationrecord> opeList = operationrecordService.listByBeginAndEnd(begin, end);
        QueryWrapper<Dutyschedule> wrapper = new QueryWrapper();
        wrapper.select("max(id) id,name,max(begin) begin,max(end) end,max(createdate) createdate");
        wrapper.le("createdate",end).ge("createdate",begin).groupBy("name");
        List<Dutyschedule> dutyList= dutyscheduleService.list(wrapper);
        for (Dutyschedule duty : dutyList) {
            Operation ope = new Operation();
            ope.setNameOfDuty(duty.getName());
            List<Operationrecord> opeVos= opeList.stream().filter(v -> v.getDutyname().equals(duty.getName())).collect(Collectors.toList());
            ope.setStartCount(opeVos.stream().filter(vo -> vo.getValue()==1.0).collect(Collectors.toList()).size());
            ope.setStopCount(opeVos.stream().filter(vo -> vo.getValue()==2.0).collect(Collectors.toList()).size());
            ope.setResetCount(opeVos.stream().filter(vo -> vo.getValue()==3.0).collect(Collectors.toList()).size());
            ope.setMaintainCount(opeVos.stream().filter(vo -> vo.getValue()==4.0).collect(Collectors.toList()).size());
            ope.setUnmaintainCount(opeVos.stream().filter(vo -> vo.getValue()==5.0).collect(Collectors.toList()).size());
            ope.setGpmaintainCount(opeVos.stream().filter(vo -> vo.getValue()==6.0).collect(Collectors.toList()).size());
            ope.setGpfaultCount(opeVos.stream().filter(vo -> vo.getValue()==7.0).collect(Collectors.toList()).size());
            ope.setGponsiteinvolvementMaintainCount(opeVos.stream().filter(vo -> vo.getValue()==8.0).collect(Collectors.toList()).size());
            ope.setGponsiteinvolvementFaultCount(opeVos.stream().filter(vo -> vo.getValue()==9.0).collect(Collectors.toList()).size());
            ope.setGpoffsiteaffectedgridCount(opeVos.stream().filter(vo -> vo.getValue()==100).collect(Collectors.toList()).size());
            ope.setGpweatherOutsideCount(opeVos.stream().filter(vo -> vo.getValue()==11.0).collect(Collectors.toList()).size());
            ope.setUngpCount(opeVos.stream().filter(vo -> vo.getValue()==12.0).collect(Collectors.toList()).size());
            resultList.add(ope);
        }
        return resultList;
    }


    public List<Operationrecord> drillOperecords(String beginDate, String endDate, String dutyname, String direct) {
        Date begin = DateUtils.parseDate(beginDate);
        Date end = DateUtils.getEndOfDay(DateUtils.parseDate(endDate));
        List<Operationrecord> opeList = operationrecordService.listByBeginAndEnd(begin,end);
        List<Operationrecord> resuList = opeList.stream().filter(ope -> ope.getDutyname().equals(dutyname) && ope.getValue() == Double.parseDouble(direct)).collect(Collectors.toList());
        return resuList;
    }

}
