package com.njcn.device.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.device.mapper.LogManageMapper;
import com.njcn.device.pojo.constant.DeviceValidMessage;
import com.njcn.device.pojo.param.DeviceLogParam;
import com.njcn.device.pojo.param.EventLogParam;
import com.njcn.device.pojo.po.EventPushLogs;
import com.njcn.device.pojo.vo.DeviceLogVO;
import com.njcn.device.pojo.vo.EventLogVO;
import com.njcn.device.service.LogManageService;
import com.njcn.event.api.EventDetailFeignClient;
import com.njcn.event.pojo.po.EventDetail;
import com.njcn.influxdb.utils.InfluxDbUtils;
import lombok.AllArgsConstructor;
import org.influxdb.dto.QueryResult;
import org.influxdb.impl.InfluxDBResultMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
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 LogManageMapper logManageMapper;

    private final EventDetailFeignClient eventDetailFeignClient;

    private final InfluxDbUtils influxDbUtils;

    @Override
    public List<DeviceLogVO> getDeviceLogData(DeviceLogParam deviceLogParam) {
        if (deviceLogParam.getType().isEmpty()) {
            deviceLogParam.setType(null);
        }
        deviceLogParam.setSearchBeginTime(deviceLogParam.getSearchBeginTime()+" 00:00:00");
        deviceLogParam.setSearchEndTime(deviceLogParam.getSearchEndTime()+" 23:59:59");
        List<DeviceLogVO> logData = logManageMapper.getDeviceLogData(deviceLogParam);
        return logData;
    }


    @Override
    public Page<EventLogVO> getEventLogData(EventLogParam eventLogParam) {
        Page<EventLogVO> page = new Page<>();
        page.setSize(eventLogParam.getPageSize());
        page.setCurrent(eventLogParam.getPageNum());
        List<EventLogVO> list = new ArrayList<>();
        /** 查询event_push_logs表数据*/
        List<EventPushLogs> eventPushLogs = getEventPushLogs(eventLogParam.getSearchBeginTime(), eventLogParam.getSearchEndTime(), eventLogParam.getResult());
        //待分页数据总量
        page.setTotal(eventPushLogs.size());
        //分页总页数
        int pages = (int)Math.ceil(eventPushLogs.size()*1.0/eventLogParam.getPageSize());
        page.setPages(pages);
        if (!CollectionUtils.isEmpty(eventPushLogs)) {
            List<String> lineIndexes = eventPushLogs.stream().map(EventPushLogs::getLineId).collect(Collectors.toList());
            lineIndexes = lineIndexes.stream().distinct().collect(Collectors.toList());
            /** 分页查询pqs_eventdetail表数据*/
            List<EventDetail> eventDetailData = eventDetailFeignClient.getEventDetailLimit(lineIndexes, eventLogParam.getSearchBeginTime(), eventLogParam.getSearchEndTime(), eventLogParam.getPageSize(), eventLogParam.getPageNum()).getData();
            if (!CollectionUtils.isEmpty(eventDetailData)) {
                for (EventPushLogs pushLogs: eventPushLogs) {
                    for (EventDetail eventDetail: eventDetailData) {
                        if (pushLogs.getLineId().equals(eventDetail.getLineId()) && pushLogs.getTimeId().equals(eventDetail.getTimeId())) {
                            EventLogVO eventLogVO = new EventLogVO();
                            eventLogVO.setLineId(pushLogs.getLineId());
                            LocalDateTime localDateTime = LocalDateTime.ofInstant(pushLogs.getTimeId(), ZoneId.systemDefault());
                            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
                            String format = dateTimeFormatter.format(localDateTime);
                            eventLogVO.setTime(format);
                            EventLogVO event = logManageMapper.getEventLogData(eventLogVO.getLineId());
                            eventLogVO.setLine(event.getLine());
                            eventLogVO.setSubstation(event.getSubstation());
                            eventLogVO.setPowerCompany(event.getPowerCompany());
                            Double e = eventDetail.getEventValue();
                            BigDecimal bd = new BigDecimal(e);
                            e= bd.setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
                            eventLogVO.setEventValue(String.valueOf(e*100));
                            double i = eventDetail.getPersistTime() / 1000;
                            eventLogVO.setPersistTime(String.valueOf(i));
                            eventLogVO.setCreatTime(pushLogs.getCreateTime());
                            eventLogVO.setCreatTimed(pushLogs.getCreateTime());
                            eventLogVO.setPushFailed(pushLogs.getPushFailed());
                            if (pushLogs.getResult()==0) {
                                eventLogVO.setResult("失败");
                                eventLogVO.setState("未推送");
                            } else {
                                eventLogVO.setResult("成功");
                                eventLogVO.setState("已推送");
                            }
                            eventLogVO.setUpdateTime(pushLogs.getUpdateTime());

                            list.add(eventLogVO);
                            //当前页数据
                            page.setRecords(list);
                        }
                    }
                }
            }

        }
        return page;
    }

    /**
     * influxDB查询暂降事件相关信息
     * @param startTime
     * @param endTime
     * @param result
     */
    private List<EventPushLogs> getEventPushLogs(String startTime, String endTime, Integer result) {
        List<EventPushLogs> logsList;
        //组装sql语句
        StringBuilder string = new StringBuilder();
        string.append(DeviceValidMessage.TIME + " >= '" + startTime + DeviceValidMessage.START_TIME + "' and " + DeviceValidMessage.TIME + " <= '" + endTime + DeviceValidMessage.END_TIME + "'");
        if (result==1 || result==2) {
            string.append(" and result=" + result);
        }
        //sql语句
        String sql = "SELECT * FROM pqs_event_push_logs WHERE " + string;
        System.out.println("sql==========="+sql);
        //结果集
        QueryResult results = influxDbUtils.query(sql);
        //结果集映射到对象中
        InfluxDBResultMapper resultMapper = new InfluxDBResultMapper();
        logsList = resultMapper.toPOJO(results, EventPushLogs.class);

        return logsList;
    }


}
