package org.dromara.service.impl;

import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.domain.SenEventsMedia;
import org.dromara.domain.bo.SenEventsObjectBo;
import org.dromara.domain.SenEventsObject;
import org.dromara.domain.vo.SenEventsMediaVo;
import org.dromara.mapper.SenEventsMediaMapper;
import org.dromara.system.domain.SysDictData;
import org.dromara.system.mapper.SysDictDataMapper;
import org.springframework.stereotype.Service;
import org.dromara.domain.bo.SenEventsBo;
import org.dromara.domain.vo.SenEventsVo;
import org.dromara.domain.SenEvents;
import org.dromara.mapper.SenEventsMapper;
import org.dromara.service.ISenEventsService;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * 事件信息Service业务层处理
 *
 * @author luogang
 * @date 2024-09-19
 */
@RequiredArgsConstructor
@Service
public class SenEventsServiceImpl implements ISenEventsService {


    private final SenEventsMapper baseMapper;

    private final SysDictDataMapper dictMapper;

    private final SenEventsMediaMapper mediaMapper;

    /**
     * 查询事件信息
     *
     * @param id 主键
     * @return 事件信息
     */
    @Override
    public SenEventsVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询事件信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 事件信息分页列表
     */
    @Override
    public TableDataInfo<SenEventsVo> queryPageList(SenEventsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SenEvents> lqw = buildQueryWrapper(bo);
        Page<SenEventsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的事件信息列表
     *
     * @param bo 查询条件
     * @return 事件信息列表
     */
    @Override
    public List<SenEventsVo> queryList(SenEventsBo bo) {
        LambdaQueryWrapper<SenEvents> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SenEvents> buildQueryWrapper(SenEventsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SenEvents> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getEventCategory()), SenEvents::getEventCategory, bo.getEventCategory());
        lqw.like(StringUtils.isNotBlank(bo.getEventName()), SenEvents::getEventName, bo.getEventName());
        lqw.eq(StringUtils.isNotBlank(bo.getEventType()), SenEvents::getEventType, bo.getEventType());
        lqw.eq(bo.getPointId() != null, SenEvents::getPointId, bo.getPointId());
        lqw.like(StringUtils.isNotBlank(bo.getPointName()), SenEvents::getPointName, bo.getPointName());
        lqw.eq(StringUtils.isNotBlank(bo.getAreaId()), SenEvents::getAreaId, bo.getAreaId());
        lqw.like(StringUtils.isNotBlank(bo.getAreaName()), SenEvents::getAreaName, bo.getAreaName());
        lqw.eq(StringUtils.isNotBlank(bo.getEventObj()), SenEvents::getEventObj, bo.getEventObj());
        lqw.eq(StringUtils.isNotBlank(bo.getDealStatus()), SenEvents::getDealStatus, bo.getDealStatus());
        return lqw;
    }

