package com.ruoyi.system.service.impl;


import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.dto.SiteRealTimeDTO;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.ReportDataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.Date;
import java.util.List;


/**
 * classname: 站点信息
 * description  服务实现类
 */
@Service
@Slf4j
public class ReportDataServiceImpl implements ReportDataService {

    @Resource
    private CarPositionMapper carPositionMapper;


    @Resource
    private HeartBeatMapper heartBeatMapper;


    @Resource
    private SiteInfoMapper siteInfoMapper;


    @Resource
    private TaskNoticeMapper taskNoticeMapper;

    @Resource
    private WaterLevelMapper waterLevelMapper;

    @Resource
    private MeasureUploadMapper measureUploadMapper;

    @Resource
    private TaskResultMapper taskResultMapper;

    @Resource
    private BerthingTimeConfigMapper berthingTimeConfigMapper;

    @Resource
    private BerthingPointConfigMapper berthingPointConfigMapper;

    @Override
    public List<CarPosition> carLocation(Long siteId, String startTime, String endTime){
        if (Strings.isNotBlank(startTime) && Strings.isNotBlank(endTime)){
            return carPositionMapper.queryBysiteIdTime(siteId,startTime,endTime);
        }
        return Collections.singletonList(carPositionMapper.queryBysiteId(siteId));
    }

    @Override
    public List<HeartBeat> carInfo(Long siteId,String startTime, String endTime){
        if (Strings.isNotBlank(startTime) && Strings.isNotBlank(endTime)){
            return heartBeatMapper.queryBysiteIdTime(siteId,startTime,endTime);
        }
        return Collections.singletonList(heartBeatMapper.queryBysiteId(siteId));
    }


    @Override
    public SiteRealTimeDTO siteRealTime(Long siteId){

        SiteRealTimeDTO siteRealTimeDTO = new SiteRealTimeDTO();
        //查询站点名称
        SiteInfo siteInfo = siteInfoMapper.queryById(siteId);
        if (siteInfo == null){
            throw new BaseException("站点不存在");
        }
        siteRealTimeDTO.setSiteName(siteInfo.getSiteName());
        siteRealTimeDTO.setSiteId(siteId);
        //查询状态
        TaskResult taskResult = taskResultMapper.queryBySiteIdOne(siteId);
        if (taskResult == null){
            siteRealTimeDTO.setSiteStatus(null);
            siteRealTimeDTO.setNextTime(null);
        } else {
            siteRealTimeDTO.setSiteStatus(taskResult.getStatus()==0?"1":"0");
            //计算下次测量时间 取当前水位匹配测流时间策略
            WaterLevel waterLevel = waterLevelMapper.queryBySiteId(siteId);
            if (waterLevel == null){
                siteRealTimeDTO.setNextTime(null);
            }else {
                //查询测流时间策略
                BerthingTimeConfig berthingTimeConfig = berthingTimeConfigMapper.queryByWlevel(waterLevel.getWaterlevel(),siteId);
                if (berthingTimeConfig == null){
                    siteRealTimeDTO.setNextTime(null);
                }else {
                    // 当前时间
                    LocalTime currentTime = LocalTime.now();
                    //计算下次测量时间
                    JSONArray timeSlots = JSONUtil.parseArray(berthingTimeConfig.getTimes());
                    List<LocalTime> parsedTimeSlots = timeSlots.stream()
                            .map(ReportDataServiceImpl::parseTime)
                            .toList();

                    // 查找当前时间之后的第一个时间段
                    LocalTime nextTimeSlot = parsedTimeSlots.stream()
                            .filter(time -> time.isAfter(currentTime))
                            .findFirst()
                            .orElse(null);
                    if (nextTimeSlot != null) {
                        siteRealTimeDTO.setNextTime(nextTimeSlot.format(DateTimeFormatter.ofPattern("HH:mm")));
                    } else {
                        siteRealTimeDTO.setNextTime(timeSlots.get(0).toString());
                    }
                }

            }

        }
        return siteRealTimeDTO;
    }


    @Override
    public Page<TaskNotice> taskNotice(Long siteId,String taskId,Long page,Long size){
        if (siteId == null){
            throw new BaseException("站点不存在");
        }
        if (page == null || size == null){
            page = 1L;
            size = 10L;
        }
        return taskNoticeMapper.queryAllByLimit(siteId,taskId,new Page(page,size));
    }


    @Override
    public WaterLevel getWaterLevel(Long siteId){
        return waterLevelMapper.queryBySiteId(siteId);
    }


    @Override
    public List<MeasureUpload> getMeasureLine (Long siteId, String taskId){
        //先查询最后一次开测时间
        if (Strings.isBlank(taskId)){
            TaskResult taskResult = taskResultMapper.queryBySiteIdOne(siteId);
            if (taskResult == null){
                return null;
            }
            //再按时间查询垂线信息
            Date createTime = taskResult.getCreateTime();
            return measureUploadMapper.queryBySiteIdTime(siteId,createTime,null);
        } else {
            return measureUploadMapper.queryBySiteIdTime(siteId,null,taskId);
        }


    }

    @Override
    public BerthingPointConfig getPointConfig (Long siteId){
        //先查询最后一次开测时间
        TaskResult taskResult = taskResultMapper.queryBySiteIdOne(siteId);
        if (taskResult == null){
            return null;
        } else {
            Long planid = taskResult.getPlanid();
            BerthingPointConfig berthingPointConfig = berthingPointConfigMapper.queryByPlanid(siteId, planid);
            if (berthingPointConfig == null){
                return null;
            }
            return berthingPointConfig;
        }
    }

    @Override
    public BerthingPointConfig getPointConfig (Long siteId, Long planid){
        return berthingPointConfigMapper.queryByPlanid(siteId, planid);
    }

    @Override
    public TaskResult getLatestTask(Long siteId) {
        return taskResultMapper.queryBySiteIdOne(siteId);
    }

    private static LocalTime parseTime(Object timeStr) {
        return LocalTime.parse(timeStr.toString(), DateTimeFormatter.ofPattern("HH:mm"));
    }





}
