package com.fastbee.data.controller.aaScreenAgricultural;

import cn.hutool.json.JSONObject;
import com.alibaba.druid.sql.ast.statement.SQLForeignKeyImpl;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.holder.ProjectHolder;
import com.fastbee.deviceData.api.devlink.service.ZhanLianBaseService;
import com.fastbee.deviceData.domain.dto.DeviceProperties;
import com.fastbee.deviceInfo.domain.*;
import com.fastbee.deviceInfo.manager.DeviceInformationManager;
import com.fastbee.deviceInfo.mapper.*;
import com.fastbee.iot.domain.AlertLog;
import com.fastbee.iot.domain.Device;
import com.fastbee.iot.mapper.AlertLogMapper;
import com.fastbee.iot.mapper.DeviceMapper;
import com.fastbee.iot.model.DeviceShortOutput;
import com.fastbee.iot.service.IDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.jws.Oneway;
import java.util.*;

/**
 * 设备告警
 */
@RestController
@RequestMapping("/device/statistics")
public class DeviceAlarmController extends BaseController {

    @Autowired
    private ZhanLianBaseService zhanLianBaseService;

    @Autowired
    private AlertLogMapper alertLogMapper;

    @Autowired
    private DeviceInformationManager deviceInformationManager;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private DeviceInformationWormsMapper wormsMapper;

    @Autowired
    private DeviceInformationMeteorologyMapper meteorologyMapper;

    @Autowired
    private DeviceInformationMoistureMapper moistureMapper;

    @Autowired
    private DeviceInformationMonitorMapper monitorMapper;

    @Autowired
    private DeviceInformationTargetpestsMapper targetpestsMapper;

    /**
     * 获取设备告警数量
     */
    @GetMapping("/alarm/count")
    public AjaxResult getDeviceAlarmCount() {

//        HashMap<String, Object> body = new HashMap<>();
//        body.put("method","get");
//        body.put("path","api/v1/product/device/statistics/months");
//        JSONObject data = devLinkBaseService.baseRequest(body);
//        alertLogMapper
//        return AjaxResult.success(data);
        Long count = new LambdaQueryChainWrapper<>(alertLogMapper)
                .select(AlertLog::getAlertLogId)
                .eq(false,AlertLog::getUserId,"")
                .count();

        //统计设备离线数量
//        List<Device> deviceList = new LambdaQueryChainWrapper<>(deviceMapper)
//                .select(Device::getDeviceId,Device::getDeviceName,Device::getProductId,Device::getProductName,Device::getStatus,Device::getTenantId)
//                .eq(Device::getTenantId, ProjectHolder.getProjectInfo().getProjectAdminId())
//                .list();
//        //循环统计状态值为4离线设备数量
//        int count1 = 0;
//        for (Device device : deviceList) {
//            if(device.getStatus()==4){
//                count1++;
//            }
//        }
        //统计设备总离线量
        Map<String, Map<String, Object>> info = getAllTypeDeviceListAndStatusCount();
        //虫情设备信息
        Map<String, Object> worm = info.get("worm");
        //气象设备信息
        Map<String, Object> meteorology = info.get("meteorology");
        //墒情设备信息
        Map<String, Object> moisture = info.get("moisture");
        //监控设备信息
        Map<String, Object> monitor = info.get("monitor");
        //杀虫灯设备信息
        Map<String, Object> targetpest = info.get("targetpest");

        int offlineCount=0;
        //计算离线设备总数
        offlineCount+=Integer.parseInt(String.valueOf(worm.get("deviceOfflineCount")));
        offlineCount+=Integer.parseInt(String.valueOf(meteorology.get("deviceOfflineCount")));
        offlineCount+=Integer.parseInt(String.valueOf(moisture.get("deviceOfflineCount")));
        offlineCount+=Integer.parseInt(String.valueOf(monitor.get("deviceOfflineCount")));
        offlineCount+=Integer.parseInt(String.valueOf(targetpest.get("deviceOfflineCount")));
        System.err.println("设备离线数量："+offlineCount);



        Map<String,Object> resp =new HashMap<>();
        resp.put("alarmTotal",count);//告警总数
        resp.put("securityLevel",getSecurityLevel(count));//安全等级
        resp.put("offlineDeviceTotal",offlineCount);//离线设备总数
        return AjaxResult.success(resp);
    }



    /**
     * 统计不同设备数量
     */
    @GetMapping("/countByType")
    public AjaxResult getDeviceCountByType() {
        return AjaxResult.success(deviceInformationManager.getAllDeviceCount());
    }

