package com.yuchen.saas.park.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yuchen.saas.message.api.feign.ws.WebSocketFeignServer;
import com.yuchen.saas.park.api.dto.park.IoTEvent;
import com.yuchen.saas.park.api.entity.device.PmgBatSmartEquipment;
import com.yuchen.saas.park.api.entity.park.PmgBatHandlerWarning;
import com.yuchen.saas.park.api.entity.park.PmgBatWarningCategory;
import com.yuchen.saas.park.api.entity.park.PmgBatWarningInfo;
import com.yuchen.saas.park.api.entity.park.PmgBatWarningLevel;
import com.yuchen.saas.park.api.vo.park.*;
import com.yuchen.saas.park.api.vo.pull.DeviceEventVo;
import com.yuchen.saas.park.service.mapper.WarningCategoryMapper;
import com.yuchen.saas.park.service.service.*;
import org.nest.springwrap.core.mp.base.BaseServiceImpl;
import org.nest.springwrap.core.tool.utils.Func;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 *
 */
@Service
public class WarningCategoryServiceImpl extends BaseServiceImpl<WarningCategoryMapper, PmgBatWarningCategory> implements IWarningCategoryService {
    @Override
    public PmgBatWarningCategoryVo getByIdentity1(String identity) {
        return baseMapper.queryByIdentify(identity);
    }

    @Autowired
    private IWarningInfoService iWarningInfoService;

    @Autowired
    private IWarningLevelService iWarningLevelService;

    @Resource
    private IHandlerWarningService iHandlerWarningService;

    @Resource
    private PmgBatSmartEquipmentService pmgBatSmartEquipmentService;

    //@Resource
    //private PushService pushService;
    @Resource
    private WebSocketFeignServer webSocketClient;

    /*@Resource
    private StompClient stompClient;*/

    /**
     * 监控点异常统计
     *
     * @param productKey
     * @return
     */
    @Override
    public Map<String, Object> getCameraCount(String productKey) {
        Map<String, Object> respMap = new HashMap<String, Object>();
        LambdaQueryWrapper<PmgBatWarningInfo> parkSpaceWrapper = Wrappers.lambdaQuery();
        // 获取摄像头预警总数
        int cameraAllCount = iWarningInfoService.count(parkSpaceWrapper.eq(PmgBatWarningInfo::getProductKey, productKey));
        int cameraUntreatedWarning = iWarningInfoService.count(parkSpaceWrapper.eq(PmgBatWarningInfo::getProductKey, productKey)
                .eq(PmgBatWarningInfo::getIsHandling, "0"));

        parkSpaceWrapper.clear();

        int cameraProcessedWarning = iWarningInfoService.count(parkSpaceWrapper.eq(PmgBatWarningInfo::getProductKey, productKey)
                .eq(PmgBatWarningInfo::getIsHandling, "1"));
        respMap.put("cameraAllCount", cameraAllCount);
        respMap.put("cameraUntreatedWarning", cameraUntreatedWarning);
        respMap.put("cameraProcessedWarning", cameraProcessedWarning);
        // 今日每小时异常数量统计
        List<GetCountTime24RespVo> returnR = baseMapper.getCountTime24(productKey);

        Map<String, Object> countTime24 = new HashMap<String, Object>();
        if (Func.isNotEmpty(returnR) && returnR.size() > 0) {
            List<String> countArr = new ArrayList<String>();
            List<String> timeArr = new ArrayList<String>();
            for (GetCountTime24RespVo getVo : returnR) {
                countArr.add(getVo.getCount());
                timeArr.add(getVo.getHour());
            }
            countTime24.put("countArr", countArr);
            countTime24.put("timeArr", timeArr);
        }
        respMap.put("returnMap", countTime24);
        return respMap;
    }

    @Override
    public Map<String, Object> getCountTime24() {
        return null;
    }

