package com.njcn.prepare.harmonic.service.mysql.Impl.device;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.jeffreyning.mybatisplus.service.MppServiceImpl;
import com.njcn.device.biz.commApi.CommTerminalGeneralClient;
import com.njcn.device.biz.pojo.dto.LineDevGetDTO;
import com.njcn.prepare.harmonic.mapper.mysql.device.RStatDevSignalDPOMapper;
import com.njcn.prepare.harmonic.mapper.mysql.line.RMpMonitorEvaluateDMapper;
import com.njcn.prepare.harmonic.pojo.bo.CalculatedParam;
import com.njcn.harmonic.pojo.po.algorithm.line.RMpMonitorEvaluateD;
import com.njcn.prepare.harmonic.pojo.po.RStatDevSignalDPO;
import com.njcn.prepare.harmonic.service.mysql.device.RStatDevSignalDPOService;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.pojo.po.DictData;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Description:
 * Date: 2023/5/4  14:25【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class RStatDevSignalDPOServiceImpl extends MppServiceImpl<RStatDevSignalDPOMapper, RStatDevSignalDPO> implements RStatDevSignalDPOService {

    private final RMpMonitorEvaluateDMapper revaluateDMapper;
    private final
    DicDataFeignClient dicDataFeignClient;

    private final CommTerminalGeneralClient commTerminalGeneralClient;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void devSignalD(CalculatedParam calculatedParam) {
        log.info(LocalDateTime.now()+"===>终端通信管理日统计算法开始");
        List<LineDevGetDTO> lineDevGetList = new ArrayList<>();
        List<RStatDevSignalDPO> rStatDevSignalList = new ArrayList<>();
        List<RMpMonitorEvaluateD> evaluateList = new ArrayList<>();
        DictData data = dicDataFeignClient.getDicDataByCode(DicDataEnum.RUNNING.getCode()).getData();
        List<String> lineIds = calculatedParam.getIdList();
        //以尺寸100分片,查询数据
        List<List<String>> pendingIds =  ListUtils.partition(lineIds,5);
        for (List<String> pendingId : pendingIds) {
            //获取监测点评价详情
            LambdaQueryWrapper<RMpMonitorEvaluateD> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(RMpMonitorEvaluateD::getMeasurementPointId,pendingId)
                                .eq(RMpMonitorEvaluateD::getDataDate,calculatedParam.getDataDate());
            List<RMpMonitorEvaluateD> ls = revaluateDMapper.selectList(lambdaQueryWrapper);
            evaluateList.addAll(ls);
            //监测点详情
            lineDevGetList.addAll(commTerminalGeneralClient.getMonitorDetailList(pendingId).getData());
        }
        Map<String,List<RMpMonitorEvaluateD>> map1 = evaluateList.stream().collect(Collectors.groupingBy(RMpMonitorEvaluateD::getDeviceId));
        Map<String,List<LineDevGetDTO>> map2 = lineDevGetList.stream().collect(Collectors.groupingBy(LineDevGetDTO::getDevId));

        map2.forEach((k,v)->{
            RStatDevSignalDPO rStatDevSignal = new RStatDevSignalDPO();
            rStatDevSignal.setDeviceId(k);
            rStatDevSignal.setDeviceStatus(data.getId());
            if (!Objects.isNull(v.get(0).getUpdateTime())){
                rStatDevSignal.setUpdateTime(v.get(0).getUpdateTime().format(DatePattern.NORM_DATETIME_FORMATTER));
            }
            rStatDevSignal.setDataDate(LocalDateTimeUtil.parseDate(calculatedParam.getDataDate(),DatePattern.NORM_DATE_FORMATTER));
            if (CollectionUtil.isNotEmpty(map1.get(k))){
                int count = map1.get(k).stream().mapToInt(RMpMonitorEvaluateD::getEffectiveMinuteCount).sum();
                if (count > 0){
                    rStatDevSignal.setRunStatus("1");
                } else {
                    rStatDevSignal.setRunStatus("0");
                }
            } else {
                rStatDevSignal.setRunStatus("0");
            }
            rStatDevSignal.setUpdateTime(calculatedParam.getDataDate());
            rStatDevSignalList.add(rStatDevSignal);
        });
        if (CollectionUtil.isNotEmpty(rStatDevSignalList)){
            this.saveOrUpdateBatchByMultiId(rStatDevSignalList, 100);
        }
    }

}
