package cn.cecep.talroad.service.impl.analysis;

import cn.cecep.talroad.common.core.utils.DateUtils;
import cn.cecep.talroad.common.core.utils.StringUtils;
import cn.cecep.talroad.domain.BasDevice;
import cn.cecep.talroad.domain.analysis.SRaRealTimeAnalysisRun;
import cn.cecep.talroad.mapper.BasDeviceMapper;
import cn.cecep.talroad.mapper.analysis.SRaRealTimeAnalysisRunMapper;
import cn.cecep.talroad.service.analysis.ISRaRealTimeAnalysisRunService;
import cn.cecep.talroad.vo.EChartsVO;
import cn.cecep.talroad.vo.query.analysis.SRaRealTimeAnalysisRunQuery;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 企业装备运行情况实时分析Service业务层处理
 *
 * @author szhpt
 * @date 2023-03-24*/
@Service
public class SRaRealTimeAnalysisRunServiceImpl extends ServiceImpl<SRaRealTimeAnalysisRunMapper, SRaRealTimeAnalysisRun> implements ISRaRealTimeAnalysisRunService
{
    @Autowired
    private SRaRealTimeAnalysisRunMapper sRaRealTimeAnalysisRunMapper;

    @Autowired
    private BasDeviceMapper basDeviceMapper;
    /**
     * 查询企业装备运行情况实时分析列表
     *
     * @param sRaRealTimeAnalysisRun 企业装备运行情况实时分析
     * @return 企业装备运行情况实时分析
     */
    @Override
    public List<SRaRealTimeAnalysisRun> selectSRaRealTimeAnalysisRunList(SRaRealTimeAnalysisRunQuery sRaRealTimeAnalysisRun)
    {

        return sRaRealTimeAnalysisRunMapper.selectSRaRealTimeAnalysisRunList(sRaRealTimeAnalysisRun);
    }


    @Override
    public List<Map<String, Object>> pullStatusOptions() {
        List<Map<String, Object>> options = Lists.newArrayList();
        for (SRaRealTimeAnalysisRun.OperationStatus option : SRaRealTimeAnalysisRun.OperationStatus.values()) {
            options.add(new HashMap<String, Object>() {{
                put("label", option.getLabel());
                put("value", option.getValue());
            }});
        }
        return options;
    }

    @Override
    public List<Map<String, Object>> pullDeviceNameOptions(String factoryName) {
        return sRaRealTimeAnalysisRunMapper.pullDeviceNameOptions(factoryName);
    }

    @Override
    public List<SRaRealTimeAnalysisRun> selectAnalysisRunByParams(
        SRaRealTimeAnalysisRun oldBasDevice) {
        return sRaRealTimeAnalysisRunMapper.selectAnalysisRunByParams(oldBasDevice);
    }

    @Override
    public EChartsVO resultCurve(String deviceId, String monitoringStartTime, String monitoringEndTime) {
        QueryWrapper<SRaRealTimeAnalysisRun> wrapper=new QueryWrapper<SRaRealTimeAnalysisRun>();
        wrapper.eq(StringUtils.isNotEmpty(deviceId), "device_id", deviceId);
        wrapper.ge("update_time", DateUtil.parse(monitoringStartTime,"yyyy-MM-dd HH:mm:ss"));
        wrapper.le("update_time", DateUtil.parse(monitoringEndTime,"yyyy-MM-dd HH:mm:ss"));
        wrapper.orderByAsc("update_time");
        List<SRaRealTimeAnalysisRun> sRaRealTimeAnalysisRuns = sRaRealTimeAnalysisRunMapper.selectList(wrapper);

        Map<String, String> timeStatusMap = sRaRealTimeAnalysisRuns.stream().collect(Collectors.toMap(o ->  DateUtil.format(o.getUpdateTime(),DatePattern.NORM_DATETIME_MINUTE_FORMATTER), o -> o.getOperationStatus(), (o1, o2) -> o1));
        // x轴数据
        List<String> xdata = DateUtils.getRangeTimes("M", monitoringStartTime, monitoringEndTime);

        EChartsVO.SeriesObj ser1 = new EChartsVO.SeriesObj();
        ser1.setName("运行");
        ser1.setProp("1");
        ser1.setValues(new ArrayList<>());

        EChartsVO.SeriesObj ser2 = new EChartsVO.SeriesObj();
        ser2.setName("停运");
        ser2.setProp("2");
        ser2.setValues(new ArrayList<>());

        EChartsVO.SeriesObj ser3 = new EChartsVO.SeriesObj();
        ser3.setName("启停");
        ser3.setProp("3");
        ser3.setValues(new ArrayList<>());

        EChartsVO.SeriesObj ser4 = new EChartsVO.SeriesObj();
        ser4.setName("停启");
        ser4.setProp("4");
        ser4.setValues(new ArrayList<>());

        EChartsVO.SeriesObj ser5 = new EChartsVO.SeriesObj();
        ser5.setName("数据缺失");
        ser5.setProp("5");
        ser5.setValues(new ArrayList<>());

        EChartsVO chartsVO = new EChartsVO();
        chartsVO.setXData(xdata);
        chartsVO.setSeries(Arrays.asList(ser1, ser2, ser3, ser4,ser5));

        /*
            填充系列值
         */

        // 当前时间设备状态
        String status = null;

        // 遍历x轴，保证系列值与x轴刻度一一对应
        for (String time : xdata) {
            String s = timeStatusMap.get(time);

            // 若不为空，更新状态，否则状态保持原值
            if (s != null) {
                status = s;
            }

            for (EChartsVO.SeriesObj ser : chartsVO.getSeries()) {
                // 若系列的prop属性与状态码相等，则设置系列值为状态码，否则填充null
                if (ser.getProp().equals(status)) {
                    ser.getValues().add(status);
                } else {
                    ser.getValues().add(null);
                }
            }
        }
        return chartsVO;
    }

