package com.njcn.device.pq.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.db.constant.DbConstant;
import com.njcn.device.line.mapper.LineMapper;
import com.njcn.device.pq.mapper.EventPushLogsMapper;
import com.njcn.device.pq.pojo.param.EventLogParam;
import com.njcn.device.pq.pojo.po.EventPushLogs;
import com.njcn.device.pq.pojo.vo.AreaLineInfoVO;
import com.njcn.device.pq.pojo.vo.EventLogVO;
import com.njcn.device.pq.service.LogManageService;
import com.njcn.event.api.EventDetailFeignClient;
import com.njcn.event.pojo.po.EventDetail;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @version 1.0.0
 * @author: chenchao
 * @date: 2022/05/26 16:51
 */
@Service
@AllArgsConstructor
public class LogManageServiceImpl implements LogManageService {

    private final EventDetailFeignClient eventDetailFeignClient;

    private final EventPushLogsMapper eventPushLogsMapper;

    private final LineMapper lineMapper;


    @Override
    public Page<EventLogVO> getEventLogData(EventLogParam eventLogParam) {
        //查询全部时间
        List<String> lineByIDs = lineMapper.getLineByIDs(eventLogParam.getSearchValue());
        if (CollUtil.isEmpty(lineByIDs)) {
            return new Page<>();
        }
        Page<EventLogVO> page = new Page<>();
        page.setSize(eventLogParam.getPageSize());
        page.setCurrent(eventLogParam.getPageNum());
        List<EventLogVO> list = new ArrayList<>();
        // influxDB改查MySQL cld_event_push_log
        Page<EventPushLogs> p = new Page<>();
        p.setSize(eventLogParam.getPageSize());
        p.setCurrent(eventLogParam.getPageNum());
        QueryWrapper<EventPushLogs> wrapper = new QueryWrapper<>();
        wrapper.between("start_time", DateUtil.beginOfDay(DateUtil.parse(eventLogParam.getSearchBeginTime())), DateUtil.endOfDay(DateUtil.parse(eventLogParam.getSearchEndTime())));
        wrapper.eq(eventLogParam.getResult() != null, "Result", eventLogParam.getResult());
        wrapper.in("measurement_point_id", lineByIDs);
        if (ObjectUtil.isAllNotEmpty(eventLogParam.getSortBy(), eventLogParam.getOrderBy())) {
            wrapper.orderBy(true, eventLogParam.getOrderBy().equals(DbConstant.ASC), StrUtil.toUnderlineCase(eventLogParam.getSortBy()));
        } else {
            //没有排序参数，默认根据sort字段排序，没有排序字段的，根据updateTime更新时间排序
            wrapper.orderBy(true, false, "start_time");
        }
        Page<EventPushLogs> rawPage = eventPushLogsMapper.selectPage(p, wrapper);
        List<EventPushLogs> rawLogs = rawPage.getRecords();
        if (CollectionUtil.isNotEmpty(rawLogs)) {
            List<String> lineIndexes = rawLogs.stream().map(EventPushLogs::getMeasurementPointId).distinct().collect(Collectors.toList());

            List<EventDetail> rawEventDetailData = eventDetailFeignClient.getEventDetail(lineIndexes, eventLogParam.getSearchBeginTime(), eventLogParam.getSearchEndTime()).getData();
            List<EventDetail> eventDetails = rawEventDetailData.stream().filter(eventDetail -> filterLineIdAndTime(eventDetail, rawLogs)).collect(Collectors.toList());

            Map<String, List<EventDetail>> eventDetailMap = eventDetails.stream().collect(Collectors.groupingBy(EventDetail::getLineId));
            List<String> lineList = eventDetails.stream().map(EventDetail::getLineId).collect(Collectors.toList());
            List<AreaLineInfoVO> lineAreaInfos = lineMapper.getBaseLineAreaInfo(lineList, null, null);
            Map<String, List<AreaLineInfoVO>> areaMap = lineAreaInfos.stream().collect(Collectors.groupingBy(AreaLineInfoVO::getLineId));
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
            for (EventPushLogs rawLog : rawLogs) {
                if (Objects.isNull(areaMap.get(rawLog.getMeasurementPointId()).get(0)) || Objects.isNull(eventDetailMap.get(rawLog.getMeasurementPointId()).get(0))) {
                    continue;
                }
                EventLogVO eventLogVO = new EventLogVO();
                eventLogVO.setLineId(rawLog.getMeasurementPointId());
                eventLogVO.setTime(dateTimeFormatter.format(rawLog.getStartTime()));
                eventLogVO.setLine(areaMap.get(rawLog.getMeasurementPointId()).get(0).getLineName());
                eventLogVO.setSubstation(areaMap.get(rawLog.getMeasurementPointId()).get(0).getSubName());
                eventLogVO.setPowerCompany(areaMap.get(rawLog.getMeasurementPointId()).get(0).getGdName());
                Double e = eventDetailMap.get(rawLog.getMeasurementPointId()).get(0).getFeatureAmplitude();
                BigDecimal bd = new BigDecimal(e);
                e = bd.setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
                eventLogVO.setEventValue(String.valueOf(e * 100));
                double i = eventDetailMap.get(rawLog.getMeasurementPointId()).get(0).getDuration();
                eventLogVO.setPersistTime(String.valueOf(i));
                eventLogVO.setCreatTime(dateTimeFormatter.format(rawLog.getCreateTime()));
                eventLogVO.setCreatTimed(dateTimeFormatter.format(rawLog.getCreateTime()));
                eventLogVO.setPushFailed(rawLog.getPushFailed());
                if (rawLog.getResult() == 0) {
                    eventLogVO.setResult("失败");
                    eventLogVO.setState("未推送");
                } else {
                    eventLogVO.setResult("成功");
                    eventLogVO.setState("已推送");
                }
                eventLogVO.setUpdateTime(dateTimeFormatter.format(rawLog.getUpdateTime()));

                list.add(eventLogVO);
            }
            page.setTotal(p.getTotal());
            page.setCurrent(p.getCurrent());
            //当前页数据
            page.setRecords(list);
        }
        return page;
    }

    private boolean filterLineIdAndTime(EventDetail eventDetail, List<EventPushLogs> eventPushLogs) {
        boolean flag = false;
        String evenDetailTime = eventDetail.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        for (EventPushLogs log : eventPushLogs) {
            String logTime = log.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            if (log.getMeasurementPointId().equals(eventDetail.getLineId()) && log.getEventId().equals(eventDetail.getEventId()) && evenDetailTime.equals(logTime)) {
                flag = true;
            }
        }
        return flag;
    }


}
