<?php

namespace App\Http\Controllers;

use App\Device_Group;
use App\User as Users;
use App\Pages;
use GuzzleHttp\Client;
use http\Client\Curl\User;
use Illuminate\Http\Request;
use function MongoDB\BSON\toJSON;

class InfluxdbController extends Controller
{
    //
    public function alpr_select(){
        //+tz('Asia/Taipei')
        $client = new Client();
        $rep=$client ->request("GET",'http://'.env("InfluxDB_IP").'/query?q=select+*+from+'.env("InfluxDB_Alpr_TABLE").'+group+by+"Device_id"+order+by+ASC+&db='.env("InfluxDB_DB"));
        $jsondata=json_decode($rep->getBody()->__toString(),true);

        $datas=array();
//        $device_ids=array();
        foreach ($jsondata["results"][0]["series"] as $data){
            $device_id=$data["tags"]["Device_id"];
            $columns=$data["columns"];
            $values=$data["values"];
            $datas[$device_id]=$this->resultTojson($columns,$values,$device_id);
//            array_push($device_ids,$device_id);
        }
        $this->alpr_merge($datas);

        $data=$this->alpr_merge($datas,"國道187km");

        return $data;
    }
    public function alpr_merge($datas){
        //$DGs=Device_Group::where("Group_Name",$device_group)->get();
        $DGs=Device_Group::all();
        foreach ($DGs as $dg){
            $A=$dg['Point_A_Device'];
            $B=$dg['Point_B_Device'];
//            dd($datas[$A][0]);
        }
    }
    public function resultTojson($columns,$values,$page_name,$tags=null){
        //date_default_timezone_set("Asia/Taipei");
        $datas=array();
        if ($page_name)
            $pages=Pages :: all();
        for($i=0 ; $i<count($values) ; $i++){
            $temp=array();
            if ($tags !=null)
                $temp["Device_id"]=$tags;
            for ($j=0;$j<count($columns);$j++){
                $temp[$columns[$j]]=$values[$i][$j];
                if ($columns[$j]=='time'){
                    $unitime=strtotime(substr($values[$i][$j],0,strpos($values[$i][$j],"."))."Z");
                    $temp[$columns[$j]]=date("Y-m-d H i s",$unitime);
                }
                if ($page_name && $columns[$j]=='Operate_Page'){
                    $page_name=$pages->where("Route",$values[$i][$j])->first()["Page_Name"];
                    $temp[$columns[$j]]= $page_name == null ? $values[$i][$j] : $page_name;
                }
            }
            array_push($datas,$temp);
        }
        return $datas;
    }

    public function Log_select(Request $request){
        $client = new Client();
        $name=$request->name =='all' ? null : $request->name;
        $page=$request->page =='all' ? null : $request->page;
        $stime=$request->dateS == null ? date('Y-m-d') :$request->dateS;
        $stime=$stime." 00:00:00";
        $etime=$request->dateE;

        $pg="";
//        if ($page != null)
//        {
//            $page=Pages :: where('Page_Name',$page)->get();
//            $pg.='+AND+"Operate_Page"+=+\''.$page[0]["Route"].'\'';
//        }
        if ($page != null)
        {
            $pg.='+AND+"Operate_Page"+=+\''.$page.'\'';
        }

        $etime=$etime!=null ? '+AND+"time"+<=+\''.$etime." 23:59:59".'\'':"";
        $op=$name !=null ? '+AND+"Operator"+=+\''.$name.'\'':"";
        $query=sprintf('http://'.env("InfluxDB_IP").'/query?q=select+*+from+'.env("InfluxDB_Log_TABLE").'+where+"time"+>=+\''.$stime.'\'%s%s%s+order+by+DESC+tz(\'Asia/Taipei\')+&db='.env("InfluxDB_DB"),$etime,$op,$pg);


        $rep=$client ->request("GET",$query);
        $jsondata=json_decode($rep->getBody()->__toString(),true);
        if (count($jsondata["results"][0])>=2){
            //$measurement=$jsondata["results"][0]["series"][0]["name"];
            $columns=$jsondata["results"][0]["series"][0]["columns"];
            $values=$jsondata["results"][0]["series"][0]["values"];
            $datas=$this->resultTojson($columns,$values,true);
            return $datas;
        }
        else{
            return "查無結果";
        }
    }

