package com.gxwebsoft.hjm.service;

import cn.hutool.core.util.StrUtil;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.hjm.entity.HjmCar;
import com.gxwebsoft.hjm.entity.HjmGpsLog;
import com.gxwebsoft.hjm.param.HjmCarParam;
import com.gxwebsoft.hjm.param.HjmGpsLogParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * GPS诊断服务
 *
 * @author 科技小王子
 * @since 2025-07-02
 */
@Service
public class GpsDiagnosticService {
    
    private static final Logger logger = LoggerFactory.getLogger(GpsDiagnosticService.class);
    
    @Resource
    private HjmCarService hjmCarService;
    
    @Resource
    private HjmGpsLogService hjmGpsLogService;
    
    @Resource
    private RedisUtil redisUtil;
    
    /**
     * 诊断GPS数据上送问题
     *
     * @return 诊断报告
     */
    public Map<String, Object> diagnoseGpsDataIssues() {
        Map<String, Object> report = new HashMap<>();
        
        logger.info("开始GPS数据诊断...");
        
        // 1. 检查所有车辆的GPS配置
        Map<String, Object> carGpsConfig = checkCarGpsConfiguration();
        report.put("车辆GPS配置检查", carGpsConfig);
        
        // 2. 检查GPS日志数据
        Map<String, Object> gpsLogAnalysis = analyzeGpsLogData();
        report.put("GPS日志分析", gpsLogAnalysis);
        
        // 3. 检查Redis缓存状态
        Map<String, Object> redisStatus = checkRedisCache();
        report.put("Redis缓存状态", redisStatus);
        
        // 4. 检查有数据的GPS设备
        Map<String, Object> activeGpsDevices = checkActiveGpsDevices();
        report.put("活跃GPS设备", activeGpsDevices);
        
        logger.info("GPS数据诊断完成");
        
        return report;
    }
    
    /**
     * 检查车辆GPS配置
     */
    private Map<String, Object> checkCarGpsConfiguration() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 查询所有车辆
            HjmCarParam param = new HjmCarParam();
            List<HjmCar> allCars = hjmCarService.listRel(param);
            
            int totalCars = allCars.size();
            int carsWithGps = 0;
            int carsWithoutGps = 0;
            
            Map<String, String> gpsDeviceMapping = new HashMap<>();
            
            for (HjmCar car : allCars) {
                if (StrUtil.isNotBlank(car.getGpsNo())) {
                    carsWithGps++;
                    gpsDeviceMapping.put(car.getGpsNo(), car.getCode());
                } else {
                    carsWithoutGps++;
                    logger.warn("车辆 {} (ID: {}) 未配置GPS设备编号", car.getCode(), car.getId());
                }
            }
            
            result.put("总车辆数", totalCars);
            result.put("已配置GPS的车辆数", carsWithGps);
            result.put("未配置GPS的车辆数", carsWithoutGps);
            result.put("GPS设备映射", gpsDeviceMapping);
            