    @Override
    public List<EChartsVO> analysisCurve(String deviceId, String monitoringStartTime, String monitoringEndTime, String judgementBasis) {
        List<EChartsVO> eChartsVOS=new ArrayList<>();
            List<SRaRealTimeAnalysisRun> analysisCurve= sRaRealTimeAnalysisRunMapper.analysisCurve(deviceId,DateUtil.parse(monitoringStartTime,"yyyy-MM-dd HH:mm:ss"),DateUtil.parse(monitoringEndTime,"yyyy-MM-dd HH:mm:ss"));

            // x轴数据
            List<String> xdata = DateUtils.getRangeTimes("QH", monitoringStartTime, monitoringEndTime);

            Map<String, List<SRaRealTimeAnalysisRun>> pollutionAir = analysisCurve.stream().collect(Collectors.groupingBy( SRaRealTimeAnalysisRun::getDeviceId));
            pollutionAir.forEach((key,value)->{
                EChartsVO eChartsVO=new EChartsVO();
                List<EChartsVO.SeriesObj> chartsVO= new ArrayList<>();
                EChartsVO.SeriesObj ser = new EChartsVO.SeriesObj();
                ser.setName("总有功功率");
                ser.setProp("activePower");
                ser.setUnit("(千瓦)");
                ser.setValues(new ArrayList<>());
                chartsVO.add(ser);
                EChartsVO.SeriesObj ser1 = new EChartsVO.SeriesObj();
                ser1.setName("总有功电量示值");
                ser1.setProp("activePowerQuantity");
                ser1.setUnit("(千瓦)");
                ser1.setValues(new ArrayList<>());
                chartsVO.add(ser1);
                /*
                    填充系列值
                 */
                Map<String, SRaRealTimeAnalysisRun> timeStatusMap = value.stream().collect(Collectors.toMap(o ->  DateUtil.format(o.getUpdateTime(),DatePattern.NORM_DATETIME_MINUTE_FORMATTER), o -> o, (o1, o2) -> o1));
                xdata.forEach(time->{
                    if(timeStatusMap.containsKey(time)){
                        SRaRealTimeAnalysisRun sRaRealTimeAnalysisRun = timeStatusMap.get(time);
                        chartsVO.get(0).getValues().add(sRaRealTimeAnalysisRun.getActivePowerQuantityTmp());
                        chartsVO.get(1).getValues().add(sRaRealTimeAnalysisRun.getActivePowerQuantity());
                    }else {
                        chartsVO.get(0).getValues().add(null);
                        chartsVO.get(1).getValues().add(null);
                    }
                    timeStatusMap.get(time);
                });
                eChartsVO.setXData(xdata);
                eChartsVO.setSeries(chartsVO);
                if(CollectionUtil.isNotEmpty(value)){
                    eChartsVO.setName(value.get(0).getDeviceName());
                }
                eChartsVOS.add(eChartsVO);
            });
            if(CollectionUtil.isEmpty(pollutionAir)){
                EChartsVO eChartsVO=new EChartsVO();
                List<EChartsVO.SeriesObj> chartsVO= new ArrayList<>();
                EChartsVO.SeriesObj ser = new EChartsVO.SeriesObj();
                ser.setName("总有功功率");
                ser.setProp("activePower");
                ser.setUnit("(千瓦)");
                ser.setValues(new ArrayList<>());
                chartsVO.add(ser);
                EChartsVO.SeriesObj ser1 = new EChartsVO.SeriesObj();
                ser1.setName("总有功电量示值");
                ser1.setProp("activePowerQuantity");
                ser1.setUnit("(千瓦)");
                ser1.setValues(new ArrayList<>());
                chartsVO.add(ser1);
                eChartsVO.setXData(xdata);
                eChartsVO.setSeries(chartsVO);
                eChartsVOS.add(eChartsVO);
            }
        return eChartsVOS;
    }

    @Override
    public String analysisCurveEndTime(String deviceId, String monitoringStartTime, String monitoringEndTime) {
        QueryWrapper<SRaRealTimeAnalysisRun> wrapper=new QueryWrapper<SRaRealTimeAnalysisRun>();
        wrapper.eq(StringUtils.isNotEmpty(deviceId), "device_id", deviceId);
        wrapper.ge("update_time", DateUtil.parse(monitoringStartTime,"yyyy-MM-dd HH:mm:ss"));
        wrapper.le("update_time", DateUtil.parse(monitoringEndTime,"yyyy-MM-dd HH:mm:ss"));
        wrapper.orderByAsc("update_time");
        String sRaRealTimeAnalysisRuns = sRaRealTimeAnalysisRunMapper.selectListMaxTime(deviceId, DateUtil.parse(monitoringStartTime,"yyyy-MM-dd HH:mm:ss"), DateUtil.parse(monitoringEndTime,"yyyy-MM-dd HH:mm:ss"));
        return sRaRealTimeAnalysisRuns;
    }
}