    /**
     * 统计设备在线率
     */
    @GetMapping("/onlineRate")
    public AjaxResult getDeviceOnlineRate(Device device) {

        Map<String, Map<String, Object>> info = getAllTypeDeviceListAndStatusCount();
        //虫情设备信息
        Map<String, Object> worm = info.get("worm");
        //气象设备信息
        Map<String, Object> meteorology = info.get("meteorology");
        //墒情设备信息
        Map<String, Object> moisture = info.get("moisture");
        //监控设备信息
        Map<String, Object> monitor = info.get("monitor");
        //杀虫灯设备信息
        Map<String, Object> targetpest = info.get("targetpest");

        System.out.println("-------------------------------------------");
        //封装结果
        List<DeviceProperties> restList=new ArrayList<>();
        restList.add(DeviceProperties.builder().name("气象监测").value(String.valueOf(meteorology.get("deviceOnlineRate"))).unit("%").build());
        restList.add(DeviceProperties.builder().name("墒情监测").value(String.valueOf(moisture.get("deviceOnlineRate"))).unit("%").build());
        restList.add(DeviceProperties.builder().name("虫情监测").value(String.valueOf(worm.get("deviceOnlineRate"))).unit("%").build());
//        restList.add(DeviceProperties.builder().name("苗情监测").value(String.valueOf(miaoQingDeviceOnlineRate)).unit("%").build());
        restList.add(DeviceProperties.builder().name("杀虫灯").value(String.valueOf(targetpest.get("deviceOnlineRate"))).unit("%").build());
        restList.add(DeviceProperties.builder().name("监控").value(String.valueOf(monitor.get("deviceOnlineRate"))).unit("%").build());

        return AjaxResult.success(restList);
    }


