<?php

namespace Home\Controller;

use Think\Controller;


class IntegratedAlarmController extends ComController
{
    //站点列表数据查询
    public function getSiteList()
    {
        if (!isset($_SESSION['phone'])) {
            $res['msg'] = '操作失败';
            $res['flag'] = false;
            echo json_encode($res);
            exit();
        }

        if (empty($_SESSION['permissionLabel'])) {
            $R['msg'] = '操作失败，该用户无权限请联系管理员！';
            $R['flag'] = false;
            echo json_encode($R);
            exit();
        }

        $Data = I('');
        if (!empty($Data['currentPage']) && !empty($Data['size'])) {
            $start_number = ($Data['currentPage'] - 1) * $Data['size'];
            $limit = " limit " . $start_number . "," . $Data['size'];
        }
        $R = M()->query("select count(*) as sl from personnel where personnel_phone='" . $_SESSION['phone'] . "'");
        $siteIdList = M()->query("select site_id as siteId from personnel where personnel_phone='" . $_SESSION['phone'] . "' " );
        $str = "";
        foreach ($siteIdList as $key => $value) {
            $str .= "'" . $siteIdList[$key]['siteId'] . "',";
        }
        if (!empty($Data['siteName'])) {
            $where = " and f.site_name like '%" . $Data['siteName'] . "%'";
        }

        $where1 = "";
        if ($_SESSION['permissionLabel'] == 3) {
            $where1 .= " and a.alarm_name in('PhaseLoss','OverV','UnderV','BusOutage') ";
        }

        if ($_SESSION['permissionLabel']==4){
//            $where1 .= " and b.device_type in(3,4) ";
        }elseif($_SESSION['permissionLabel']==1){
//            $where1 .= " and b.device_type in(1,3,4) ";
        }else{
            $where1 .= " and b.device_type in(1,2) ";
        }

        $siteId = substr($str, 0, strlen($str) - 1);
//        print_r("SELECT f.id,f.siteName,IFNULL(count,0) AS siteAlarmCount FROM (SELECT c.id,c.siteName,COUNT(a.id) AS count FROM wj_power_monitoring_alarm as a JOIN wj_device as b on a.deviceName=b.deviceCode JOIN wj_power_monitoring_site AS c ON b.siteId=c.id where a.clzt=0 GROUP BY siteId) as e RIGHT JOIN wj_power_monitoring_site AS f ON e.id=f.id where f.id in (".$siteId.") ".$where);
        $siteList = M()->query("SELECT f.id,f.site_name as siteName,IFNULL(count,0) AS siteAlarmCount FROM (SELECT c.id,c.site_name as siteName
                               ,COUNT(a.id) AS count FROM alarm_power as a JOIN device as b on a.device_code=b.device_code JOIN site AS c 
                                ON b.site_id=c.id where c.enable=1 and  a.handling_status=0 " . $where1 . " GROUP BY b.site_id) as e RIGHT JOIN site AS f ON e.id=f.id 
                                where f.enable=1 and f.id in (" . $siteId . ") " . $where." ".$limit );
        $videoList = query_187_jdxf("select b.push_param2 AS siteId,count(a.id) AS siteAlarmCount from sp_video2017 as a join sp_owner as b 
                                    on a.device_code=b.owner_code where b.company='11111' and clzt=0 and push_param2 in(" . $siteId . ") group by b.push_param2");
        foreach ($siteList as $key => $value) {
            $siteList[$key]['companyCode'] = $siteList[$key]['id'];
            $siteList[$key]['siteAlarmCount'] = (int)$siteList[$key]['siteAlarmCount'];
            foreach ($videoList as $key1 => $value1) {
                if ($videoList[$key1]['siteId'] == $siteList[$key]['id']) {
                    $siteList[$key]['siteAlarmCount'] = (int)$siteList[$key]['siteAlarmCount'] + (int)$videoList[$key1]['siteAlarmCount'];
                }
            }
        }

        $res['msg'] = '操作成功';
        $res['flag'] = true;
        $res['data'] = $siteList;
        $res['total'] = $R[0]['sl'];
        $res['currentPage'] = $Data['currentPage'];
        $res['size'] = $Data['size'];
        echo json_encode($res);
    }


    //站点各类型告警数量统计
    public function getSiteType()
    {
        $Data = I('');
        if (empty($_SESSION['permissionLabel'])) {
            $R['msg'] = '操作失败，该用户无权限请联系管理员！';
            $R['flag'] = false;
            echo json_encode($R);
            exit();
        }

        if (empty($Data['companyCode'])) {
            $res['msg'] = '操作失败，缺少参数companyCode';
            $res['flag'] = false;
            $res['data'] = null;
            echo json_encode($res);
            exit();
        }
        $where = "";
        if ($_SESSION['permissionLabel'] == 3) {
            $where .= " and a.alarm_name in('PhaseLoss','OverV','UnderV','BusOutage') ";
        }

        if ($_SESSION['permissionLabel'] == 4) {
//            $where .= " and b.device_type in(3,4) ";
        }elseif($_SESSION['permissionLabel']==1){
//            $where .= " and b.device_type in(1,3,4) ";
        }else{
            $where .= " and b.device_type =1 ";
        }
        //站点下电力监测报警总数
        $siteStatisticsCount = M()->query("select count(*) as powerMonitoringCount from alarm_power as a join device as b on a.device_code=b.device_code 
                                            where a.handling_status=0 and b.site_id=" . $Data['companyCode'] . $where);
        $data[0]['powerMonitoringCount'] = (int)$siteStatisticsCount[0]['powerMonitoringCount'];

        //站点下视频监测报警总数
        $siteVideoList = M()->query("select device_code from device where device_type=2 and site_id=" . $Data['companyCode']);
        if (!empty($siteVideoList)) {
            $str = "";
            foreach ($siteVideoList as $key => $value) {
                $str .= "'" . $siteVideoList[$key]['device_code'] . "',";
            }

            $deviceCode = substr($str, 0, strlen($str) - 1);
            $siteVideoCount = query_187_jdxf("select count(*) as videoMonitoringCount from sp_video2017 where clzt=0 and device_code in (" . $deviceCode . ")");
            if (empty($siteVideoCount[0]['videoMonitoringCount'])) {
                $siteVideoCount[0]['videoMonitoringCount'] = 0;
            }
        } else {
            $siteVideoCount[0]['videoMonitoringCount'] = 0;
        }

        $data[0]['videoMonitoringCount'] = (int)$siteVideoCount[0]['videoMonitoringCount'];
        $res['msg'] = '操作成功';
        $res['flag'] = true;
        $res['companyCode'] = $Data['companyCode'];
        $res['data'] = $data;
        echo json_encode($res);
    }

    //  报警已处理未处理列表及总数查询
    public function getElectricAlarmUntreated()
    {
        $Data = I('');

        if (empty($_SESSION['permissionLabel'])) {
            $R['msg'] = '操作失败，该用户无权限请联系管理员！';
            $R['flag'] = false;
            echo json_encode($R);
            exit();
        }

        if (empty($Data['companyCode']) || empty($Data['type']) || !isset($Data['processingStatus'])) {
            $res['msg'] = '操作失败，缺少参数';
            $res['flag'] = false;
            $res['data'] = null;
            echo json_encode($res);
            exit();
        }

        $where = "";
        if ($_SESSION['permissionLabel'] == 3) {
            $where .= " and a.alarm_name in('PhaseLoss','OverV','UnderV','BusOutage') ";
        }

        if ($_SESSION['permissionLabel'] == 4) {
//            $where .= " and b.device_type in(3,4) ";
        }elseif($_SESSION['permissionLabel']==1){
//            $where .= " and b.device_type in(1,3,4) ";
        }else{
            $where .= " and b.device_type =1 ";
        }


        if (!empty($Data['currentPage']) && !empty($Data['size'])) {
            $start_number = ($Data['currentPage'] - 1) * $Data['size'];
            $limit = " limit " . $start_number . "," . $Data['size'];
        }

        if ($Data['type'] == 1) {
            $R = M()->query("select count(*) as sl from alarm_power as a 
                                join device as b on a.device_code=b.device_code join wc_meas_type as c on a.meas_name=c.meas_name 
                                where b.site_id=" . $Data['companyCode'] . " and a.handling_status in (
                                " . $Data['processingStatus'] . ") " . $where . " ORDER BY a.soe_time desc");

            $data = M()->query("select a.id,c.meas_desc as measName,a.digital_value as digitalValue,a.soe_time as soeTime,handling_status from alarm_power as a 
                                join device as b on a.device_code=b.device_code join wc_meas_type as c on a.meas_name=c.meas_name 
                                where b.site_id=" . $Data['companyCode'] . " and a.handling_status in (
                                " . $Data['processingStatus'] . ") " . $where . " ORDER BY a.soe_time desc " . $limit);
            if (!empty($R)) {
                $dataCount = $R[0]['sl'];
            } else {
                $dataCount = 0;
            }
        } elseif ($Data['type'] == 2) {
            $R = query_187_jdxf("select count(a.id) as sl from sp_video2017 as a 
                                        join sp_owner as b on a.device_code=b.owner_code where b.dwtype=16 and a.clzt = '" . $Data['processingStatus'] . "' 
                                        and b.push_param2='" . $Data['companyCode'] . "'");

            $data = query_187_jdxf("select a.id,b.owner_name as measName,a.data4 as digitalValue,a.time as soeTime,a.clzt as  handling_status from sp_video2017 as a 
                                        join sp_owner as b on a.device_code=b.owner_code where b.dwtype=16 and a.clzt = '" . $Data['processingStatus'] . "' 
                                        and b.push_param2='" . $Data['companyCode'] . "' ORDER BY a.id desc" . $limit);
            $dataCount = $R[0]['sl'];

        }


        $res['msg'] = '操作成功';
        $res['flag'] = true;
        $res['companyCode'] = $Data['companyCode'];
        $res['alarmUntreatedCount'] = $dataCount;
        $res['total'] = $dataCount;
        $res['currentPage'] = $Data['currentPage'];
        $res['size'] = $Data['size'];
        $res['data'] = $data;
        echo json_encode($res);

    }

    //电力监测报警已处理未处理详情数据查询
    public function getPowerAlarmDetails()
    {
        $Data = I('');
        if (!isset($Data['companyCode']) || !isset($Data['alarmId'])) {
            $res['msg'] = '操作失败，缺少参数';
            $res['flag'] = false;
            $res['data'] = null;
            echo json_encode($res);
            exit();
        }
        $data = M()->query("SELECT s.route_name,c.site_id as siteId,a.soe_time as time,a.meas_name,a.id,d.site_name as siteName,
                            c.device_name as deviceName,b.meas_desc as measValue,a.digital_value as digitalValue,c.device_code as deviceCode,
                            d.site_address as address,d.user_name as userName,d.phone,a.handler AS `handler`,a.handling_time AS handlerTime,
                            a.handling_content as handlerContent,d.longitude,d.latitude,o.platform_area_name,a.handling_status,d.spare_user_name,
                            d.spare_phone,x.account_number  
                            FROM alarm_power AS a 
                            JOIN wc_meas_type AS b ON a.meas_name=b.meas_name 
                            JOIN device AS c ON  a.device_code=c.device_code 
                            left JOIN site AS d ON c.site_id=d.id 
                            join route as s on d.route_id=s.id 
                            left join platform_area as o on d.station_area_id=o.id 
                            left join site_information as x on d.id=x.site_id WHERE a.id=" . $Data['alarmId']);
        if (!empty($data) && $data[0]['handling_status'] != 0) {
//            $time1 = floor((strtotime($data[0]['handlerTime'])-strtotime($data[0]['time']))/60);
            $time2 = strtotime($data[0]['handlerTime']) - strtotime($data[0]['time']);
            if ($time2 > 0) {
                $arr = $this->secondsToTime($time2);
                $time3 = '';
                if ($arr['d'] > 0) {
                    $time3 .= $arr['d'] . '天';
                }
                if ($arr['h'] > 0) {
                    $time3 .= $arr['h'] . '小时';
                }
                if ($arr['m'] > 0) {
                    $time3 .= $arr['m'] . '分钟';
                }
                if ($arr['s'] > 0) {
                    $time3 .= $arr['s'] . '秒';
                }
                $data[0]['duration'] = $time3;
            } else {
                $data[0]['duration'] = '0秒';
            }
        }

        $res['msg'] = '操作成功';
        $res['flag'] = true;
        $res['companyCode'] = $Data['companyCode'];
        $res['data'] = $data;
        echo json_encode($res);
    }


    public function secondsToTime($inputSeconds)
    {

        $secondsInAMinute = 60;
        $secondsInAnHour = 60 * $secondsInAMinute;
        $secondsInADay = 24 * $secondsInAnHour;

        // extract days
        $days = floor($inputSeconds / $secondsInADay);

        // extract hours
        $hourSeconds = $inputSeconds % $secondsInADay;
        $hours = floor($hourSeconds / $secondsInAnHour);

        // extract minutes
        $minuteSeconds = $hourSeconds % $secondsInAnHour;
        $minutes = floor($minuteSeconds / $secondsInAMinute);

        // extract the remaining seconds
        $remainingSeconds = $minuteSeconds % $secondsInAMinute;
        $seconds = ceil($remainingSeconds);

        // return the final array
        $obj = array(
            'd' => (int)$days,
            'h' => (int)$hours,
            'm' => (int)$minutes,
            's' => (int)$seconds,
        );
        return $obj;
    }


    //视频监测报警已处理未处理详情数据查询
    public function getVideoAlarmDetails()
    {
        $Data = I('');
        if (!isset($Data['companyCode']) || !isset($Data['alarmId'])) {
            $res['msg'] = '操作失败，缺少参数';
            $res['flag'] = false;
            $res['data'] = null;
            echo json_encode($res);
            exit();
        }
        $data = query_187_jdxf("SELECT a.time,a.id,b.owner_name as deviceName,b.push_param2,a.data4 AS alarmInformation,a.data2 as alarmPicture
                                ,a.device_code AS deviceCode,a.clwb AS alarmStatus,a.clr AS `handler`,a.clsj AS handlerTime,a.clnr AS handlerContent,a.clzt as handling_status 
                                    FROM sp_video2017 as a JOIN sp_owner AS b ON a.device_code=b.owner_code WHERE a.id=" . $Data['alarmId']);
        if (empty($data)) {
            $res['msg'] = '操作失败，缺少参数ID';
            $res['flag'] = false;
            $res['data'] = null;
            echo json_encode($res);
            exit();
        }
        $data[0]['alarmPicture'] = str_replace("http://47.103.74.123/", "https://iot.usky.cn/", $data[0]['alarmPicture']);;
        $deviceAddress = M()->query("select site_address as address from site where id=" . $data[0]['push_param2']);
        if (empty($deviceAddress)) {
            $res['msg'] = '操作失败，缺少参数点位ID';
            $res['flag'] = false;
            $res['data'] = null;
            echo json_encode($res);
            exit();
        }
        $data[0]['deviceAddress'] = $deviceAddress[0]['address'];

        $res['msg'] = '操作成功';
        $res['flag'] = true;
        $res['companyCode'] = $Data['companyCode'];
        $res['data'] = $data;
        echo json_encode($res);
    }

    public function setAlarmHandle()
    {
        $Data = I('');
//        if (!isset($Data['batchProcessing']) || !isset($Data['clwb'])) {
//            $Data['batchProcessing'] = 0;
//            $Data['clwb'] = 1;
//        }

        if (!isset($Data['type']) || !isset($Data['deviceCode']) || !isset($Data['id']) || !isset($Data['companyCode'])) {
            $res['msg'] = '操作失败，缺少参数';
            $res['flag'] = false;
            $res['data'] = null;
            echo json_encode($res);
            exit();
        }


        $Map['id'] = $Data['id'];
        $data['clnr'] = $Data['handlerContent'];
        $data['clzt'] = 1;
        $data['clsj'] = date('Y-m-d h:i:s', time());;
        $data['cldh'] = $_SESSION['phone'];


        $data1['handling_content'] = $Data['handlerContent'];
        $data1['handling_status'] = 1;
        $data1['handling_time'] = date('Y-m-d h:i:s', time());;
        $data1['handler_phone'] = $_SESSION['phone'];

        if (!empty($_SESSION['phone'])) {
            $userName = M()->query("select personnel_name as userName from personnel where personnel_phone='" . $_SESSION['phone'] . "'");
            if (!empty($userName[0]['userName'])) {
                $data['clr'] = $userName[0]['userName'];
                $data1['handler'] = $userName[0]['userName'];
            } else {
                $data['clr'] = $_SESSION['phone'];
                $data1['handler'] = $_SESSION['phone'];
            }
        }

        switch ($Data['type']) {
            case '1':
//                print_r($data1);
//                print_r($Map);
                $res = M('alarm_power')->where($Map)->save($data1);
                break;
            case '2':
                if ($Data['batchProcessing'] == 1) {
                    $res = insert_187_jdxf("UPDATE sp_video2017 set clr='" . $data['clr'] . "',cldh='" . $data['cldh'] . "',clzt=1,clsj=
                    '" . $data['clsj'] . "',clwb='" . $Data['alarmStatus'] . "',clnr='" . $data['clnr'] . "' where device_code='" . $Data['deviceCode'] . "'");
                } else {
                    $res = insert_187_jdxf("UPDATE sp_video2017 set clr='" . $data['clr'] . "',cldh='" . $data['cldh'] . "',clzt=1,clsj=
                    '" . $data['clsj'] . "',clwb='" . $Data['alarmStatus'] . "',clnr='" . $data['clnr'] . "' where id=" . $Data['id']);
                }
                break;
            default:
                exit();
                break;
        }

        if ($res) {
            $res1['msg'] = '操作成功';
            $res1['flag'] = true;
            $res1['companyCode'] = $Data['companyCode'];
            echo json_encode($res1);
        } else {
            $res1['msg'] = '操作失败';
            $res1['flag'] = false;
            $res1['companyCode'] = $Data['companyCode'];
            echo json_encode($res1);
        }
    }


    //电力监测批量处理
    public function setBatchProcessing()
    {
        $Data = I('');
        if (!isset($Data['id']) || !isset($Data['companyCode'])) {
            $res['msg'] = '操作失败，缺少参数';
            $res['flag'] = false;
            $res['data'] = null;
            echo json_encode($res);
            exit();
        }
        $pieces = explode(",", $Data['id']);
        $Map['id'] = array("in", $pieces);
        $data1['handling_content'] = "快速处理";
        $data1['handling_status'] = 1;
        $data1['handling_time'] = date('Y-m-d h:i:s', time());;
        $data1['handler_phone'] = "快速处理";
        $data1['handler'] = "快速处理";
//        print_r($Map);
        $res = M('alarm_power')->where($Map)->save($data1);
        if ($res) {
            $res1['msg'] = '操作成功';
            $res1['flag'] = true;
            $res1['companyCode'] = $Data['companyCode'];
            echo json_encode($res1);
        } else {
            $res1['msg'] = '操作失败';
            $res1['flag'] = false;
            $res1['companyCode'] = $Data['companyCode'];
            echo json_encode($res1);
        }
    }
}