package com.yuchen.saas.park.service.pull.untils;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.thinkunion.park.service.common.constant.PKCONSTANT;
import com.yuchen.saas.integration.feign.api.feign.CameraClient;
import com.yuchen.saas.message.api.feign.ws.WebSocketFeignServer;
import com.yuchen.saas.message.api.vo.NoticeVo;
import com.yuchen.saas.park.api.entity.device.PmgBatSmartEquipment;
import com.yuchen.saas.park.api.entity.park.PmgLogPeopleCount;
import com.yuchen.saas.park.api.entity.park.Property;
import com.yuchen.saas.park.api.vo.park.DeviceOnLineCountVo;
import com.yuchen.saas.park.api.vo.park.HandleStatisticsVo;
import com.yuchen.saas.park.service.config.PeopleConfig;
import com.yuchen.saas.park.service.config.UtilDate;
import com.yuchen.saas.park.service.pull.entity.WSNotification;
import com.yuchen.saas.park.service.pull.input.DevicePropertyInput;
import com.yuchen.saas.park.service.pull.vo.DevicePropertyVo;
import com.yuchen.saas.park.service.service.*;
import org.nest.springwrap.core.tool.utils.Func;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * @author 刘通
 * @version 1.0
 * @date 2021/2/2 17:03
 * ws 推送公共类
 */
@Component
public class StompClient {

    @Resource
    private WebSocketFeignServer pushService;

    @Autowired
    private IWarningInfoService iWarningInfoService;

    @Autowired
    private ParkDeviceDataService deviceDataService;

    @Autowired
    private CameraClient cameraClient;

    @Autowired
    private PmgBatSmartEquipmentService pmgBatSmartEquipmentService;


    /**
     * 注入视频异常记录接口
     */
    @Autowired
    private PmgLogVideoEventsCountService pmgLogVideoEventsCountService;

    /**
     * 注入人员类别配置信息
     */
    @Autowired
    private PeopleConfig peopleConfig;

    /**
     * 注入报警信息对象接口
     */
    @Autowired
    private IPeopleCountService iPeopleCountService;

//    /**
//     * 注入车辆记录接口
//     */
//    @Autowired
//    private ParkingVehiclePassLogService parkingVehiclePassLogService;
//
//
//    /**
//     * 停车场相关
//     */
//    @Resource
//    private ParkingService parkingService;
//
    @Autowired
    private UtilDate utilDate;

    private final Logger logger = LoggerFactory.getLogger(DevicePropertyInput.class);

    public void pushPersonData(String parkId) {
        // 推送人员统计数据
        Map<String, Long> personData = iPeopleCountService.getPersonImage(parkId);
        if (Func.isNotEmpty(personData)) {
            WSNotification WSNotification = new WSNotification();
            WSNotification.setKey(WSConstant.KEY_ANALYSIS);
            WSNotification.setIdentity(WSConstant.GET_PERSON_IMAGE);

            Map<String, Object> valueMap = new HashMap<String, Object>();
            valueMap.put("count", personData.get("count"));
            valueMap.put("vipCount", personData.get("vipCount"));
            valueMap.put("insiderCount", personData.get("insiderCount"));
            valueMap.put("visitorCount", personData.get("visitorCount"));
            valueMap.put("todayVisitorCount", personData.get("todayVisitorCount"));

            WSNotification.setValue(valueMap);

            pushService.realTimeData(NoticeVo.getByParkIdAndData(parkId, JSON.toJSONString(WSNotification)));
        }
    }

