package com.njcn.harmonic.service.impl;

import com.njcn.device.api.LineFeignClient;
import com.njcn.device.pojo.vo.CommunicateVO;
import com.njcn.harmonic.constant.Param;
import com.njcn.harmonic.pojo.param.PulicTimeParam;
import com.njcn.harmonic.pojo.param.PulicTimeStatisParam;
import com.njcn.harmonic.pojo.vo.CommunicateStatisticsVO;
import com.njcn.harmonic.service.CommunicateService;
import com.njcn.influxdb.utils.InfluxDbUtils;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.influxdb.dto.QueryResult;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author denghuajun
 * @date 2022/2/28
 *
 */
@Service
@AllArgsConstructor
public class CommunicateServiceImpl implements CommunicateService {

    private final LineFeignClient lineFeignClient;

    private final InfluxDbUtils influxDbUtils;

    @Override
    public CommunicateVO getComFlagInfoData(PulicTimeParam pulicTimeParam) {
        //根据监测点id获取终端状态信息
        return lineFeignClient.getComFlagInfoData(pulicTimeParam.getId(), pulicTimeParam.getSearchBeginTime(), pulicTimeParam.getSearchEndTime()).getData();
    }

    @Override
    public CommunicateStatisticsVO getRunInfoData(PulicTimeStatisParam pulicTimeStatisParam) {
        CommunicateStatisticsVO communicateStatisticsVO = new CommunicateStatisticsVO();
        //根据监测点id获取终端id
        String devId = lineFeignClient.getLineIdByDevId(pulicTimeStatisParam.getId()).getData();
        List<Float> floatList = new ArrayList<>();
        List<Float> floats = new ArrayList<>();
        floatList.add(getCondition(pulicTimeStatisParam.getId(), pulicTimeStatisParam.getSearchBeginTime(), pulicTimeStatisParam.getSearchEndTime(),0) * 100);
        floats.add(getCondition(devId, pulicTimeStatisParam.getSearchBeginTime(), pulicTimeStatisParam.getSearchEndTime(),1) * 100);
        if (StringUtils.isNotBlank(pulicTimeStatisParam.getPeriodBeginTime())&& StringUtils.isNotBlank(pulicTimeStatisParam.getPeriodEndTime())){
            floatList.add(getCondition(pulicTimeStatisParam.getId(), pulicTimeStatisParam.getPeriodBeginTime(), pulicTimeStatisParam.getPeriodEndTime(),0)*100);
            floats.add(getCondition(devId, pulicTimeStatisParam.getPeriodBeginTime(), pulicTimeStatisParam.getPeriodEndTime(),1)*100);
        }
        communicateStatisticsVO.setOnlineRateData(floats);
        communicateStatisticsVO.setIntegrityData(floatList);
        return communicateStatisticsVO;
    }

    /**
     * influxDB相关操作
     * 查询监测点的数据完整性
     */
    private Float getCondition(String lineList, String startTime, String endTime,Integer state) {
        final Float[] resultList = {0.0f};
        //组装sql语句
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(Param.TIME + " >= '").append(startTime).append(Param.START_TIME).append("' and ").append(Param.TIME).append(" <= '").append(endTime).append(Param.END_TIME).append("' and (");
        //sql语句
        String sql = "";
        if (state == 0) {
            stringBuilder.append(Param.LINE_INDEX + "='").append(lineList).append("')");
            sql = "SELECT SUM(" + Param.REAL + ")/SUM(" + Param.DUE + ") AS integrity FROM PQS_INTEGRITY WHERE " + stringBuilder.toString() + " group by " + Param.LINE_INDEX;
        } else {
            stringBuilder.append(Param.DEV_INDEX + "='").append(lineList).append("')");
             sql = "SELECT SUM(" + Param.ONLINEMIN + ")/(SUM(" + Param.OFFLINEMIN + ")+SUM(" + Param.ONLINEMIN + ")) AS onlineRate FROM PQS_ONLINERATE WHERE " + stringBuilder.toString() + " group by " + Param.DEV_INDEX;
        }
        //结果集
        QueryResult result = influxDbUtils.query(sql);
        //处理结果集
        List<QueryResult.Series> list = result.getResults().get(0).getSeries();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(po -> {
                List<List<Object>> valueList = po.getValues();
                if (!CollectionUtils.isEmpty(valueList)) {
                    for (List<Object> value : valueList) {
                        //数据完整性 保留四位小数
                        resultList[0] = value.get(1) == null ? null : BigDecimal.valueOf(Float.parseFloat(value.get(1).toString())).setScale(4, BigDecimal.ROUND_HALF_UP).floatValue();
                    }
                }
            });
        }

        return resultList[0];
    }
}