    /**
     * 统计近一周的异常
     */
    @Override
    public List<WarningCategoryAbnormalCount> getAbnormalCount(String datetime) {

        List<PmgBatWarningInfo> pmgBatWarningInfos = iWarningInfoService.list();
        List<PmgBatWarningCategory> pmgBatWarningCategories = this.list();


        Map<String, String> keys = new HashMap<>();
        pmgBatWarningCategories.forEach(c -> {
            String identity = c.getIdentity();
            keys.putIfAbsent(identity, c.getName());
        });

        List<WarningCategoryAbnormalCount> warningCategoryAbnormalCounts = new ArrayList<>();
        keys.forEach((key, value) -> {
            WarningCategoryAbnormalCount warningCategoryAbnormalCount = new WarningCategoryAbnormalCount();
            warningCategoryAbnormalCount.setName(value);

            List<String> countArr = new ArrayList<>();

            for (String date : datetime.split(",")) {
                countArr.add(pmgBatWarningInfos.stream().filter(category -> category.getIdentity().equals(key)
                        && category.getCreateTime().after(Date.from(LocalDateTime.parse(date + " 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).atZone(ZoneId.systemDefault()).toInstant()))
                        && category.getCreateTime().before(Date.from(LocalDateTime.parse(date + " 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).atZone(ZoneId.systemDefault()).toInstant()))).count() + "");
            }
            warningCategoryAbnormalCount.setCountArr(countArr);
            warningCategoryAbnormalCounts.add(warningCategoryAbnormalCount);
        });

        return warningCategoryAbnormalCounts;
    }

	@Override
	public List<WarningCategoryAbnormalCount> getAbnormalCount(String datetime, String parkId) {
		QueryWrapper<PmgBatWarningInfo> queryWrapper = new QueryWrapper<PmgBatWarningInfo>().eq("park_id", parkId);
		List<PmgBatWarningInfo> pmgBatWarningInfos = iWarningInfoService.list(queryWrapper);
		QueryWrapper<PmgBatWarningCategory> queryWrapper1 = new QueryWrapper<PmgBatWarningCategory>().eq("park_id", parkId);
		List<PmgBatWarningCategory> pmgBatWarningCategories = this.list(queryWrapper1);


		Map<String, String> keys = new HashMap<>();
		pmgBatWarningCategories.forEach(c -> {
			String identity = c.getIdentity();
			keys.putIfAbsent(identity, c.getName());
		});

		List<WarningCategoryAbnormalCount> warningCategoryAbnormalCounts = new ArrayList<>();
		keys.forEach((key, value) -> {
			WarningCategoryAbnormalCount warningCategoryAbnormalCount = new WarningCategoryAbnormalCount();
			warningCategoryAbnormalCount.setName(value);

			List<String> countArr = new ArrayList<>();

			for (String date : datetime.split(",")) {
				countArr.add(pmgBatWarningInfos.stream().filter(category -> category.getIdentity().equals(key)
						&& category.getCreateTime().after(Date.from(LocalDateTime.parse(date + " 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).atZone(ZoneId.systemDefault()).toInstant()))
						&& category.getCreateTime().before(Date.from(LocalDateTime.parse(date + " 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).atZone(ZoneId.systemDefault()).toInstant()))).count() + "");
			}
			warningCategoryAbnormalCount.setCountArr(countArr);
			warningCategoryAbnormalCounts.add(warningCategoryAbnormalCount);
		});

		return warningCategoryAbnormalCounts;
	}



    /**
     * 获取报警类型对象信息-分页
     * @param page 分页信息
     * @return
     */
    @Override
    public IPage<WarningCategoryLevelName> getWarningCategoryPage(IPage<Object> page) {
        return baseMapper.getWarningCategoryPage(page);
    }

    @Override
    public PmgBatWarningCategoryVo getByIdentity(String identity) {
        PmgBatWarningCategoryVo pmgBatWarningCategoryVo = new PmgBatWarningCategoryVo();
        PmgBatWarningCategory pmgBatWarningCategory = getOne(Wrappers.<PmgBatWarningCategory>query().lambda().eq(PmgBatWarningCategory::getIdentity, identity));
        if (null != pmgBatWarningCategory && null != pmgBatWarningCategory.getId()) {
            PmgBatWarningLevel pmgBatWarningLevel = iWarningLevelService.getById(pmgBatWarningCategory.getLevelId());
            pmgBatWarningCategoryVo.setIdentity(identity);
            pmgBatWarningCategoryVo.setRemark(pmgBatWarningCategory.getRemark());
            pmgBatWarningCategoryVo.setLevel(pmgBatWarningLevel.getLevel());
            pmgBatWarningCategoryVo.setLevelName(pmgBatWarningLevel.getName());
            return pmgBatWarningCategoryVo;
        } else {
            pmgBatWarningCategoryVo.setIdentity(identity);
            pmgBatWarningCategoryVo.setRemark("无");
            return pmgBatWarningCategoryVo;
        }
    }

    /**
     * 为使用暂时屏蔽
     * @param ioTEvent
     */
    @Override
    public void inputData(IoTEvent ioTEvent) {

        PmgBatWarningCategoryVo pmgBatWarningCategoryVo = getByIdentity(ioTEvent.getIdentifier());

        if (ioTEvent.getProductKey() != null) {

            // 告警事件处理
            PmgBatHandlerWarning pmgBatHandlerWarning = iHandlerWarningService.getHandlerResult(ioTEvent.getProductKey(),
                    ioTEvent.getDeviceName());

            if (null != pmgBatHandlerWarning) {
                long event_time = ioTEvent.getEventTime();
                if (pmgBatHandlerWarning.getEndTime() != null && event_time < pmgBatHandlerWarning.getEndTime()) {
                    return;
                }
            }

            PmgBatSmartEquipment pmgBatSmartEquipment = pmgBatSmartEquipmentService.getDetails(ioTEvent.getProductKey(), ioTEvent.getDeviceName());

            // 封装数据保存历史报警
            PmgBatWarningInfo pmgBatWarningInfo = new PmgBatWarningInfo();
            pmgBatWarningInfo.setProductKey(ioTEvent.getProductKey());
            pmgBatWarningInfo.setDeviceName(ioTEvent.getDeviceName());
            pmgBatWarningInfo.setIdentity(ioTEvent.getIdentifier());
            pmgBatWarningInfo.setRemark(pmgBatWarningCategoryVo.getRemark());
            pmgBatWarningInfo.setLevel(pmgBatWarningCategoryVo.getLevel());
            pmgBatWarningInfo.setIsHandling("0");
            pmgBatWarningInfo.setName(pmgBatSmartEquipment.getName());
            pmgBatWarningInfo.setLevelName(pmgBatWarningCategoryVo.getLevelName());
            pmgBatWarningInfo.setParkId(pmgBatSmartEquipment.getParkId());
            pmgBatWarningInfo.setEventTime(ioTEvent.getEventTime());
            pmgBatWarningInfo.setTenantId(pmgBatSmartEquipment.getTenantId());
            pmgBatWarningInfo.setSetPosition(pmgBatSmartEquipment.getSetPosition());
            pmgBatWarningInfo.setCreateDept(pmgBatSmartEquipment.getCreateDept());

            pmgBatWarningInfo.setBuildingId(pmgBatSmartEquipment.getBuildingId());
            pmgBatWarningInfo.setFloorId(pmgBatSmartEquipment.getFloorId());
            pmgBatWarningInfo.setRoomId(pmgBatWarningInfo.getRoomId());

            iWarningInfoService.save(pmgBatWarningInfo);

            // 封装数据发送到stomp
            DeviceEventVo deviceEventVo = new DeviceEventVo();
            deviceEventVo.setEquipmentName(pmgBatSmartEquipment.getName());
            deviceEventVo.setProduct("");
            deviceEventVo.setOut(ioTEvent.getOut());
            deviceEventVo.setPosition("");
            deviceEventVo.setLevel(pmgBatWarningCategoryVo.getLevel());
            deviceEventVo.setLevelName(pmgBatWarningCategoryVo.getLevelName());
            deviceEventVo.setRemark(pmgBatWarningCategoryVo.getRemark());
            deviceEventVo.setIdentify(ioTEvent.getIdentifier());
            deviceEventVo.setProductKey(ioTEvent.getProductKey());
            deviceEventVo.setDeviceName(ioTEvent.getDeviceName());
            deviceEventVo.setEventTime(ioTEvent.getEventTime());
            deviceEventVo.setParkId(String.valueOf(pmgBatSmartEquipment.getParkId()));
            deviceEventVo.setSetPosition(pmgBatSmartEquipment.getSetPosition());

            deviceEventVo.setBuildingId(pmgBatSmartEquipment.getBuildingId());
            deviceEventVo.setFloorId(pmgBatSmartEquipment.getFloorId());
            deviceEventVo.setRoomId(pmgBatWarningInfo.getRoomId());
            //pushService.postEvent(String.valueOf(pmgBatSmartEquipment.getParkId()), JSON.toJSONString(deviceEventVo));

            // 已处理未处理
            //stompClient.getWarningHandlerResult(String.valueOf(pmgBatSmartEquipment.getParkId()));

        }
    }

    public WarningLevelVo getWarningLevelInfo(String identity){
        WarningLevelVo levelVo=new WarningLevelVo();

        LambdaQueryWrapper<PmgBatWarningCategory> categoryQueryWrapper=new LambdaQueryWrapper<>();
        categoryQueryWrapper.eq(PmgBatWarningCategory::getIdentity,identity).last("limit 1");
        PmgBatWarningCategory category=getBaseMapper().selectOne(categoryQueryWrapper);
        if(category!=null){
            levelVo.setIdentity(identity);
            levelVo.setRemark(category.getRemark());
            if(category.getLevelId()!=null){
                PmgBatWarningLevel level=iWarningLevelService.getById(category.getLevelId());
                levelVo.setLevel(level.getLevel());
                levelVo.setLevelName(level.getName());
            }
        }
        return levelVo;
    }

}