    public void pushWarningByLevelData(String parkId) {
        // 一级、二级、三级、四级
        Map<String, Object> warningByLevelData = iWarningInfoService.getWarningByLevel(parkId);
        if (Func.isNotEmpty(warningByLevelData)) {
            WSNotification WSNotification = new WSNotification();
            WSNotification.setKey(WSConstant.KEY_HOME);
            WSNotification.setIdentity(WSConstant.DEVICE_WARNING_COUNT);
            Map<String, Object> valueMap = new HashMap<String, Object>();
            valueMap.put("countList", warningByLevelData.get("countList"));
            WSNotification.setValue(valueMap);
            pushService.realTimeData(NoticeVo.getByParkIdAndData(parkId, JSON.toJSONString(WSNotification)));
        }
    }

    public void pushEnterParkPeopleCount(String parkId) {
        // 入园小时分布  统计近24小时每小时的入园人数
        Map<String, Object> enterParkPeopleCount = iPeopleCountService
                .getCountTime24(Long.valueOf(parkId), null, null, null);
        if (Func.isNotEmpty(enterParkPeopleCount)) {
            WSNotification WSNotification = new WSNotification();
            WSNotification.setKey(WSConstant.KEY_HOME);
            WSNotification.setIdentity(WSConstant.GET_COUNT_TIME24);
            Map<String, Object> valueMap = new HashMap<String, Object>();
            valueMap.put("countArr", enterParkPeopleCount.get("countArr"));
            valueMap.put("timeArr", enterParkPeopleCount.get("timeArr"));
            WSNotification.setValue(valueMap);
            pushService.realTimeData(NoticeVo.getByParkIdAndData(parkId, JSON.toJSONString(WSNotification)));
        }
    }

    public void getWarningHandlerResult(String parkId) {
        // 已处理未处理
        Map<String, Long> handlerResult = iWarningInfoService.getWarningHandlerResult(parkId);
        if (Func.isNotEmpty(handlerResult)) {
            WSNotification WSNotification = new WSNotification();
            WSNotification.setKey(WSConstant.KEY_ANALYSIS);
            WSNotification.setIdentity(WSConstant.ANALYSIS_GETWARNINGHANDLERRESULT);
            Map<String, Object> valueMap = new HashMap<String, Object>();
            valueMap.put("abnormalPeople", handlerResult.get("abnormalPeople"));
            valueMap.put("isHandling", handlerResult.get("isHandling"));
            valueMap.put("monitorWarning", handlerResult.get("monitorWarning"));
            valueMap.put("unHandling", handlerResult.get("unHandling"));
            WSNotification.setValue(valueMap);
            pushService.realTimeData(NoticeVo.getByParkIdAndData(parkId, JSON.toJSONString(WSNotification)));
        }
    }

    /**
     * 行为事件、测温事件、异常事件（陌生人和高频人员） 的总数、已处理、未处理(已处理和未处理有的事件没有)
     */
    public void getStatistics(String parkId) {
        // 声明返回集合
        Map<String, Object> map = new HashMap<>();
        // 1、行为事件的总数、已处理，未处理
        HandleStatisticsVo handleStatisticsVo = pmgLogVideoEventsCountService.getStatistics(parkId);
        map.put("behavior", handleStatisticsVo);
        // 2、测温事件的总数、已处理、未处理
        QueryWrapper<PmgLogPeopleCount> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("temperature").gt("temperature", peopleConfig.getTemperature());
        map.put("temperature", iPeopleCountService.count(queryWrapper));
        // 3、异常事件的总数、已处理、未处理
        queryWrapper = new QueryWrapper<>();
        queryWrapper.in("code", peopleConfig.getCode10003(), peopleConfig.getCode10004());
        queryWrapper.eq("park_id", parkId);
        map.put("abnormal", iPeopleCountService.count(queryWrapper));
        // 已处理未处理
        if (Func.isNotEmpty(map)) {
            WSNotification WSNotification = new WSNotification();
            WSNotification.setKey(WSConstant.KEY_COUNT);
            WSNotification.setIdentity(WSConstant.GET_STATISTICS);
            WSNotification.setValue(map);
            pushService.realTimeData(NoticeVo.getByParkIdAndData(parkId, JSON.toJSONString(WSNotification)));
        }
    }