    public function dashboard_index(){
        $client = new Client();
        $stime=date("Y-m-01 00:00:00");
        $etime=date("Y-m-t 23:59:59");

        $rep=$client ->request("GET",'http://'.env("InfluxDB_IP").'/query?q=select+*+from+'.env("InfluxDB_Log_TABLE").'+where+"time"+>=+\''.$stime.'\'+AND+"time"+<=+\''.$etime.'\'+order+by+DESC+tz(\'Asia/Taipei\')+&db='.env("InfluxDB_DB"));
        $jsondata=json_decode($rep->getBody()->__toString(),true);
        //$measurement=$jsondata["results"][0]["series"][0]["name"];
        $LogsArray=array();
        $LogsArray["帳號管理"]["新增帳號"]=array();
        $LogsArray["帳號管理"]["修改帳號"]=array();
        $LogsArray["帳號管理"]["刪除帳號"]=array();
        $LogsArray["帳號管理"]["查詢帳號"]=array();
        $LogsArray["群組管理"]["新增群組"]=array();
        $LogsArray["群組管理"]["修改群組"]=array();
        $LogsArray["群組管理"]["刪除群組"]=array();
        $LogsArray["車輛查詢"]["車輛查詢"]=array();
        $LogsArray["車輛查詢"]["修改車輛"]=array();
        $LogsArray["車輛查詢"]["刪除車輛"]=array();
        $LogsArray["設備管理"]["新增設備"]=array();
        $LogsArray["設備管理"]["修改設備"]=array();
        $LogsArray["設備管理"]["刪除設備"]=array();
        $LogsArray["設備管理"]["查詢設備"]=array();
        $LogsArray["設備群組"]["新增設備群組"]=array();
        $LogsArray["設備群組"]["修改設備群組"]=array();
        $LogsArray["設備群組"]["刪除設備群組"]=array();
        $LogsArray["設備群組"]["查詢設備群組"]=array();
//        $LogsArray["日誌"]["查詢日誌"]=array();
        $LogsArray["登錄"]=array();


        if (count($jsondata["results"][0])>=2) {
            $columns=$jsondata["results"][0]["series"][0]["columns"];
            $values=$jsondata["results"][0]["series"][0]["values"];
            $Logs=$this->resultTojson($columns,$values,false);
            foreach ($Logs as $log) {
                $page = $log["Operate_Page"];
                switch ($page) {
                    case "admin/account/create":
                        array_push($LogsArray["帳號管理"]["新增帳號"], $log);
                        break;
                    case "admin/account/update":
                        array_push($LogsArray["帳號管理"]["修改帳號"], $log);
                        break;
                    case "admin/account/delete":
                        array_push($LogsArray["帳號管理"]["刪除帳號"], $log);
                        break;
                    case "admin/account/select/where":
                        array_push($LogsArray["帳號管理"]["查詢帳號"], $log);
                        break;
                    case "admin/account/group/create":
                        array_push($LogsArray["群組管理"]["新增群組"], $log);
                        break;
                    case "admin/account/group/update":
                        array_push($LogsArray["群組管理"]["修改群組"], $log);
                        break;
                    case "admin/account/group/delete":
                        array_push($LogsArray["群組管理"]["刪除群組"], $log);
                        break;
                    case "plates/select":
                        array_push($LogsArray["車輛查詢"]["車輛查詢"], $log);
                        break;
                    case "plates/update":
                        array_push($LogsArray["車輛查詢"]["修改車輛"], $log);
                        break;
                    case "plates/delete":
                        array_push($LogsArray["車輛查詢"]["刪除車輛"], $log);
                        break;
                    case "device/create":
                        array_push($LogsArray["設備管理"]["新增設備"], $log);
                        break;
                    case "device/update":
                        array_push($LogsArray["設備管理"]["修改設備"], $log);
                        break;
                    case "device/delete":
                        array_push($LogsArray["設備管理"]["刪除設備"], $log);
                        break;
                    case "device/select":
                        array_push($LogsArray["設備管理"]["查詢設備"], $log);
                        break;
                    case "device/group/create":
                        array_push($LogsArray["設備群組"]["新增設備群組"], $log);
                        break;
                    case "device/group/update":
                        array_push($LogsArray["設備群組"]["修改設備群組"], $log);
                        break;
                    case "device/group/delete":
                        array_push($LogsArray["設備群組"]["刪除設備群組"], $log);
                        break;
                    case "device/group/select":
                        array_push($LogsArray["設備群組"]["查詢設備群組"], $log);
                        break;
//                    case "dashboard/select":
//                        array_push($LogsArray["日誌"]["查詢日誌"], $log);
//                        break;
                    case "login":
                        array_push($LogsArray["登錄"], $log);
                        break;
//                case route("acc_C"):
//                    $LogsArray["新增帳號"]=$log;
//                case route("acc_C"):
//                    $LogsArray["新增帳號"]=$log;
//                case route("acc_C"):
//                    $LogsArray["新增帳號"]=$log;
                }
            }
        }
//        dd($LogsArray);
//        $LogsArray=json_encode($LogsArray,JSON_UNESCAPED_UNICODE);
        $user=Users :: all();
        $page=Pages :: all();
        return view('dashboard')->with(["Logs"=>$LogsArray,"Users"=>$user,"Pages"=>$page]);
    }
}