    /**
     * 查询所有类型设备列表返回每种设备列表Map
     */
    private Map<String,Map<String,Object>> getAllTypeDeviceListAndStatusCount(){
        Map<String,Map<String,Object>> resultMap=new HashMap<>();
        int meteorologyDeviceCount = 0;//气象设备总量
        int meteorologyDeviceOnLineCount = 0;//气象设备在线量
        int meteorologyDeviceOfflineCount=0;//气象设备离线量
        double meteorologyDeviceOnlineRate = 0.0; //气象设备在线率

        int moistureDeviceCount = 0;//墒情设备总量
        int moistureDeviceOnLineCount = 0;//墒情设备在线量
        int moistureDeviceOfflineCount=0;//墒情设备离线量
        double moistureDeviceOnlineRate = 0.0; //墒情设备在线率

        int wormDeviceCount = 0;//虫情设备总量
        int wormDeviceOnLineCount = 0;//虫情设备在线量
        int wormDeviceOfflineCount=0;//虫情设备离线量
        double wormDeviceOnlineRate = 0.0; //虫情设备在线率

        int miaoQingDeviceCount = 0;//苗情设备总量
        int miaoQingDeviceOnLineCount = 0;//苗情设备在线量
        int miaoQingDeviceOfflineCount=0;//苗情设备离线量
        double miaoQingDeviceOnlineRate = 0.0; //苗情设备在线率

        int insecticidalLampDeviceCount = 0;//杀虫灯设备总量
        int insecticidalLampDeviceOnLineCount = 0;//杀虫灯设备在线量
        int insecticidalLampDeviceOfflineCount=0;//杀虫灯设备离线量
        double insecticidalLampDeviceOnlineRate = 0.0; //杀虫灯设备在线率

        int monitorDeviceCount = 0;//监控设备总量
        int monitorDeviceOnLineCount = 0;//监控设备在线量
        int monitorDeviceOfflineCount=0;//监控设备离线量
        double monitorDeviceOnlineRate = 0.0; //监控设备在线率

//        List<Device> deviceList = new LambdaQueryChainWrapper<>(deviceMapper)
//                .select(Device::getDeviceId,Device::getDeviceName,Device::getProductId,Device::getProductName,Device::getStatus,Device::getTenantId)
//                .eq(Device::getTenantId,device.getTenantId())
//                .list();
////        deviceList.forEach(System.err::println);
//        for (Device d:deviceList) {
//            if (d.getProductName().equals("气象设备") || d.getProductId() == 144) {
//                meteorologyDeviceCount++;
//                if (d.getStatus() == 3) {
//                    meteorologyDeviceOnLineCount++;
//                }
//            } else if (d.getProductName().equals("墒情设备") || d.getProductId() == 142) {
//                moistureDeviceCount++;
//                if (d.getStatus() == 3) {
//                    moistureDeviceOnLineCount++;
//                }
//            } else if (d.getProductName().equals("太阳能供电设备") || d.getProductId() == 138) {
//                miaoQingDeviceCount++;
//                if (d.getStatus() == 3) {
//                    miaoQingDeviceOnLineCount++;
//                }
//            } else if (d.getProductName().equals("杀虫灯设备") || d.getProductId() == 145) {
//                insecticidalLampDeviceCount++;
//                if (d.getStatus() == 3) {
//                    insecticidalLampDeviceOnLineCount++;
//                }
//            } else if (d.getProductName().equals("虫情设备") || d.getProductId() == 143) {
//                wormDeviceCount++;
//                if (d.getStatus() == 3) {
//                    wormDeviceOnLineCount++;
//                }
//
//            } else if ( d.getProductName().equals("萤石云视频")||d.getProductId()==141) {
//                monitorDeviceCount++;
//                if(d.getStatus()==3){
//                    monitorDeviceOnLineCount++;
//                }
//            }
//        }

        //查询虫情设备列表

        List<DeviceInformationWorms> wormList =  new LambdaQueryChainWrapper<>(wormsMapper)
                .select(DeviceInformationWorms::getStatus)
                .list();
        wormDeviceCount=wormList.size();
        for(DeviceInformationWorms d:wormList){
            if(d.getStatus()==1){
                wormDeviceOnLineCount++;
            } else if (d.getStatus()==0) {
                wormDeviceOfflineCount++;
            }
        }
        //查询墒情设备列表
        List<DeviceInformationMoisture> moistureList = new LambdaQueryChainWrapper<>(moistureMapper).select(DeviceInformationMoisture::getStatus).list();
        moistureDeviceCount=moistureList.size();
        for(DeviceInformationMoisture d:moistureList){
            if(d.getStatus()==1){
                moistureDeviceOnLineCount++;
            } else if (d.getStatus()==0) {
               meteorologyDeviceOfflineCount++;
            }
        }
        //查询气象设备列表
        List<DeviceInformationMeteorology> meteorologyList = new LambdaQueryChainWrapper<>(meteorologyMapper).select(DeviceInformationMeteorology::getStatus).list();
        meteorologyDeviceCount=meteorologyList.size();
        for(DeviceInformationMeteorology d:meteorologyList){
            if(d.getStatus()==1){
                meteorologyDeviceOnLineCount++;
            } else if (d.getStatus()==0) {
                meteorologyDeviceOfflineCount++;
            }
        }

        //查询监控设备列表
        List<DeviceInformationMonitor> monitorList =   new LambdaQueryChainWrapper<>(monitorMapper).select(DeviceInformationMonitor::getStatus).list();
        monitorDeviceCount=monitorList.size();
        for(DeviceInformationMonitor d:monitorList){
            if(d.getStatus()==1){
                monitorDeviceOnLineCount++;
            } else if (d.getStatus()==0) {
                monitorDeviceOfflineCount++;
            }
        }

        //查询杀虫灯设备列表
        List<DeviceInformationTargetpests> targetpestList =   new LambdaQueryChainWrapper<>(targetpestsMapper).select(DeviceInformationTargetpests::getStatus).list();
        insecticidalLampDeviceCount=targetpestList.size();
        for(DeviceInformationTargetpests d:targetpestList){
            if(d.getStatus()==1){
                insecticidalLampDeviceOnLineCount++;
            } else if (d.getStatus()==0) {
                insecticidalLampDeviceOfflineCount++;
            }
        }

        //计算在线率
        //气象设备在线率
        meteorologyDeviceOnlineRate = meteorologyDeviceCount==0?0.0:((double) meteorologyDeviceOnLineCount / meteorologyDeviceCount)*100;
        //墒情设备在线率
        moistureDeviceOnlineRate = moistureDeviceCount==0?0.0:((double) moistureDeviceOnLineCount / moistureDeviceCount)*100;
        //虫情设备在线率
        wormDeviceOnlineRate = wormDeviceCount==0?0.0:((double) wormDeviceOnLineCount / wormDeviceCount)*100;
        //苗情设备在线率
//        miaoQingDeviceOnlineRate = miaoQingDeviceCount==0?0.0:((double) miaoQingDeviceOnLineCount / miaoQingDeviceCount)*100;
        //杀虫灯设备在线率
        insecticidalLampDeviceOnlineRate = insecticidalLampDeviceCount==0?0.0:((double) insecticidalLampDeviceOnLineCount / insecticidalLampDeviceCount)*100;
        //监控设备在线率
        monitorDeviceOnlineRate = monitorDeviceCount==0?0.0:((double) monitorDeviceOnLineCount / monitorDeviceCount)*100;

        //打印累加后结果
        System.out.println("气象设备总量:"+meteorologyDeviceCount);
        System.out.println("气象设备在线量:"+meteorologyDeviceOnLineCount);
        System.out.println("气象设备在线率:"+meteorologyDeviceOnlineRate);
        System.out.println("-------------------------------------------");
        System.out.println("墒情设备总量:"+moistureDeviceCount);
        System.out.println("墒情设备在线量:"+moistureDeviceOnLineCount);
        System.out.println("墒情设备在线率:"+moistureDeviceOnlineRate);
        System.out.println("-------------------------------------------");
        System.out.println("虫情设备总量:"+wormDeviceCount);
        System.out.println("虫情设备在线量:"+wormDeviceOnLineCount);
        System.out.println("虫情设备在线率:"+wormDeviceOnlineRate);
//        System.out.println("-------------------------------------------");
//        System.out.println("苗情设备总量:"+miaoQingDeviceCount);
//        System.out.println("苗情设备在线量:"+miaoQingDeviceOnLineCount);
//        System.out.println("苗情设备在线率:"+miaoQingDeviceOnlineRate);
        System.out.println("-------------------------------------------");
        System.out.println("杀虫灯设备总量:"+insecticidalLampDeviceCount);
        System.out.println("杀虫灯设备在线量:"+insecticidalLampDeviceOnLineCount);
        System.out.println("杀虫灯设备在线率:"+insecticidalLampDeviceOnlineRate);
        System.out.println("-------------------------------------------");
        System.out.println("监控设备总量:"+monitorDeviceCount);
        System.out.println("监控设备在线量:"+monitorDeviceOnLineCount);
        System.out.println("监控设备在线率:"+monitorDeviceOnlineRate);
        System.out.println("-------------------------------------------");


        Map<String,Object> worm=new HashMap<>();
        worm.put("deviceCount",wormDeviceCount);
        worm.put("deviceOnlineCount",wormDeviceOnLineCount);
        worm.put("deviceOfflineCount",wormDeviceOfflineCount);
        worm.put("deviceOnlineRate",wormDeviceOnlineRate);
        resultMap.put("worm",worm);


        Map<String,Object> moisture=new HashMap<>();
        moisture.put("deviceCount",moistureDeviceCount);
        moisture.put("deviceOnlineCount",moistureDeviceOnLineCount);
        moisture.put("deviceOfflineCount",moistureDeviceOfflineCount);
        moisture.put("deviceOnlineRate",moistureDeviceOnlineRate);
        resultMap.put("moisture",moisture);


        Map<String,Object> meteorology=new HashMap<>();
        meteorology.put("deviceCount",meteorologyDeviceCount);
        meteorology.put("deviceOnlineCount",meteorologyDeviceOnLineCount);
        meteorology.put("deviceOfflineCount",meteorologyDeviceOfflineCount);
        meteorology.put("deviceOnlineRate",meteorologyDeviceOnlineRate);
        resultMap.put("meteorology",meteorology);


        Map<String,Object> targetpest=new HashMap<>();
        targetpest.put("deviceCount",insecticidalLampDeviceCount );
        targetpest.put("deviceOnlineCount",insecticidalLampDeviceOnLineCount);
        targetpest.put("deviceOfflineCount",insecticidalLampDeviceOfflineCount);
        targetpest.put("deviceOnlineRate",insecticidalLampDeviceOnlineRate);
        resultMap.put("targetpest",targetpest);



        Map<String,Object> monitor=new HashMap<>();
        monitor.put("deviceCount",monitorDeviceCount);
        monitor.put("deviceOnlineCount",monitorDeviceOnLineCount);
        monitor.put("deviceOfflineCount",monitorDeviceOfflineCount);
        monitor.put("deviceOnlineRate",monitorDeviceOnlineRate);
        resultMap.put("monitor",monitor);

        return resultMap;
    }

    /**
     * 查询告警列表
     */
    @GetMapping("/alarmList")
    public AjaxResult getAlarmList(@Param("sort")Integer sort ){
        List<AlertLog> list = new LambdaQueryChainWrapper<>(alertLogMapper)
                .select(AlertLog::getAlertLogId,AlertLog::getCreateTime,AlertLog::getAlertName,AlertLog::getSerialNumber,AlertLog::getDeviceName)
                .list();
        if(sort != null){
            //对列表进行排序
            //升序
            if(sort==1){
                list.sort(Comparator.comparing(AlertLog::getCreateTime));
            }
            //降序
            else if(sort==2){
                list.sort(Comparator.comparing(AlertLog::getCreateTime).reversed());
            }
        }

        return AjaxResult.success(list);
    }


    /**
     * 研判等级评级策略方法
     * A级，3个以下报警；B级，3-10个报警；C级；10个以上报警
     */
    private String getSecurityLevel(Long alarmTotal) {
        if (alarmTotal <3) {
            return "A级";
        } else if (alarmTotal <= 10) {
            return "B级";
        } else {
            return "C级";
        }
    }

}
