package com.sz.admin.monitor.listener.event;

import com.sz.admin.monitor.listener.mode.CameraDeleteEvent;
import com.sz.admin.monitor.mapper.EdgeBoxMapper;
import com.sz.admin.monitor.pojo.po.Camera;
import com.sz.admin.monitor.pojo.po.EdgeBox;
import com.sz.admin.monitor.pojo.vo.edgebox.AlgorithmTaskVO;
import com.sz.admin.monitor.service.AlgorithmTaskService;
import com.sz.admin.monitor.service.CameraService;
import com.sz.admin.monitor.service.impl.CameraServiceImpl;
import com.sz.admin.monitor.utils.AiBoxRequestUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * ClassName: CameraDeleteEventListener
 * Package: com.sz.admin.monitor.listener.event
 * Description:
 */
@Component
@Slf4j
public class CameraDeleteEventListener {
    @Resource
    private CameraService cameraService;
    @Resource
    private AlgorithmTaskService algorithmTaskService;
    @Resource
    private EdgeBoxMapper edgeBoxMapper;
    @Resource
    private AiBoxRequestUtil aiBoxRequestUtil;

    @EventListener
    @Async
    public void handleCameraDelete(CameraDeleteEvent event) {
        List<Long> ids = event.getCameraIds();
        try {
            List<Camera> cameraList = cameraService.listByIds(ids);
            if (cameraList.isEmpty()) return;
            List<AlgorithmTaskVO> taskList = algorithmTaskService.listByCameraIds(ids);
            // 一次性查询出这批摄像头管理的盒子
            Set<Long> boxIdset = cameraList
                .stream()
                .map(Camera::getBoxId)
                .collect(Collectors.toSet());
            Map<Long, EdgeBox> boxMap=new HashMap<>();
            if(!boxIdset.isEmpty())
            {
                List<EdgeBox> edgeBoxList = edgeBoxMapper.selectListByIds(boxIdset);
                boxMap = edgeBoxList.stream().collect(Collectors.toMap(EdgeBox::getId, edgeBox -> edgeBox));
            }
            try {
                // 批量删除本地数据
                cameraService.batchDeleteLocalData(ids, taskList);
            } catch (Exception e) {
                log.error("本地数据库删除失败，中止后续硬件清理逻辑以防数据割裂！", e);
                return;
            }
            // 清理盒子的算法任务
            for (AlgorithmTaskVO task : taskList) {
                if(task!=null && task.getAlgTaskSession()!=null)
                {
                    Camera camera = cameraList.stream().filter(c -> c.getId().equals(task.getCameraId()))
                        .findFirst()
                        .orElse(null);
                    if(camera==null) continue;
                    EdgeBox edgeBox = boxMap.get(camera.getBoxId());
                    if(edgeBox==null) continue;
                    try {
                        aiBoxRequestUtil.controlTask(edgeBox.getIp(), edgeBox.getPort(), task.getAlgTaskSession(), 0);
                        aiBoxRequestUtil.deleteTask(edgeBox.getIp(), edgeBox.getPort(), task.getAlgTaskSession());
                    } catch (Exception e) {
                        log.error("清理 AI 盒子任务失败，摄像机ID: {}, 忽略该错误继续执行...", task.getCameraId(), e);
                    }
                }
            }
            // 清理盒子的通道
            for (Camera camera : cameraList) {
                Long boxId = camera.getBoxId();
                if (boxId == null) continue;
                EdgeBox edgeBox = boxMap.get(boxId);
                if (edgeBox == null) continue;
                try {
                    aiBoxRequestUtil.deleteVideoChannel(edgeBox.getIp(), edgeBox.getPort(), camera.getId().toString());
                } catch (Exception e) {
                    log.error("清理 AI 盒子视频通道失败，摄像机ID: {}", camera.getId(), e);
                }
            }

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

}
