<?php

namespace app\common\logic;

use app\common\model\device\Device;
use Symfony\Component\HttpClient\HttpClient;

class RemoteRequestLogic extends BaseLogic
{
    // 获取监控数据
    public static function getMonitorData($deviceIds = [])
    {
        // 查询产品绑定的设备,根据对应的设备检测项查询监测数据
        $datas = [];

        // 空气湿度和温度
        $airDevice = Device::whereIn('id', $deviceIds)->where('monitor_item', 'ambient_temperature,ambient_humidity')->find();
        if (!empty($airDevice)) {
            $airMonitor = self::requestMqtt($airDevice);
            if (!empty($airMonitor)) {
                $datas['ambient_temperature'] = $airMonitor[1][1];
                $datas['ambient_humidity'] = $airMonitor[1][2];
            } else {
                $datas['ambient_temperature'] = 0;
                $datas['ambient_humidity'] = 0;
            }
        } else {
            $datas['ambient_temperature'] = 0;
            $datas['ambient_humidity'] = 0;
        }

        // 氮气 nitrogen
        $NDevice = Device::whereIn('id', $deviceIds)->where('monitor_item', 'nitrogen')->find();
        if (!empty($NDevice)) {
            $NMonitor = self::requestMqtt($NDevice);
            if (!empty($NMonitor)) {
                $datas['nitrogen'] = $NMonitor[1][2];
            }else {
                $datas['nitrogen'] = 0;
            }
        } else {
            $datas['nitrogen'] = 0;
        }

        // 防火 fireproof
        $fireproofDevice = Device::whereIn('id', $deviceIds)->where('monitor_item', 'fireproof')->find();
        if (!empty($fireproofDevice)) {
            $fireproofMonitor = self::requestMqtt($fireproofDevice);
            if (!empty($fireproofMonitor)) {
                $datas['fireproof'] = $fireproofMonitor[1][2];
            } else {
                $datas['fireproof'] = 0;
            }
        } else {
            $datas['fireproof'] = 0;
        }

        // 甲烷 methane
        $methaneDevice = Device::whereIn('id', $deviceIds)->where('monitor_item', 'methane')->find();
        if (!empty($methaneDevice)) {
            $methaneMonitor = self::requestMqtt($methaneDevice);
            if (!empty($methaneMonitor)) {
                $datas['methane'] = $methaneMonitor[1][2];
            } else {
                $datas['methane'] = 0;
            }

        } else {
            $datas['methane'] = 0;
        }

        // 噪音 noise
        $noiseDevice = Device::whereIn('id', $deviceIds)->where('monitor_item', 'noise')->find();
        if (!empty($noiseDevice)) {
            $noiseMonitor = self::requestMqtt($noiseDevice);
            if (!empty($noiseMonitor)) {
                $datas['noise'] = $noiseMonitor[1][2];
            } else {
                $datas['noise'] = 0;
            }
        } else {
            $datas['noise'] = 0;
        }
        return $datas;
    }

    public static function requestMqtt($device)
    {
        $response = HttpClient::create()->request('GET', env('PROJECT.MQTT_PROJECT_URL'). 'api/xumu/data/query', [
            'query' => [
                'deviceId' => $device['code']
            ]
        ]);
        $monitor = json_decode($response->getContent(), true);
        return $monitor['data']['values'];
    }


    public static function getAlarmData($deviceList = [])
    {
        $list = [];
        // 获取设备报警信息
        foreach ($deviceList as $device) {
            $device['alarm_value'] = ''; // 警告数据
            $device['alarm_time'] = ''; // 警告时间
            $device['alarm_resolution'] = ''; // 解决方案
            $device['alarm_reason'] = ''; // 警告原因
            // 视频设备没有编码
            if (empty($device['code'])) {
                continue;
            }
            $temp =  self::requestAlarmData($device);
            if (empty($temp['values'])) {
                $list[] = $device;
                continue;
            }

            foreach ($temp['values'][4] as $key => $value) {
                $device['alarm_value'] = $value;
                $device['alarm_time'] = date('Y-m-d H:i:s', $temp['timestamps'][$key]/1000);
                $device['alarm_reason'] = $temp['values'][0][$key];
                $device['alarm_resolution'] = $temp['values'][2][$key];
                $list[] = $device;
            }

        }
        return $list;
    }

    public static function requestAlarmData($device = [])
    {
        $response = HttpClient::create()->request('GET', env('PROJECT.MQTT_PROJECT_URL'). 'api/xumu/warning', [
            'query' => [
                'deviceId' => $device['code'],
                'limit' => 5,
                'offset' => 0
            ]
        ]);
        $monitor = json_decode($response->getContent(), true);
        return $monitor['data'];
    }

    public static function getAlarmCount($deviceList = [])
    {
        $totalAlarmCount = 0;
        $todayAlarmCount = 0;

        // 获取设备报警信息
        foreach ($deviceList as $deivce) {
            if (empty($deivce['code'])) {
                continue;
            }
            $row = self::requestAlarmCount($deivce);
            $totalAlarmCount += $row['totoal_warning_count'];
            $todayAlarmCount += $row['today_warning_count'];
        }
        return [$totalAlarmCount, $todayAlarmCount];
    }

