<?php

namespace App\Http\Controllers;

use App\E3SCamera;
use Illuminate\Database\PostgresConnection;
use Illuminate\Http\Request;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class UserController extends Controller
{
    //user登入頁面
    public function index(Request $request)
    {
        $request->session()->all();
        $username = $request->session()->get('Tusername');
        $userpwd = $request->session()->get('Tuserpwd');
        $auth = $request->session()->get('auth');
        $user=$username." ".$userpwd." ".$auth;
        return view("User_login",["title"=>"使用者登入","uername"=>$username,"userpwd"=>$userpwd,"auth"=>$auth]);
    }
    //user登入後驗證
    public function user_login(Request $request){
        if($request->Auto_live=="right")
        {
            $request->session()->put('Tusername',$_POST["user_name"]);
            $request->session()->put('Tuserpwd',$_POST["user_pwd"]);
        }
        $request->session()->put('AI_lock','default');
        $_SESSION['user_name']=$_POST["user_name"];
        $_SESSION['user_pwd']=$_POST["user_pwd"];
        $username = $request->session()->get('user_name',$_POST["user_name"]);
        $userpwd = $request->session()->get('user_pwd',$_POST["user_pwd"]);
        if($username!=null || $userpwd!=null)
        {

            $client = new \GuzzleHttp\Client();
            $res=$client->request('POST', sprintf("http://%s:%s/user/auth", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")),[
                'form_params'=>[
                    "username"=>$username,
                    "password"=>$userpwd
                ]
            ]);
            $jsondata = json_decode($res->getBody()->__toString(), true);
            if(isset($jsondata["Data"]) ){
                $request->session()->put('lostring',$jsondata["Data"]);
                if ($request->Auto_live=="right") {
                    $request->session()->put('auth','1');
                }else{
                    $value1 = $request->session()->pull('auth');
                }
                $error_msg="登入成功".$_SESSION["user_name"];
            return redirect('Device')->with(["error_msg"=>$error_msg]);
            }else{
                $request->session()->put('lostring',$jsondata["Data"]);
                $error_msg="登入失敗，請重新輸入帳號密碼".' '.$request->Auto_live;
                return $this->index($request)->with(["error_msg" => $error_msg]);
            }
        }else{
            $error_msg="請輸入帳號密碼";
            return $this->index($request)->with(["title"=>"使用者登入","error_msg" => $error_msg]);
        }
    }
    //user登出
    public function user_logout(Request $request){
        $value = $request->session()->pull('lostring');
        $value1 = $request->session()->pull('auth');
        //$request->session()->flush();
        return redirect('/');
    }
    //user首頁
    public function index_insert(Request $request){
        $request->session()->all();
        $devices = array();
        $groups = array();
        $camera_list = array("Enabled"=>array());
        // 取得 Device 資料
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/device/select/all",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"GET");
        $jsondata = json_decode($res->getBody()->__toString(),true);
        foreach ($jsondata["Data"] as $device) {
            if ($device["Location"] == "") {
                $name = $device["ID"];
            }
            else {
                $name = $device["Location"];
            }
            array_push($camera_list["Enabled"],array(
                "id"=>$device["ID"],
                "name"=>$name,
            ));
        }
        array_push($groups, array("group"=> "Enabled"));
        // 取得所有使用者資料
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/user/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")),"POST");
       $jsondata=json_decode($res->getBody()->__toString(),true);
      $rowdata=array();
       foreach ($jsondata["Data"] as $user) {
           switch ($user["role"]){
               case 3:
               $user_role="經理";
               break;
               case 5:
               $user_role="使用者";
               break;
               default:
                   break;
           }
           array_push($rowdata,array(
               "id"=>$user["id"],
               "name"=>$user["name"],
               "role"=>$user_role,
               "username"=>$user["username"],
               "modify"=>sprintf("<button class=\"btn btn-outline-dark\" title=\"修改人員資料\" data-toggle=\"modal\" data-target=\"#ModifyMemberModalCenter\" onclick=\"person_modify(this)\">修改</button>"),
           ));
       }
        /*if($request->session()->has('Tusername')){
             $error_msg="有第一位登入者".$request->session()->get('lostring')."  "."第二個測試位置".$request->session()->get('Tusername');//測試登入者是否可以存進去session
        }else{"error_msg"=>$error_msg,
         $error_msg="沒有登入者";
        }*/
        $usermsg=$request->session()->get('Tusername');
//        foreach($rowdata as $user_auth)
//        {
//            if($user_auth["name"]==$usermsg)
//                $auth=$user_auth["role"];
//        }
//        if($auth!="經理")
//        {
//            $msg="身份不對";
//            return redirect()->route('AI')->with(["error_msg"=>$msg]);
//        }


        return view("User",["title"=>"使用者管理","groups"=>$groups,"camera_list"=>$camera_list,"rowdata"=>$rowdata,"msg"=>$usermsg]);
        }

    //新增使用者
    public function insert_user(Request $request)
        {
            $request->session()->all();
            $devices = array();
            $groups = array();
            $camera_list = array("Enabled" => array());
            // 取得 Device 資料
            [$ret, $res] = $this->request_server(sprintf("http://%s:%s/device/select/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "GET");
            $jsondata = json_decode($res->getBody()->__toString(), true);
            foreach ($jsondata["Data"] as $device) {
                if ($device["Location"] == "") {
                    $name = $device["ID"];
                } else {
                    $name = $device["Location"];
                }
                array_push($camera_list["Enabled"], array(
                    "id" => $device["ID"],
                    "name" => $name,
                ));
            }
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/user/insert", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
            "multipart",
            [
                [
                    'name' => "id",
                    "contents" => $request->user_id
                ],
                [
                    'name' => "name",
                    "contents" => $request->user_name
                ],
                [
                    'name' => "role",
                    "contents" => $request->user_role
                ],
                [
                    'name'=>"username",
                    "contents"=>$request->user_username
                ],
                [
                  'name'=>"password",
                  "contents"=>$request->user_password
                ],
                ]);
        $jsondata = json_decode($res->getBody()->__toString(), true);
        switch ($jsondata["Code"]) {
            case 1:
                // 成功
                $error_msg = "新增成功";
                break;
            default:
                return abort("500", "伺服器無法回應");
                break;
        }
        return  $this->index_insert($request)->with(["error_msg" => $error_msg]);
    }
    //刪除使用者
    public function delete_user(Request $request){
             $request->session()->all();

             if($request->selectedId!=null) {
                 $client = new \GuzzleHttp\Client();
                 $error_ids=array();
                 $ids=explode(",",$request->selectedId);
                 foreach ($ids as $id){
                     $res=$client->request('POST',sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT"))."/user/delete",[
                         'form_params'=>[
                             "id"=>$id
                         ]
                     ]);
                     $jsondata=json_decode($res->getBody()->__toString(),true);
                     if($res->getStatusCode()!=200){
                         array_push($error_ids,$id);
                     }
                 }
                 if (count($error_ids)==0){
                     $msg="刪除成功";
                 }else{
                     $msg=$error_ids[0];
                     for ($i=1;$i<count($error_ids);$i++){
                         $msg=$msg.",".$error_ids[$i];
                     }
                     $msg=$msg."刪除失敗";
                 }
                 return  $this->index_insert($request)->with(["error_msg" => $msg]);
             }else{
                 $msg="未選擇刪除人員";
                 return  $this->index_insert($request)->with(["error_msg" => $msg]);
             }
         }
    //修改使用者
    public function post_modifyuser(Request $request){
        $request->session()->all();
        //dd($request->all());
        $groups = array();
        $camera_list = array("Enabled"=>array());
        // 取得 Device 資料
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/device/select/all", env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"GET");
        $jsondata = json_decode($res->getBody()->__toString(),true);
        foreach ($jsondata["Data"] as $device) {
            if ($device["Location"] == "") {
                $name = $device["ID"];
            }
            else {
                $name = $device["Location"];
            }
            array_push($camera_list["Enabled"],array(
                "id"=>$device["ID"],
                "name"=>$name,
            ));
        }
        array_push($groups, array("group"=> "Enabled"));
        // dd($request->all());
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/user/update", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")),"POST",
            "multipart",
            [
                [
                    'name'=>"id",
                    "contents"=>$request->modify_user_id
                ],
                [
                    'name'=>"name",
                    "contents"=>$request->modify_user_name
                ],
                [
                    'name'=>"role",
                    "contents"=>$request->modify_user_role
                ],
                [
                    'name'     => 'username',
                    'contents' =>$request->modify_username
                ],
                [
                    'name'     => 'password',
                    'contents' => $request->modify_password

                ],
            ]);
        return $this->index_insert($request);
    }

    //搜尋使用者
    public function search_user(Request $request){
        $request->session()->all();
        $devices = array();
        $groups = array();
        $camera_list = array("Enabled"=>array());
        // 取得 Device 資料
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/device/select/all",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"GET");
        $jsondata = json_decode($res->getBody()->__toString(),true);
        foreach ($jsondata["Data"] as $device) {
            if ($device["Location"] == "") {
                $name = $device["ID"];
            }
            else {
                $name = $device["Location"];
            }
            array_push($camera_list["Enabled"],array(
                "id"=>$device["ID"],
                "name"=>$name,
            ));
        }
        array_push($groups, array("group"=> "Enabled"));
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/user/all",env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")),"POST");
        $jsondata=json_decode($res->getBody()->__toString(),true);
        $rowdata=array();
        foreach ($jsondata["Data"] as $user) {
            switch ($user["role"]){
                case 3:
                    $user_role="經理";
                    break;
                case 5:
                    $user_role="使用者";
                    break;
                default:
                    break;
            }
            if (!$request->search_text ==null){
                switch ($request->search_type){
                    // ID
                    case 1:
                        if(count(explode($request->search_text,$user["username"]))<2){
                            // no match
                            continue 2;
                        }
                        break;
                    // 姓名
                    case 2:
                        if(count(explode($request->search_text,$user_role))<2){
                            // no match
                            continue 2;
                        }
                        break;
                    // 類別
                    case 3:
                        if(count(explode($request->search_text,$user["Name"]))<2){
                            // no match
                            continue 2;
                        }
                        break;
                    // 未選擇
                    default:
                        break;
                }
            }
            array_push($rowdata,array(
                "id"=>$user["id"],
                "name"=>$user["name"],
                "role"=>$user_role,
                "username"=>$user["username"],
                "modify"=>sprintf("<button class=\"btn btn-outline-dark\" title=\"修改人員資料\" data-toggle=\"modal\" data-target=\"#ModifyMemberModalCenter\" onclick=\"person_modify(this)\">修改</button>"),
            ));
        }
        $usermsg=$request->session()->get('Tusername');
        return view("User",["title"=>"使用者管理","groups"=>$groups,"camera_list"=>$camera_list,"rowdata"=>$rowdata,"msg"=>$usermsg]);
    }




    // 公用方法(別人寫的)
    // 取得所有設備清單 回傳 群組 設備名稱與id
    public function get_all_device(){
        $e3scamera=new E3SCamera;
        $groups=$e3scamera->distinct('group')->get('group');
        $rowdata=$e3scamera->select("id","group","name")->get();
        // 建立攝影機清單
        $camera_list=array();
        foreach ($rowdata as $data){
            if(array_key_exists($data->group,$camera_list)){
                array_push($camera_list[$data->group],array("name"=>$data->name,"id"=>$data->id));
            }else{
                $camera_list[$data->group]=array(array("name"=>$data->name,"id"=>$data->id));
            }
        }

        return [$groups,$camera_list];
    }
    // 狀態碼檢查
    private function check_status_code($status_code){
        switch ($status_code){
            case 200:
                return true;
                break;
            case 500:
                return abort("500","伺服器沒有回應");
            case 503:
                return abort("503","伺服器沒有回應");
            default:
                break;
        }
        return true;
    }
    private function request_server($url,$method,$data_format=null,$data=null){
        $status_code=404;
        $client=new \GuzzleHttp\Client();
        switch ($method){
            case "GET":
                try {
                    $res = $client->request('GET',$url);
                    $status_code=$res->getStatusCode();
                }catch (RequestException $e){
                    if (!$e->hasResponse()) {
                        // 伺服器沒有回應
                        $status_code=503;
                    }
                }
                break;
            case "POST":
                if ($data!=null and $data_format !=null){
                    if ($data_format =="form_params" or $data_format =="multipart"){
                        try {
                            $res=$client->request('POST',$url,[
                                $data_format=>$data
                            ]);
                            $status_code=$res->getStatusCode();
                        }catch (RequestException $e){
                            if (!$e->hasResponse()) {
                                // 伺服器沒有回應
                                $status_code=503;
                            }
                        }
                    }else{
                        $status_code=404;
                    }
                }else{
                    try {
                        $res=$client->request('POST',$url);
                        $status_code=$res->getStatusCode();
                    }catch (RequestException $e){
                        if (!$e->hasResponse()) {
                            // 伺服器沒有回應
                            $status_code=503;
                        }
                    }
                }
                break;
            default:
                break;
        }
        switch ($status_code){
            case 200:
                return [true,$res];
                break;
            case 404:
                return abort("404","查無此頁");
            case 500:
                return abort("500","內部伺服器錯誤");
            case 503:
                return abort("503","伺服器沒有回應");
            default:
                return abort("404","查無此頁");
                break;
        }
    }
}
