package com.njcn.csdevice.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.github.jeffreyning.mybatisplus.service.MppServiceImpl;
import com.njcn.csdevice.api.CsLineFeignClient;
import com.njcn.csdevice.mapper.RStatIntegrityDMapper;
import com.njcn.csdevice.pojo.po.CsEquipmentDeliveryPO;
import com.njcn.csdevice.pojo.po.CsLinePO;
import com.njcn.csdevice.pojo.po.RStatIntegrityD;
import com.njcn.csdevice.service.CsEquipmentDeliveryService;
import com.njcn.csdevice.service.IRStatIntegrityDService;
import com.njcn.csdevice.util.TimeUtil;
import com.njcn.csharmonic.pojo.param.StatisticsDataParam;
import com.njcn.influx.pojo.dto.StatisticalDataDTO;
import com.njcn.influx.service.CommonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 数据完整性日表 服务实现类
 * </p>
 *
 * @author xy
 * @since 2025-06-23
 */
@DS("sjzx")
@Slf4j
@Service
@RequiredArgsConstructor
public class RStatIntegrityDServiceImpl extends MppServiceImpl<RStatIntegrityDMapper, RStatIntegrityD> implements IRStatIntegrityDService {

    private final CsLineFeignClient csLineFeignClient;
    private final CommonService commonService;
    private final CsEquipmentDeliveryService csEquipmentDeliveryService;

    @Override
    public void addData(StatisticsDataParam param) {
        List<RStatIntegrityD> result = new ArrayList<>();
        List<CsEquipmentDeliveryPO> devList;
        //判断是否指定设备补招
        if (CollectionUtil.isNotEmpty(param.getIdList())) {
            devList = csEquipmentDeliveryService.getListByIds(param.getIdList());
        } else {
            //获取库中正常的所有装置
            devList = csEquipmentDeliveryService.getAll();
        }
        if (CollectionUtil.isNotEmpty(devList)) {
            Map<String, CsEquipmentDeliveryPO> devMap = devList.stream().collect(Collectors.toMap(CsEquipmentDeliveryPO::getId, Function.identity()));
            //获取所有监测点
            List<String> devIdList = devList.stream().map(CsEquipmentDeliveryPO::getId).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(devIdList)) {
                //获取需要计算的时间
                List<String> dateRange = TimeUtil.getDateRangeAsString(param.getStartTime(), param.getEndTime());
                //获取监测点信息
                List<CsLinePO> csLinePOList = csLineFeignClient.getLinesByDevList(devIdList).getData();
                csLinePOList.forEach(item->{
                    //没有统计间隔就计算下一次监测点
                    if (Objects.isNull(item.getLineInterval()) || item.getLineInterval() == 0) {
                        item.setLineInterval(1);
                    }
                    //应收数据
                    int dueCount = 1440 / item.getLineInterval();
                    Integer process = devMap.get(item.getDeviceId()).getProcess();
                    for (String time : dateRange) {
                        StatisticalDataDTO statisticalDataDTO;
                        RStatIntegrityD data = new RStatIntegrityD();
                        //治理监测点
                        if (item.getClDid() == 0) {
                            statisticalDataDTO = commonService.getDataCounts(item.getLineId(),"apf_data","Apf_Freq","value","T","AVG",item.getClDid().toString(),process.toString(),time+" 00:00:00",time+" 23:59:59");
                        }
                        else {
                            //云前置监测点 && 治理、无线监测点
                            statisticalDataDTO = commonService.getDataCounts(item.getLineId(),"data_v","freq","value","T","AVG",item.getClDid().toString(),process.toString(),time+" 00:00:00",time+" 23:59:59");
                        }
                        data.setTimeId(LocalDate.parse(time, DatePattern.NORM_DATE_FORMATTER));
                        data.setLineIndex(item.getLineId());
                        data.setDueTime(dueCount);
                        data.setRealTime(statisticalDataDTO == null || statisticalDataDTO.getValue() == null
                                ? 0 : (int)Math.round(statisticalDataDTO.getValue()));
                        result.add(data);
                    }
                });
            }
        }
        if (CollectionUtil.isNotEmpty(result)) {
            this.saveOrUpdateBatchByMultiId(result);
        }
    }

    @Override
    public List<RStatIntegrityD> getData(List<String> list, String startTime, String endTime) {
        return this.lambdaQuery()
                .in(RStatIntegrityD::getLineIndex,list)
                .between(RStatIntegrityD::getTimeId,startTime,endTime)
                .list();
    }

}