    /**
     * 摄像头在线离线
     * 已改
     */
    public void getCountOnlineCamera(String parkId) {
        Map<String, Object> countOnlineCamera = cameraClient.getCountOnlineCamera(parkId);
        logger.info("countOnlineCamera:" + countOnlineCamera);
        if (Func.isNotEmpty(countOnlineCamera)) {
            WSNotification WSNotification = new WSNotification();
            WSNotification.setKey(WSConstant.KEY_MINITOR);
            WSNotification.setIdentity(WSConstant.GET_COUNT_ON_LINE_CAMERA);
            Map<String, Object> valueMap = new HashMap<String, Object>();

            valueMap.put("onlineY", countOnlineCamera.get("onlineY"));
            valueMap.put("onlineN", countOnlineCamera.get("onlineN"));
            valueMap.put("cameraCount", countOnlineCamera.get("cameraCount"));
            WSNotification.setValue(valueMap);
            logger.info("WSNotification:" + WSNotification);
            pushService.realTimeData(NoticeVo.getByParkIdAndData(parkId, JSON.toJSONString(WSNotification)));
        }
    }

    /**
     * 设备在离线统计
     */
    public void getDeviceAnalysis(String parkId) {
        DeviceOnLineCountVo countOnlineCamera = pmgBatSmartEquipmentService.getOnLineCount(parkId);
        logger.info("countOnlineCamera:" + countOnlineCamera);
        if (Func.isNotEmpty(countOnlineCamera)) {
            WSNotification WSNotification = new WSNotification();
            WSNotification.setKey(WSConstant.KEY_MINITOR);
            WSNotification.setIdentity(WSConstant.GET_DEVICE_ANALYSIS);
            Map<String, Object> valueMap = new HashMap<String, Object>();
            valueMap.put("deviceCount", countOnlineCamera.getDeviceCount()); // 设备总数
            valueMap.put("onlineDeviceYes", countOnlineCamera.getOnlineDevice()); // 在线设备数
            valueMap.put("onlineDeviceNo", countOnlineCamera.getDeviceCount() - countOnlineCamera.getOnlineDevice()); // 在线设备数
            valueMap.put("warningDevice", countOnlineCamera.getWarningDevice()); // 告警设备数
            WSNotification.setValue(valueMap);
            logger.info("WSNotification:" + WSNotification);
            pushService.realTimeData(NoticeVo.getByParkIdAndData(parkId, JSON.toJSONString(WSNotification)));
        }
    }
    /**
     * 发送零点数据
     */
    public void sendZeroPointData(String parkId) {
        // 查询所有水表和电表的设备
        String keys = PKCONSTANT.WATERPK + "," + PKCONSTANT.AMMETERPK;
        List<PmgBatSmartEquipment> list = pmgBatSmartEquipmentService.getDevicesListByKey(parkId, keys);
        logger.info("jsonPmgBatSmartEquipment:" + list);
        if (Func.isNotEmpty(list)) {
            for (PmgBatSmartEquipment pmgBatSmartEquipment : list) {
                // 封装数据发送到stomp
                // 发送 到stomp
                DevicePropertyVo propertySend = new DevicePropertyVo();
                propertySend.setParkId(parkId);
                propertySend.setProduct("");
                propertySend.setIsOnline(pmgBatSmartEquipment.getIsOnline());
                propertySend.setEquipmentName(pmgBatSmartEquipment.getName());
                propertySend.setSetPosition(pmgBatSmartEquipment.getSetPosition());
                propertySend.setProductKey(pmgBatSmartEquipment.getProductKey());
                propertySend.setDeviceName(pmgBatSmartEquipment.getDeviceName());
                propertySend.setDesire(null);
                propertySend.setTimestamp(System.currentTimeMillis() / 1000L);
                // 发送今天水电量
                propertySend.setValue("0");
                propertySend.setIdentify(utilDate.getToday());
                logger.info("propertySend-零点:" + propertySend);
                pushService.send(NoticeVo.getByParkIdAndData(parkId, JSON.toJSONString(propertySend)));
                // -------------
                // 更新mongo
                Property p2 = new Property();
                p2.setParkId(parkId);
                p2.setEquipmentName(pmgBatSmartEquipment.getName());
                p2.setSetPosition(pmgBatSmartEquipment.getSetPosition());
                p2.setEId(pmgBatSmartEquipment.getId());
                p2.setProduct("");
                p2.setDesire(null);
                p2.setProductKey(pmgBatSmartEquipment.getProductKey());
                p2.setDeviceName(pmgBatSmartEquipment.getDeviceName());
                p2.setDeviceTime(System.currentTimeMillis() / 1000L);
                // 发送今天水电量
                p2.setIdentify(utilDate.getToday());
                p2.setValue("0");
                logger.info("p2AAA-零点:" + p2);
//                iDeviceDataService.saveDeviceData(p2);
            }
        }
    }

//    /**
//     * 车辆驶入驶出车位事件
//     */
//    public void placeCount(String parkId, Object placeCountData) {
//        logger.info("placeCountData:" + placeCountData);
//        if (Func.isNotEmpty(placeCountData)) {
//            WSNotification WSNotification = new WSNotification();
//            WSNotification.setKey(WSConstant.KEY_CAR);
//            WSNotification.setIdentity(WSConstant.LOG_PLACE_COUNT);
//            WSNotification.setValue((Map<String, Object>) placeCountData);
//            logger.info("WSNotification:" + JSON.toJSONString(WSNotification));
//            pushService.realTimeData(NoticeVo.getByParkIdAndData(parkId, JSON.toJSONString(WSNotification)));
//        }
//    }
//
//    /**
//     * 车位占用事件
//     */
//    public void placeCountUse(String parkId, Object placeCountUseData) {
//        logger.info("placeCountUseData:" + placeCountUseData);
//        if (Func.isNotEmpty(placeCountUseData)) {
//            WSNotification WSNotification = new WSNotification();
//            WSNotification.setKey(WSConstant.KEY_CAR);
//            WSNotification.setIdentity(WSConstant.LOG_PLACE_COUNT_USE);
//            WSNotification.setValue((Map<String, Object>) placeCountUseData);
//            logger.info("WSNotification:" + JSON.toJSONString(WSNotification));
//            pushService.realTimeData(NoticeVo.getByParkIdAndData(parkId, JSON.toJSONString(WSNotification)));
//        }
//    }
//
//    /**
//     * 车辆入场放行事件
//     */
//    public void pushParkingLogNotification(String parkId, String identifier, Object placeCountData) {
//        if (Func.isNotEmpty(placeCountData)) {
//            WSNotification WSNotification = new WSNotification();
//            WSNotification.setKey(WSConstant.KEY_CAR);
//            WSNotification.setIdentity(identifier);
//            WSNotification.setValue(placeCountData);
//            pushService.realTimeData(NoticeVo.getByParkIdAndData(parkId, JSON.toJSONString(WSNotification)));
//        }
//    }
//
//    /**
//     * 今日车辆总数（去重） 和 今日VIP车辆（去重）
//     */
//    public void getTodayAndVipRepeat(String parkId) {
//        // 今日车辆总数
//        Long todayCount = parkingVehiclePassLogService.getTodayCount(parkId);
//        // 今日VIP车辆
//        Long todayVIPCount = parkingVehiclePassLogService.getTodayVIPCount(parkId);
//        if (todayCount != null && todayVIPCount != null) {
//            WSNotification WSNotification = new WSNotification();
//            WSNotification.setKey(WSConstant.KEY_CAR);
//            WSNotification.setIdentity(WSConstant.GET_TODAY_AND_VIP_REPEAT);
//            Map<String, Object> valueMap = new HashMap<String, Object>();
//            valueMap.put("todayVIPCount", todayCount);
//            valueMap.put("todayCount", todayCount);
//            WSNotification.setValue(valueMap);
//            logger.info("WSNotification:" + WSNotification);
//            pushService.realTimeData(NoticeVo.getByParkIdAndData(parkId, JSON.toJSONString(WSNotification)));
//        }
//    }
//
//    /**
//     * 今日车辆总数（去重） 和 今日内部车辆（去重）
//     */
//    public void getTodayAndInnerRepeat(String parkId) {
//        // 今日车辆总数
//        Long todayCount = parkingVehiclePassLogService.getTodayCount(parkId);
//        // 今日内部车辆（去重）
//        Long todayInnerCount = parkingVehiclePassLogService.getTodayInnerCount(parkId);
//        if (todayCount != null && todayInnerCount != null) {
//            WSNotification WSNotification = new WSNotification();
//            WSNotification.setKey(WSConstant.KEY_CAR);
//            WSNotification.setIdentity(WSConstant.GET_TODAY_AND_INNER_REPEAT);
//            Map<String, Object> valueMap = new HashMap<String, Object>();
//            valueMap.put("todayInnerCount", todayInnerCount);
//            valueMap.put("todayCount", todayCount);
//            WSNotification.setValue(valueMap);
//            logger.info("WSNotification:" + WSNotification);
//            pushService.realTimeData(parkId, JSON.toJSONString(WSNotification));
//        }
//    }
//
//    /**
//     * 今日车辆总数（去重） 和 今日访客车辆（去重）
//     */
//    public void getTodayAndVisitorRepeat(String parkId) {
//        // 今日车辆总数
//        Long todayCount = parkingVehiclePassLogService.getTodayCount(parkId);
//        // 今日访客车辆（去重）
//        Long todayVisitorCount = parkingVehiclePassLogService.getTodayVisitorCount(parkId);
//        if (todayCount != null && todayVisitorCount != null) {
//            WSNotification WSNotification = new WSNotification();
//            WSNotification.setKey(WSConstant.KEY_CAR);
//            WSNotification.setIdentity(WSConstant.GET_TODAY_AND_VISITOR_REPEAT);
//            Map<String, Object> valueMap = new HashMap<String, Object>();
//            valueMap.put("todayVisitorCount", todayVisitorCount);
//            valueMap.put("todayCount", todayCount);
//            WSNotification.setValue(valueMap);
//            logger.info("WSNotification:" + WSNotification);
//            pushService.realTimeData(parkId, JSON.toJSONString(WSNotification));
//        }
//    }
//
//    /**
//     * 推送停车场车位数据
//     *
//     * @param parkId       园区ID
//     * @param parkingId    停车场ID
//     * @param passagesType 0 入 1 出
//     */
//    public int pushRemainingSpacesCount(String parkId, String parkingId, Integer passagesType) {
//        // TODO:下面这行代码，车辆类型暂时写死为0-普通车
//        ParkingStatisticsInfo parkingExtend =
//                parkingService.updateParkingSpaceCount(Long.valueOf(parkingId), 0, passagesType);
//        // 重新统计整个园区停车位数量
//        ParkingStatisticsInfo parkingExtendVO = parkingService.parkingCountStall(Long.valueOf(parkId));
//        WSNotification WSNotification = new WSNotification();
//        WSNotification.setKey(WSConstant.KEY_CAR);
//        WSNotification.setIdentity(WSConstant.PARKING_IOT);
//        Map<String, Object> content = JSON.parseObject(JSON.toJSONString(parkingExtendVO), Map.class);
//        WSNotification.setValue(content);
//        pushService.realTimeData(parkId, JSON.toJSONString(WSNotification));
//        return parkingExtend.getLeftPlace() != null ? parkingExtend.getLeftPlace() : 0;
//    }

}