    /**
     * 新增事件信息
     *
     * @param bo 事件信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SenEventsBo bo) {
        SenEvents add = MapstructUtils.convert(bo, SenEvents.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改事件信息
     *
     * @param bo 事件信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SenEventsBo bo) {
        SenEvents update = MapstructUtils.convert(bo, SenEvents.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SenEvents entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除事件信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public HashMap<String, Object> eventsCount() {
        HashMap<String, Object> result;
        result = baseMapper.selectEventsCount();
        LambdaQueryWrapper<SenEvents> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(SenEvents::getCreateTime);
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(1);
        pageQuery.setPageSize(5);
        result.put("latestData", baseMapper.selectVoPage(pageQuery.build(), lqw).getRecords());
        return result;
    }

    public LambdaQueryWrapper<SenEvents> buildDateWrapper(String dateType) {
        LocalDateTime now = LocalDateTime.now();
        Date startDate = null;
        Date endDate = switch (dateType) {
            case "1" -> {
                startDate = Date.from(now.withHour(0).withMinute(0).withSecond(0).atZone(ZoneId.systemDefault()).toInstant());
                yield Date.from(now.withHour(23).withMinute(59).withSecond(59).atZone(ZoneId.systemDefault()).toInstant());
            }
            case "7" -> {
                startDate = Date.from(now.minusDays(7).withHour(0).withMinute(0).withSecond(0).atZone(ZoneId.systemDefault()).toInstant());
                yield Date.from(now.withHour(23).withMinute(59).withSecond(59).atZone(ZoneId.systemDefault()).toInstant());
            }
            case "30" -> {
                startDate = Date.from(now.minusDays(30).withHour(0).withMinute(0).withSecond(0).atZone(ZoneId.systemDefault()).toInstant());
                yield Date.from(now.withHour(23).withMinute(59).withSecond(59).atZone(ZoneId.systemDefault()).toInstant());
            }
            default -> throw new IllegalArgumentException("Invalid time range: " + dateType);
        };

        LambdaQueryWrapper<SenEvents> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .ge(SenEvents::getCreateTime, startDate)
                .le(SenEvents::getCreateTime, endDate);
        return queryWrapper;
    }

    @Override
    public List<HashMap<String, Object>> importantEventsStat(String dateType) {
        LambdaQueryWrapper<SenEvents> queryWrapper = buildDateWrapper(dateType);
        queryWrapper
                .eq(SenEvents::getEventCategory, 1);
        return baseMapper.importantEventsStat(queryWrapper);
    }

    @Override
    public HashMap<String, Object> motorInLanesTop10(String dateType) {
        LambdaQueryWrapper<SenEvents> queryWrapper = buildDateWrapper(dateType);
        queryWrapper
                .eq(SenEvents::getEventType, 10);
        HashMap<String, Object> result = new HashMap<>();
        result.put("list", baseMapper.motorInLanesTop10(queryWrapper));
        result.putAll(baseMapper.motorInLanesCount(queryWrapper));
        return result;
    }

    /**
     * 事件占比TOP10（%）
     */
    @Override
    public List<Map<String, Object>> eventPercentTop10() {
        return baseMapper.eventPercentTop10();
    }

    /**
     * 近30日事件统计
     */
    @Override
    public List<Map<String, Object>> eventMonthCount() {
        return baseMapper.eventMonthCount();
    }

