package com.pm.patrol.service.impl;

import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.pm.patrol.mapper.PatrolRecordMapper;
import com.pm.patrol.mapper.PatrolPointMapper;
import com.pm.patrol.service.IPatrolMonitorService;
import com.pm.common.config.PageData;

/**
 * 巡更监控Service业务层处理
 *
 * @author pm
 * @date 2025-06-03
 */
@Service
public class PatrolMonitorServiceImpl implements IPatrolMonitorService {
    
    @Autowired
    private PatrolRecordMapper patrolRecordMapper;
    
    @Autowired
    private PatrolPointMapper patrolPointMapper;

    @Override
    public List<PageData> getRealtimePatrolData() {
        // 获取最近的巡更记录（如最近30分钟内的）
        PageData pd = new PageData();
        pd.put("recentMinutes", 30);
        return patrolRecordMapper.selectRecentPatrolRecords(pd);
    }

    @Override
    public PageData getPatrolRouteInfo(String routeId) {
        // 获取巡更路线信息，包括路线上的所有巡更点
        PageData routeInfo = new PageData();
        routeInfo.put("routeId", routeId);
        
        // 获取路线基本信息
        // 这里可以调用路线相关的mapper
        
        // 获取路线上的巡更点
        List<PageData> points = patrolPointMapper.selectPointsByRouteId(routeId);
        routeInfo.put("points", points);
        
        return routeInfo;
    }

    @Override
    public PageData getCameraStreamInfo(String cameraId) {
        // 获取摄像头流信息
        PageData cameraInfo = new PageData();
        cameraInfo.put("cameraId", cameraId);
        
        // 这里应该调用第三方摄像头系统的接口获取流地址
        // 模拟返回数据
        cameraInfo.put("streamUrl", "rtsp://camera.example.com/stream/" + cameraId);
        cameraInfo.put("status", "online");
        
        return cameraInfo;
    }

    @Override
    public Map<String, Object> getPatrolStatistics(PageData pd) {
        Map<String, Object> statistics = new HashMap<>();
        
        // 获取今日巡更统计
        statistics.put("todayTotal", patrolRecordMapper.getTodayPatrolCount(pd));
        statistics.put("todayNormal", patrolRecordMapper.getTodayNormalCount(pd));
        statistics.put("todayAbnormal", patrolRecordMapper.getTodayAbnormalCount(pd));
        statistics.put("todayTimeout", patrolRecordMapper.getTodayTimeoutCount(pd));
        
        // 获取活跃巡更人员
        statistics.put("activePersonnel", patrolRecordMapper.getActivePersonnel(pd));
        
        // 获取巡更点覆盖率
        int totalPoints = patrolPointMapper.getTotalActivePoints();
        int patrolledPoints = patrolRecordMapper.getTodayPatrolledPoints(pd);
        double coverage = totalPoints > 0 ? (double) patrolledPoints / totalPoints * 100 : 0;
        statistics.put("coverage", String.format("%.2f", coverage));
        
        return statistics;
    }
}