            logger.info("车辆GPS配置检查完成 - 总数: {}, 已配置GPS: {}, 未配置GPS: {}", 
                       totalCars, carsWithGps, carsWithoutGps);
            
        } catch (Exception e) {
            logger.error("检查车辆GPS配置失败", e);
            result.put("错误", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 分析GPS日志数据
     */
    private Map<String, Object> analyzeGpsLogData() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 查询最近的GPS日志
            HjmGpsLogParam param = new HjmGpsLogParam();
            List<HjmGpsLog> recentLogs = hjmGpsLogService.listRel(param);
            
            Map<String, Integer> gpsDeviceLogCount = new HashMap<>();
            Map<String, String> latestLogTime = new HashMap<>();
            
            for (HjmGpsLog log : recentLogs) {
                String gpsNo = log.getGpsNo();
                if (StrUtil.isNotBlank(gpsNo)) {
                    gpsDeviceLogCount.put(gpsNo, gpsDeviceLogCount.getOrDefault(gpsNo, 0) + 1);
                    
                    if (log.getCreateTime() != null) {
                        String currentTime = latestLogTime.get(gpsNo);
                        String logTime = log.getCreateTime().toString();
                        if (currentTime == null || logTime.compareTo(currentTime) > 0) {
                            latestLogTime.put(gpsNo, logTime);
                        }
                    }
                }
            }
            
            result.put("总日志条数", recentLogs.size());
            result.put("各GPS设备日志数量", gpsDeviceLogCount);
            result.put("各GPS设备最新日志时间", latestLogTime);
            
            // 找出有数据的GPS设备
            if (!gpsDeviceLogCount.isEmpty()) {
                String mostActiveGps = gpsDeviceLogCount.entrySet().stream()
                    .max(Map.Entry.comparingByValue())
                    .map(Map.Entry::getKey)
                    .orElse("无");
                result.put("最活跃的GPS设备", mostActiveGps);
                result.put("最活跃设备日志数", gpsDeviceLogCount.getOrDefault(mostActiveGps, 0));
            }
            
            logger.info("GPS日志分析完成 - 总日志数: {}, 活跃设备数: {}", 
                       recentLogs.size(), gpsDeviceLogCount.size());
            
        } catch (Exception e) {
            logger.error("分析GPS日志数据失败", e);
            result.put("错误", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 检查Redis缓存状态
     */
    private Map<String, Object> checkRedisCache() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 检查围栏缓存
            String testGpsNo = "862317042719778";
            String fenceKey = "inFence:" + testGpsNo;
            String fenceCache = redisUtil.get(fenceKey);
            
            result.put("测试GPS围栏缓存键", fenceKey);
            result.put("测试GPS围栏缓存值", fenceCache != null ? fenceCache : "无缓存");
            
            // 检查GPS日志缓存
            String gpsLogCache = redisUtil.get(testGpsNo);
            result.put("测试GPS日志缓存", gpsLogCache != null ? gpsLogCache : "无缓存");
            
            logger.info("Redis缓存状态检查完成");
            
        } catch (Exception e) {
            logger.error("检查Redis缓存状态失败", e);
            result.put("错误", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 检查活跃的GPS设备
     */
    private Map<String, Object> checkActiveGpsDevices() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 检查特定GPS设备的车辆信息
            String activeGpsNo = "862317042719778";
            HjmCar activeCar = hjmCarService.getByGpsNo(activeGpsNo);
            
            if (activeCar != null) {
                Map<String, Object> activeCarInfo = new HashMap<>();
                activeCarInfo.put("车辆编号", activeCar.getCode());
                activeCarInfo.put("车辆名称", activeCar.getName());
                activeCarInfo.put("车辆ID", activeCar.getId());
                activeCarInfo.put("GPS设备编号", activeCar.getGpsNo());
                activeCarInfo.put("最新经度", activeCar.getLongitude());
                activeCarInfo.put("最新纬度", activeCar.getLatitude());
                activeCarInfo.put("最新速度", activeCar.getSpeed());
                activeCarInfo.put("更新时间", activeCar.getUpdateTime());
                activeCarInfo.put("围栏ID", activeCar.getFenceId());
                activeCarInfo.put("是否在围栏内", activeCar.getInFence());
                
                result.put("活跃GPS设备信息", activeCarInfo);
            } else {
                result.put("活跃GPS设备信息", "未找到对应车辆");
            }
            
            // 检查其他GPS设备
            HjmCarParam param = new HjmCarParam();
            List<HjmCar> allCars = hjmCarService.listRel(param);
            
            Map<String, String> otherGpsDevices = new HashMap<>();
            for (HjmCar car : allCars) {
                if (StrUtil.isNotBlank(car.getGpsNo()) && !activeGpsNo.equals(car.getGpsNo())) {
                    otherGpsDevices.put(car.getGpsNo(), car.getCode());
                }
            }
            
            result.put("其他GPS设备", otherGpsDevices);
            
            logger.info("活跃GPS设备检查完成");
            
        } catch (Exception e) {
            logger.error("检查活跃GPS设备失败", e);
            result.put("错误", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 检查特定GPS设备的详细信息
     *
     * @param gpsNo GPS设备编号
     * @return 设备详细信息
     */
    public Map<String, Object> checkSpecificGpsDevice(String gpsNo) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            logger.info("检查GPS设备详细信息: {}", gpsNo);
            
            // 检查车辆信息
            HjmCar car = hjmCarService.getByGpsNo(gpsNo);
            if (car != null) {
                result.put("车辆信息", car);
            } else {
                result.put("车辆信息", "未找到对应车辆");
            }
            
            // 检查GPS日志
            HjmGpsLogParam logParam = new HjmGpsLogParam();
            logParam.setGpsNo(gpsNo);
            List<HjmGpsLog> logs = hjmGpsLogService.listRel(logParam);
            result.put("GPS日志数量", logs.size());
            if (!logs.isEmpty()) {
                result.put("最新GPS日志", logs.get(0));
            }
            
            // 检查Redis缓存
            String fenceCache = redisUtil.get("inFence:" + gpsNo);
            String logCache = redisUtil.get(gpsNo);
            result.put("围栏缓存", fenceCache);
            result.put("日志缓存", logCache);
            
        } catch (Exception e) {
            logger.error("检查GPS设备详细信息失败: {}", gpsNo, e);
            result.put("错误", e.getMessage());
        }
        
        return result;
    }
}