    /**
     * 每日事件统计
     */
    @Override
    public List<Map<String, Object>> eventDayCount() {
        LambdaQueryWrapper<SysDictData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictData::getDictType, "event_type");
        return baseMapper.eventDayCount();
    }

    /**
     * 监控点位违反统计
     */
    @Override
    public List<HashMap<String, Object>> pointEventsStat(String dateType) {
        LambdaQueryWrapper<SenEvents> queryWrapper = buildDateWrapper(dateType);
        return baseMapper.pointEventsStat(queryWrapper);
    }

    /**
     * 区域违法分布
     */
    @Override
    public List<HashMap<String, Object>> regionEventsStat(String dateType) {
        return baseMapper.regionEventsStat(dateType);
    }

    /**
     * 每分钟事件统计
     */
    @Override
    public List<HashMap<String, Object>> minuteEventsStat(String eventType) {
        LambdaQueryWrapper<SenEvents> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SenEvents::getEventType, eventType);
        return baseMapper.minuteEventsStat(queryWrapper);
    }

    /**
     * 交通违法数据来源分析
     */
    @Override
    public List<HashMap<String, Object>> eventsDatasourceStat(String dateType) {
        LambdaQueryWrapper<SenEvents> queryWrapper = buildDateWrapper(dateType);
        return baseMapper.eventsDatasourceStat(queryWrapper);
    }

    /**
     * 交通违法分布式时间
     */
    @Override
    public List<HashMap<String, Object>> eventsHourStat(String dateType) {
        LambdaQueryWrapper<SenEvents> queryWrapper = buildDateWrapper(dateType);
        return baseMapper.eventsHourStat(queryWrapper);
    }

    /**
     * 交通违法处置分析
     */
    @Override
    public List<HashMap<String, Object>> eventsDealRateStat(String dateType) {
        LambdaQueryWrapper<SenEvents> queryWrapper = buildDateWrapper(dateType);
        return baseMapper.eventsDealRateStat(queryWrapper);
    }

    /**
     * 骑行违法分析
     */
    @Override
    public TableDataInfo<Map<String, Object>> cycleEventStat(SenEventsBo senEventsBo, PageQuery pageQuery) {
        LambdaQueryWrapper<SenEvents> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(senEventsBo.getPointName()), SenEvents::getPointName, senEventsBo.getPointName());
        queryWrapper.ge(StringUtils.isNotBlank((CharSequence) senEventsBo.getParams().get("startDate")), SenEvents::getCreateTime, senEventsBo.getParams().get("startDate"))
                .le(StringUtils.isNotBlank((CharSequence) senEventsBo.getParams().get("endDate")), SenEvents::getCreateTime, senEventsBo.getParams().get("endDate"));
        Page<Map<String, Object>> result = baseMapper.cycleEventStat(pageQuery.build(), queryWrapper);
        return TableDataInfo.build(result);
    }

    /**
     * 重点车辆分析
     */
    @Override
    public TableDataInfo<Map<String, Object>> keyVehicleEventStat(SenEventsObjectBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SenEventsObject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(bo.getObjectId()), SenEventsObject::getObjectId, bo.getObjectId());
        String startDate = null;
        String endDate = null;
        if (StringUtils.isNotBlank((CharSequence) bo.getParams().get("startDate"))) {
            startDate = (String) bo.getParams().get("startDate");
        }
        if (StringUtils.isNotBlank((CharSequence) bo.getParams().get("endDate"))) {
            endDate = (String) bo.getParams().get("endDate");
        }
        Page<Map<String, Object>> result = baseMapper.keyVehicleEventStat(pageQuery.build(), startDate, endDate, queryWrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<SenEventsVo> eventsMediaList(SenEventsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SenEvents> queryWrapper = new LambdaQueryWrapper<>();
        String[] eventTypes = null;
        if(StringUtils.isNotBlank(bo.getEventType())){
            eventTypes= bo.getEventType().split(",");
        }
        String[] eventCategorys = null;
        if(StringUtils.isNotBlank(bo.getEventCategory())){
            eventCategorys= bo.getEventCategory().split(",");
        }
        queryWrapper.eq(bo.getPointId() != null, SenEvents::getPointId, bo.getPointId());
        queryWrapper.in(eventCategorys!=null, SenEvents::getEventCategory, (Object[]) eventCategorys);
        queryWrapper.eq(StringUtils.isNotBlank(bo.getDealStatus()), SenEvents::getDealStatus, bo.getDealStatus());
        queryWrapper.in(eventTypes!=null, SenEvents::getEventType, (Object[]) eventTypes);
        queryWrapper.ge(StringUtils.isNotBlank((CharSequence) bo.getParams().get("startDate")), SenEvents::getCreateTime, bo.getParams().get("startDate"))
                .le(StringUtils.isNotBlank((CharSequence) bo.getParams().get("endDate")), SenEvents::getCreateTime, bo.getParams().get("endDate"));
        queryWrapper.orderByDesc(SenEvents::getCreateTime);
        Page<SenEventsVo> result = baseMapper.selectVoPage(pageQuery.build(), queryWrapper);
        for (SenEventsVo vo : result.getRecords()) {
            LambdaQueryWrapper<SenEventsMedia> mediaWrapper = new LambdaQueryWrapper<>();
            mediaWrapper.eq(SenEventsMedia::getEventId, vo.getId());
            List<SenEventsMediaVo> mediaList = mediaMapper.selectVoList(mediaWrapper);
            vo.setMediaList(mediaList);
        }
        return TableDataInfo.build(result);
    }
}