    // 设备总告警数
    public static function requestAlarmCount($device = [])
    {
        $response = HttpClient::create()->request('GET', env('PROJECT.MQTT_PROJECT_URL'). 'api/xumu/warning/statistics', [
            'query' => [
                'deviceId' => $device['code']
            ]
        ]);
        $monitor = json_decode($response->getContent(), true);
        return $monitor['data'];
    }

    // 获取近一周的监控数据
    public static function getRangeMonitorData($deviceIds = [])
    {
        // 查询产品绑定的设备,根据对应的设备检测项查询监测数据
        $datas = [];

        // 空气温度 ambient_temperature
        $ambientTemperatureDevice = Device::whereIn('id', $deviceIds)->where('monitor_item', 'ambient_temperature,ambient_humidity')->find();
        $ambientTemperatureDevice['name'] = '温度监测';
        if (!empty($ambientTemperatureDevice)) {
            $rangeData =  self::requestRangeMonitorData($ambientTemperatureDevice);
            if (!empty($rangeData)) {
                $ambientTemperatureDevice['RangeMonitorData'] = $rangeData[0];
            } else {
                $ambientTemperatureDevice['RangeMonitorData'] = [0,0,0,0,0,0,0];
            }
        } else {
            $ambientTemperatureDevice['RangeMonitorData'] = [0,0,0,0,0,0,0];
        }

        // 空气湿度 ambient_humidity
        $ambientHumidityDevice = Device::whereIn('id', $deviceIds)->where('monitor_item', 'ambient_temperature,ambient_humidity')->find();
        $ambientHumidityDevice['name'] = '湿度监测';
        if (!empty($ambientHumidityDevice)) {
            $rangeData =  self::requestRangeMonitorData($ambientHumidityDevice);
            if (!empty($rangeData)) {
                $ambientHumidityDevice['RangeMonitorData'] = $rangeData[1];
            } else {
                $ambientHumidityDevice['RangeMonitorData'] = [0,0,0,0,0,0,0];
            }
        } else {
            $ambientHumidityDevice['RangeMonitorData'] = [0,0,0,0,0,0,0];
        }
        // 氮气 nitrogen
        $NDevice = Device::whereIn('id', $deviceIds)->where('monitor_item', 'nitrogen')->find();
        if (!empty($NDevice)) {
            $rangeData =  self::requestRangeMonitorData($NDevice);
            if (!empty($rangeData)) {
                $NDevice['RangeMonitorData'] = $rangeData[0];
            } else {
                $NDevice['RangeMonitorData'] = [0,0,0,0,0,0,0];
            }
        } else {
            $NDevice['RangeMonitorData'] = [0,0,0,0,0,0,0];
        }
        // 防火 fireproof
        $fireproofDevice = Device::whereIn('id', $deviceIds)->where('monitor_item', 'fireproof')->find();
        if (!empty($fireproofDevice)) {
            $rangeData =  self::requestRangeMonitorData($fireproofDevice);
            if (!empty($rangeData)) {
                $fireproofDevice['RangeMonitorData'] = $rangeData[0];
            } else {
                $fireproofDevice['RangeMonitorData'] = [0,0,0,0,0,0,0];
            }
        } else {
            $fireproofDevice['RangeMonitorData'] = [0,0,0,0,0,0,0];
        }

        // 甲烷 methane
        $methaneDevice = Device::whereIn('id', $deviceIds)->where('monitor_item', 'methane')->find();
        if (!empty($methaneDevice)) {
            $rangeData =  self::requestRangeMonitorData($methaneDevice);
            if (!empty($rangeData)) {
                $methaneDevice['RangeMonitorData'] = $rangeData[0];
            } else {
                $methaneDevice['RangeMonitorData'] = [0,0,0,0,0,0,0];;
            }
        } else {
            $methaneDevice['RangeMonitorData'] =[0,0,0,0,0,0,0];
        }

        // 噪音 noise
        $noiseDevice = Device::whereIn('id', $deviceIds)->where('monitor_item', 'noise')->find();
        if (!empty($noiseDevice)) {
            $rangeData =  self::requestRangeMonitorData($noiseDevice);
            if (!empty($rangeData)) {
                $noiseDevice['RangeMonitorData'] = $rangeData[0];
            } else {
                $noiseDevice['RangeMonitorData'] = [0,0,0,0,0,0,0];
            }
        } else {
            $noiseDevice['RangeMonitorData'] = [0,0,0,0,0,0,0];
        }
        array_push($datas, $ambientTemperatureDevice, $ambientHumidityDevice, $fireproofDevice, $methaneDevice, $noiseDevice, $NDevice);
        return $datas;
    }

    public static function requestRangeMonitorData($device)
    {
        $response = HttpClient::create()->request('GET', env('PROJECT.MQTT_PROJECT_URL'). '/api/xumu/normal/past_seven_days', [
            'query' => [
                'deviceId' => $device['code']
            ]
        ]);
        $monitor = json_decode($response->getContent(), true);
        return $monitor['data']['values'];
    }

    public static function requestAnimalTemperature($rfid='')
    {
        $response = HttpClient::create()->request('GET', env('PROJECT.MQTT_PROJECT_URL'). 'api/xumu/rfid/query', [
            'query' => [
                'rfid' => $rfid
            ]
        ]);
        $monitor = json_decode($response->getContent(), true);
        return $monitor['data'];
    }
}