package com.cico.nest.lcdp.boot.core.qxsd.adapter.web;

import cn.hutool.core.date.DateUtil;
import com.cico.nest.lcdp.boot.core.qxsd.adapter.web.vo.ReportCarTypeFlowVO;
import com.cico.nest.lcdp.boot.core.qxsd.adapter.web.vo.StatisticalByEventType;
import com.cico.nest.lcdp.boot.core.qxsd.adapter.web.vo.StatisticalHoleVo;
import com.cico.nest.lcdp.boot.core.qxsd.adapter.web.vo.TableStatsReqVO;
import com.cico.nest.lcdp.boot.core.qxsd.application.service.StatisticalReportsService;
import com.cico.nest.lcdp.boot.core.qxsd.application.service.TunnelHoleService;
import com.cico.nest.lcdp.boot.core.qxsd.domain.event.EventType;
import com.cico.nest.lcdp.boot.core.qxsd.infrastructure.gatewayimpl.database.EventDetailMapper;
import com.cico.nest.lcdp.boot.core.qxsd.infrastructure.gatewayimpl.database.dataobject.EventDetailDO;
import com.cico.nest.lcdp.boot.core.qxsd.infrastructure.gatewayimpl.database.dataobject.TunnelHoleV2DO;
import com.cico.nest.lcdp.framework.common.pojo.CommonResult;
import com.cico.nest.lcdp.framework.mybatis.core.query.LambdaQueryWrapperX;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 统计报表
 * @author zws
 * @date 2024/10/28
 */

@Tag(name = "管理后台 - 数据统计")
@RestController
@RequestMapping("/qxsd/report")
public class StatisticalReportsController {

    @Resource
    private StatisticalReportsService statisticalReportsService;
    @Resource
    private TunnelHoleService tunnelHoleService;
    @Resource
    private EventDetailMapper eventDetailMapper;

    /**
     * 通行车次统计
     * @param tableStatsReqVO
     * @return
     */
    @PostMapping("/carTypeFlow")
    @Operation(summary = "通行车次统计")
    CommonResult<List<ReportCarTypeFlowVO>> carTypeFlow(@RequestBody TableStatsReqVO tableStatsReqVO){
        return CommonResult.success(statisticalReportsService.carTypeFlow(tableStatsReqVO));
    }

    /**
     * 通行流量趋势
     * @param tableStatsReqVO
     * @return
     */
    @PostMapping("/carTypeFlowDay")
    @Operation(summary = "通行流量趋势")
    CommonResult<List<Map<String,Object>>> carTypeFlowDay(@RequestBody TableStatsReqVO tableStatsReqVO){
        return CommonResult.success(statisticalReportsService.carTypeFlowDay(tableStatsReqVO));
    }

    /**
     * 24小时流量趋势
     * @param tableStatsReqVO
     * @return
     */
    @PostMapping("/carTypeFlowHour")
    @Operation(summary = "24小时流量趋势")
    CommonResult<List<Map<String,Object>>> carTypeFlowHour(@RequestBody TableStatsReqVO tableStatsReqVO){
        return CommonResult.success(statisticalReportsService.carTypeFlowHour(tableStatsReqVO));
    }

    /**
     * 24小时时速趋势
     * @param tableStatsReqVO
     * @return
     */
    @PostMapping("/carTypeSpeedTrend")
    @Operation(summary = "24小时时速趋势")
    CommonResult<List<Map<String,Object>>> carTypeSpeedTrend(@RequestBody TableStatsReqVO tableStatsReqVO){
        return CommonResult.success(statisticalReportsService.carTypeSpeedTrend(tableStatsReqVO));
    }

    /**
     * 整个隧道今日流量
     * @param tableStatsReqVO
     * @return
     */
    @PostMapping("/tunnelStatisticalTodayByHole")
    @Operation(summary = "整个隧道今日流量")
    CommonResult<StatisticalHoleVo> tunnelStatisticalTodayByHole(@RequestBody TableStatsReqVO tableStatsReqVO){
        StatisticalHoleVo statisticalHoleVo = new StatisticalHoleVo();
        String day = DateUtil.today().replaceAll("-","");
        tableStatsReqVO.setStartStatisticsDay(day);
        tableStatsReqVO.setEndStatisticsDay(day);
        List<TunnelHoleV2DO> holeV2DOList = tunnelHoleService.getTunnelBaseId(tableStatsReqVO.getTunnelBaseId());
        for (TunnelHoleV2DO tunnelHoleV2DO : holeV2DOList) {
            if("tunnel_up".equals(tunnelHoleV2DO.getSfHoleId())){
                tableStatsReqVO.setXlwTunnelId(tunnelHoleV2DO.getSfHoleId());
                List<ReportCarTypeFlowVO> list = statisticalReportsService.carTypeFlow(tableStatsReqVO);
                if(CollectionUtils.isNotEmpty(list)){
                    Integer count = list.stream().filter(item -> "全部".equals(item.getCatType())).findFirst().map(ReportCarTypeFlowVO::getCount).orElse(0);
                    statisticalHoleVo.setTunnelUpOld(count);
                }
            }
        }
        return CommonResult.success(statisticalHoleVo);
    }

    /**
     * 整个隧道事件统计
     * @return
     */
    @PostMapping("/tunnelStatisticalByEventType")
    @Operation(summary = "整个隧道今日流量")
    CommonResult<Map<String, EventType.TypeStatistics>> carTypeFlowByHole(@Validated  @RequestBody StatisticalByEventType statisticalByEventType ){
        String startTime = "";
        String endTime = "";
        // 1:今日;2:本月;3:本年;
        if( 1 == statisticalByEventType.getType()){
            startTime = DateUtil.today() + " 00:00:00";
            endTime = DateUtil.today() + " 23:59:59";

        }else if( 2 == statisticalByEventType.getType()){
            startTime = getCurrentMonthStartTime();
            endTime = getCurrentMonthEndTime();

        }else if( 3 == statisticalByEventType.getType()){
            startTime = DateUtil.year(new Date()) + "-01-01 00:00:00";
            endTime = DateUtil.year(new Date()) + "-12-31 23:59:59";
        }
        LambdaQueryWrapperX<EventDetailDO> wrapper = new LambdaQueryWrapperX<>();
        wrapper.eq(EventDetailDO::getBaseTunnelId, statisticalByEventType.getTunnelBaseId());
        wrapper.between(EventDetailDO::getEventStartTime,startTime,endTime);
        List<EventDetailDO> list = eventDetailMapper.selectList(wrapper);
        Map<String, EventType.TypeStatistics> map =  EventType.getTypeStatistics();
        for (String key : map.keySet()) {
            EventType.TypeStatistics typeStatistics = map.get(key);
            if(CollectionUtils.isNotEmpty(typeStatistics.getTypes())){
                long count = list.stream().filter(item -> typeStatistics.getTypes().contains(item.getEventType())).count();
                typeStatistics.setCount(count);
            }
        }

        return CommonResult.success(map);
    }



    /**
     * 获取当前月份开始时间并转换到字符串
     * 如 当前为10月1日，返回2024-10-01 00:00:00
     * @return 2024-10-01 00:00:00
     */
    public static String getCurrentMonthStartTime() {
        LocalDate startOfMonth = LocalDate.now().withDayOfMonth(1);
        return startOfMonth.atStartOfDay().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 获取当前月份结束时间并转换到字符串
     * 如 当前为10月1日，返回2024-10-31 23:59:59
     * @return 2024-10-31 23:59:59
     */
    public static String getCurrentMonthEndTime() {
        LocalDate endOfMonth = LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth());
        return endOfMonth.atTime(23, 59, 59).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

}
