<?php

namespace App\Http\Controllers;

use App\E3SCamera;
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 PersonGroupController extends Controller
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    //人員群組首頁
    public function Group_index(Request $request)
    {
        $request->session()->all();
        $msg = request()->session()->get('error_msg');
        $username=$request->session()->get('Tusername');    //帳號
        $role="";
        $department="";
        $level="";
        $user_id="";
        [$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);
        foreach ($jsondata["Data"] as $user) {
            if($user["username"]==$username)
            {
                $role=$user["role"];
                $department=$user["department"];
                $user_id=$user["id"];
            }
        }
        if($role=="7")
        {
            $level="4";
        }
        elseif ($role=="3")
        {
            $level="3";
        }
        elseif ($role=="6")
        {
            $level="2";
        }
        elseif($role=="5")
        {
            $level="1";
        }
        //取得權限
        $authority=array();
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/features/role/relation/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")),"POST");
        $jsondata=json_decode($res->getBody()->__toString(),true);
        if($jsondata["Data"] !=null)
        {
            foreach ($jsondata["Data"] as $role_authority) {
                if($role_authority["role_id"]==$role)
                {
                    array_push( $authority, array(
//                    "no" => $role_authority["no"],
                        "features_id" => $role_authority["features_id"],
                    ));
                }
            }
        }
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/features/user/relation/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")),"POST");
        $jsondata=json_decode($res->getBody()->__toString(),true);
        if($jsondata["Data"] !=null)
        {
            foreach ($jsondata["Data"] as $user_authority) {
                if($user_authority["user_id"]==$user_id)
                {
                    array_push( $authority, array(
//                    "no" => $role_authority["no"],
                        "features_id" => $user_authority["features_id"],
                    ));
                }
            }
        }


        // 取得人員資料
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/group/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
        $jsondata = json_decode($res->getBody()->__toString(), true);
        $rowdata = array();
        if($jsondata["Data"] != null) {
            foreach ($jsondata["Data"] as $personG) {
                array_push($rowdata, array(
                    'id' => $personG["ID"],
                    'name' => $personG["Name"],
                    "detail" => sprintf("<button class=\"btn btn-outline-dark\" data-toggle=\"modal\" data-target=\"#ModifyMemberModalCenter\" onclick=\"group_modify(this)\">修改</button>"),
                ));
            }
        }
        //$persontest=implode("",$persondata);
        //$personGer=array();
        //$personGer=explode(',',"$persondata");
        //$data =array('name' => 'ray','age' => 25);
        if($msg!=null)
            return view("Person_Search_Group", ["title" => "人員群組", "rowdata" => $rowdata,"level"=>$level,"error_msg"=>$msg,'authority'=>$authority]);
        else
            return view("Person_Search_Group", ["title" => "人員群組", "rowdata" => $rowdata,"level"=>$level,'authority'=>$authority]);
    }

    //新增人員群組
    public function insert_Group(Request $request)
    {

        $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);
        if($jsondata["Data"] !=null)
        {
            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,
                ));
            }
        }

        $group = $request->group_text;
        $stuat = 1;
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/group/all",env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
        $jsondata = json_decode($res->getBody()->__toString(), true);
        $search_type = 2;
        if($jsondata["Data"] != null){
            foreach ($jsondata["Data"] as $personG) {
            if ($group != null) {
                switch ($search_type) {
                    case 2:
                        if (count(explode($group, $personG["Name"])) < 2) {
                            continue 2;
                        }
                        break;
                    default:
                        break;
                }
            }
            $stuat = 2;
        }
        }
        if ($group != null) {
            if ($stuat != 2) {
                [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/group/insert", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
                    "multipart",
                    [
                        [
                            'name' => "name",
                            "contents" => $group
                        ],
                    ]);
                $error_msg = "已新增成功";
            } else {
                $error_msg = "已有相同的名字";
            }
        } else {
            $error_msg = "請填寫群組名稱，未新增成功";
        }
        //dd($error_msg);
        return redirect()->route('Group_index')->with(["error_msg" => $error_msg]);
        //return $this->Group_index()->with(["error_msg" => $error_msg]);
    }

    //搜尋人員群組
    public function search_Group(Request $request)
    {

        $request->session()->all();
        $username=$request->session()->get('Tusername');    //帳號
        $role="";
        $department="";
        $level="";
        $user_id="";
        [$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);
        foreach ($jsondata["Data"] as $user) {
            if($user["username"]==$username)
            {
                $role=$user["role"];
                $department=$user["department"];
                $user_id=$user["id"];
            }
        }
        if($role=="7")
        {
            $level="4";
        }
        elseif ($role=="3")
        {
            $level="3";
        }
        elseif ($role=="6")
        {
            $level="2";
        }
        elseif($role=="5")
        {
            $level="1";
        }
        //取得權限
        $authority=array();
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/features/role/relation/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")),"POST");
        $jsondata=json_decode($res->getBody()->__toString(),true);
        if($jsondata["Data"] !=null)
        {
            foreach ($jsondata["Data"] as $role_authority) {
                if($role_authority["role_id"]==$role)
                {
                    array_push( $authority, array(
//                    "no" => $role_authority["no"],
                        "features_id" => $role_authority["features_id"],
                    ));
                }
            }
        }
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/features/user/relation/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")),"POST");
        $jsondata=json_decode($res->getBody()->__toString(),true);
        if($jsondata["Data"] !=null)
        {
            foreach ($jsondata["Data"] as $user_authority) {
                if($user_authority["user_id"]==$user_id)
                {
                    array_push( $authority, array(
//                    "no" => $role_authority["no"],
                        "features_id" => $user_authority["features_id"],
                    ));
                }
            }
        }

        // 取得人員資料
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/group/all",env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
        $jsondata = json_decode($res->getBody()->__toString(), true);
        $rowdata = array();
        if($jsondata["Data"]!=null){
            foreach ($jsondata["Data"] as $group) {
                // 搜尋類別
                if (!$request->search_text == null) {
                    switch ($request->search_type) {
                        /*ID case 1:
                             if (count(explode($request->search_text, $group["ID"])) < 2) {
                                 // no match
                                 continue 2;
                             }
                             break;*/
                        // 名稱
                        case 2:
                            if (count(explode($request->search_text, $group["Name"])) < 2) {
                                // no match
                                continue 2;
                            }
                            break;
                        // 未選擇
                        default:
                            break;
                    }
                }
                array_push($rowdata, array(
                    "id" => $group["ID"],
                    "name" => $group["Name"],
                    "detail" => sprintf("<button class=\"btn btn-outline-dark\" data-toggle=\"modal\" data-target=\"#ModifyMemberModalCenter\" onclick=\"group_modify(this)\">修改</button>"),
                ));
            }
            if (count($rowdata) == 0) {
                $msg = "查無結果";
            } else {
                $msg = "以下為查詢結果";
            }
            if ($msg == "以下為查詢結果") {
                return view("Person_Search_Group", ["title" => "人員群組","rowdata" => $rowdata, "error_msg" => $msg,"level"=>$level,'authority'=>$authority]);
            } else {
                return $this->Group_index()->with(["error_msg"=>$msg]);
            }
        }else{
            $msg = "尚未有群組";
            return view("Person_Search_Group", ["title" => "人員群組", "rowdata" => $rowdata,"error_msg"=>$msg,"level"=>$level,'authority'=>$authority]);
        }
    }

    //修改人員群組
    public function modify_Group(Request $request)
    {

        $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);
        if($jsondata["Data"] !=null)
        {
            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"));
        }
        $search_type=2;
        $groupname = $request->modify_name;
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/group/all",env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
        $jsondata = json_decode($res->getBody()->__toString(), true);
        if($jsondata["Data"] !=null)
        {
            foreach ($jsondata["Data"] as $personG) {
                if ( $groupname  != null) {
                    switch ($search_type) {
                        case 2:
                            if (count(explode($groupname, $personG["Name"])) < 2) {
                                $stuat = 1;
                                continue 2;
                            }
                            break;
                        default:
                            break;
                    }
                    $stuat = 2;
                }else{
                    $msg = "請輸入修改內容";
                    return redirect()->route('Group_index')->with(["error_msg" => $msg]);
                }
            }
        }
        if ($stuat != 2){
            [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/group/update", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
                "multipart",
                [
                    [
                        'name' => "id",
                        "contents" => $request->modify_id
                    ],
                    [
                        'name' => "name",
                        "contents" => $groupname
                    ],

                ]);
            $msg = "修改成功";
            return redirect()->route('Group_index')->with(["error_msg" => $msg]);
        }else{
            $msg = "已有重複群組名稱";
            return redirect()->route('Group_index')->with(["error_msg" => $msg]);
        }
    }

    //刪除人員群組
    public function delete_Group(Request $request)
    {

        if ($request->selectedId != null) {
            $id = $request->selectedId;
            $ids = explode(",", $id);
            $grouphasperson=0;
            [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/group/relation/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
            $jsondata = json_decode($res->getBody()->__toString(), true);
            foreach ($ids as $id){
                if($jsondata["Data"]!=null){
            foreach ($jsondata["Data"] as $person){
                if ($id == $person["PersonGroupID"]){
                    $grouphasperson=1;
                }
            }}
            }
            if ($grouphasperson==0){
            $client = new \GuzzleHttp\Client();
            foreach ($ids as $groupid) {
                $res = $client->request('POST', sprintf("http://%s:%s", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")) . "/person/group/delete", [
                    'form_params' => [
                        "id" => $groupid,
                    ]
                ]);
                $jsondata = json_decode($res->getBody()->__toString(), true);
                if ($res->getStatusCode() != 200) {
                    array_push($error_ids, $id);
                }
            }
                return redirect()->route('Group_index');
        } else {
                $msg="群組還存在有人員";
                return redirect()->route('Group_index')->with(["error_msg" => $msg]);
        }
        }else {
            $msg = "未選擇刪除群組名稱";
            return redirect()->route('Group_index')->with(["error_msg" => $msg]);

        }
    }


    //人員群組首頁--沒用
    public function index_Group(Request $request)
    {
        $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($camera_list);
        // dd($groups);
        // 取得人員資料

        $request->session()->all();
        $persongroupid =  $request->session()->get('groupid');;
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/group/relation/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
        $jsondata = json_decode($res->getBody()->__toString(), true);
        //dd($jsondata);
        $rowdata2 = array();
        $search_type = 1;
        $rowdata = array();
        $removeperson=array();
        if ($jsondata["Data"] == null){
            [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/select/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "GET");
            $jsondata = json_decode($res->getBody()->__toString(), true);
            if ($jsondata["Data"] != null){
                foreach ($jsondata["Data"] as $person) {
                array_push($rowdata, array(
                    "id" => $person["ID"],
                    "name" => $person["Name"],
                ));
            }}

            $msg="群組無相關人員";
            return view("Person_Group", ["title" => "人員群組管理", "groups" => $groups, "camera_list" => $camera_list, "rowdata" => $rowdata, "rowdata2" => $rowdata2,"error_msg"=>$msg]);
        }
        if( $persongroupid !=null and $jsondata["Data"]!=null) {
        if( $persongroupid !=null and $jsondata["Data"] != null) {

            foreach ($jsondata["Data"] as $personG) {
                if ($persongroupid != null) {
                    switch ($search_type) {
                        case 1:
                            if ($persongroupid != $personG["PersonGroupID"]) {
                                // no match
                                continue 2;
                            }
                            break;
                        // 未選擇
                        default:
                            continue 2;
                            break;
                    }
                }
                [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/select/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "GET");
                $jsondata2 = json_decode($res->getBody()->__toString(), true);
                foreach ($jsondata2["Data"] as $personname) {
                    if ($persongroupid != null) {
                        switch ($search_type) {
                            case 1:
                                if ($personname["ID"] != $personG["PersonID"]) {
                                    continue 2;
                                }
                                break;
                            // 未選擇
                            default:
                                continue 2;
                                break;
                        }
                    }
                    array_push($rowdata2, array(
//                        "img" => sprintf("<img class='faceimg' src='%s/person/%s'>", sprintf("http://%s:%s", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), $personname["Photo"]),
                        "img" => sprintf("<img class='faceimg' src='/get/image?img_path=/person/%s'>", $personname["Photo"]),
                        "id" => $personG["PersonGroupID"],
                        "name" => $personG["PersonID"],
                        "personname" => $personname["Name"],
                    ));
                }
                array_push($removeperson, array(
                    "name" => $personG["PersonID"],
                ));
            }

            //人員群組新增表格顯示
            [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/select/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "GET");
            $jsondata = json_decode($res->getBody()->__toString(), true);
            foreach ($jsondata["Data"] as $person) {
                $check = 0;
                foreach ($rowdata2 as $rd2) {
                    if ($rd2["name"] == $person["ID"]) {
                        $check = 1;
                    }
                }
                if ($check == 0) {
                    array_push($rowdata, array(
                        "id" => $person["ID"],
                        "name" => $person["Name"],
                    ));
                }
            }
//           dd($rowdata);
            return view("Person_Group", ["title" => "人員群組管理", "groups" => $groups, "camera_list" => $camera_list, "rowdata" => $rowdata, "rowdata2" => $rowdata2]);
        }
    }
    }

    //搜尋群組人員
    public function search_personGroup(Request $request)
    {
        $request->session()->all();
        $username=$request->session()->get('Tusername');    //帳號
        $role="";
        $department="";
        $level="";
        $user_id="";
        [$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);
        foreach ($jsondata["Data"] as $user) {
            if($user["username"]==$username)
            {
                $role=$user["role"];
                $department=$user["department"];
                $user_id=$user["id"];
            }
        }
        if($role=="7")
        {
            $level="4";
        }
        elseif ($role=="3")
        {
            $level="3";
        }
        elseif ($role=="6")
        {
            $level="2";
        }
        elseif($role=="5")
        {
            $level="1";
        }
        //取得權限
        $authority=array();
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/features/role/relation/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")),"POST");
        $jsondata=json_decode($res->getBody()->__toString(),true);
        if($jsondata["Data"] !=null)
        {
            foreach ($jsondata["Data"] as $role_authority) {
                if($role_authority["role_id"]==$role)
                {
                    array_push( $authority, array(
//                    "no" => $role_authority["no"],
                        "features_id" => $role_authority["features_id"],
                    ));
                }
            }
        }
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/features/user/relation/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")),"POST");
        $jsondata=json_decode($res->getBody()->__toString(),true);
        if($jsondata["Data"] !=null)
        {
            foreach ($jsondata["Data"] as $user_authority) {
                if($user_authority["user_id"]==$user_id)
                {
                    array_push( $authority, array(
//                    "no" => $role_authority["no"],
                        "features_id" => $user_authority["features_id"],
                    ));
                }
            }
        }

        // 取得人員資料
        $request->session()->put('groupid', $request->selectedId);
        $persongroupid = $request->selectedId;
//        dd($persongroupid);
        if(strpos($persongroupid,',')!==false){
            $msg="請選擇單一群組";
            return redirect()->route('Group_index')->with(["error_msg" => $msg]);
//            return $this->Group_index()->with(["error_msg"=>$msg]);
        }
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/group/relation/all",env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
        $jsondata = json_decode($res->getBody()->__toString(), true);
        //dd($jsondata);
        $rowdata2 = array();
        $search_type = 1;
        $rowdata = array();
        $removeperson=array();
        if($persongroupid !=null){
        if ($jsondata["Data"] == null){
            [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/select/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "GET");
            $jsondata = json_decode($res->getBody()->__toString(), true);
            if ($jsondata["Data"] != null){
            foreach ($jsondata["Data"] as $person) {
                    array_push($rowdata, array(
                        "id" => $person["ID"],
                        "name" => $person["Name"],
                    ));
                }
            $msg="群組無相關人員";
            return view("Person_Group", ["title" => "人員群組管理", "rowdata" => $rowdata, "rowdata2" => $rowdata2,"error_msg"=>$msg,"level"=>$level,'authority'=>$authority]);
        }else{
                $msg="群組無相關人員";
                return view("Person_Group", ["title" => "人員群組管理", "rowdata" => $rowdata, "rowdata2" => $rowdata2,"error_msg"=>$msg,"level"=>$level,'authority'=>$authority]);
            }
        }
        if( $persongroupid !=null and $jsondata["Data"] != null){
            foreach ($jsondata["Data"] as $personG) {
                if ($persongroupid != null) {
                    switch ($search_type) {
                        case 1:
                            if ($persongroupid!=$personG["PersonGroupID"]) {
                                // no match
                                continue 2;
                            }
                            break;
                        // 未選擇
                        default:
                            continue 2;
                            break;
                    }
                }
                [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/select/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "GET");
                $jsondata2 = json_decode($res->getBody()->__toString(), true);
                foreach ($jsondata2["Data"] as $personname){
                    if ($persongroupid != null) {
                        switch ($search_type) {
                            case 1:
                                if ($personname["ID"]!=$personG["PersonID"]) {
                                    continue 2;
                                }
                                break;
                            // 未選擇
                            default:
                                continue 2;
                                break;
                        }
                    }
                    array_push($rowdata2, array(
//                        "img"=>sprintf("<img class='faceimg' src='%s/person/%s'>",sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")), $personname["Photo"]),
                        "img"=>sprintf("<img class='faceimg' src='/get/image?img_path=/person/%s'>", $personname["ID"]),
                        "id" => $personG["PersonGroupID"],
                        "name" => $personG["PersonID"],
                        "personname"=>$personname["Name"],
                    ));
                }  array_push($removeperson, array(
                    "name" => $personG["PersonID"],
                ));
            }

            //人員群組新增表格顯示
            [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/select/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "GET");
            $jsondata = json_decode($res->getBody()->__toString(), true);
            if($jsondata["Data"] !=null)
            {
                foreach ($jsondata["Data"] as $person) {
                    $check=0;
                    foreach ($rowdata2 as $rd2){
                        if($rd2["name"] ==$person["ID"])
                        {
                            $check=1;
                        }
                    }
                    if($check==0)
                    {
                        array_push($rowdata, array(
                            "id" => $person["ID"],
                            "name" => $person["Name"],
                        ));
                    }
                }
            }

         //dd($rowdata);
            return view("Person_Group", ["title" => "人員群組管理", "rowdata" => $rowdata, "rowdata2" => $rowdata2,"level"=>$level,'authority'=>$authority]);
        }else{
            $msg="請選擇搜尋群組";
            return redirect()->route('Group_index')->with(["error_msg" => $msg]);
        }
        }else{
            $msg="請選擇搜尋群組";
            return redirect()->route('Group_index')->with(["error_msg" => $msg]);
        }

    }


    //新增人員群組關係
    public function insert_personG(Request $request) {
        $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);
        if($jsondata["Data"] !=null)
        {
            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,
                ));
            }
        }

        $personGId=$request->session()->get('groupid');
        $personId=$request->selectedpId;
        $pids=explode(",",$personId);
        $idss=implode("",$pids);
        if ($personId!=null){
            foreach ($pids as $id){
                [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/group/relation/insert",env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
                    "multipart",
                    [
                        [
                            'name' => "person_group_id",
                            "contents" => $personGId
                        ],
                        [
                            'name' => "person_id",
                            "contents" => $id
                        ],
                    ]);
            }
            $error_msg="已新增成功".$idss;
        }else{
            $error_msg="新增失敗，未選擇人員";
        }
        return redirect()->route('Group_index')->with(["error_msg" => $error_msg]);
    }

    //移除人員群組關係
    public function delete_personG(Request $request){
        $server_ip="192.168.6.240";
        $server_port="5000";
        if($request->selectedId!=null) {
            $client = new \GuzzleHttp\Client();
            $error_ids=array();
            $ids=explode(",",$request->selectedId);
            $names=explode(",",$request->selectedName);
            foreach ($names as $name){
                foreach ($ids as $id){
                $res=$client->request('POST',sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT"))."/person/group/relation/delete",[
                    'form_params'=>[
                        "person_group_id"=>$id,
                        "person_id"=>$name
                    ]
                ]);
                $jsondata=json_decode($res->getBody()->__toString(),true);
                if($res->getStatusCode()!=200){
                    array_push($error_ids,$name);
                }
                }
            }
            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 redirect()->route('Group_index')->with(["error_msg" => $msg]);
        }else{
            $msg="未選擇刪除人員編號";
            return redirect()->route('Group_index')->with(["error_msg" => $msg]);
        }

    }

    //查詢群組首頁名稱
    public function personG_search(Request $request)
{
    $server_ip = "192.168.6.240";
    $server_port = "5000";
    $request->session()->all();
    $username=$request->session()->get('Tusername');    //帳號
    $role="";
    $department="";
    $level="";
    $user_id="";
    [$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);
    foreach ($jsondata["Data"] as $user) {
        if($user["username"]==$username)
        {
            $role=$user["role"];
            $department=$user["department"];
            $user_id=$user["id"];
        }
    }
    if($role=="7")
    {
        $level="4";
    }
    elseif ($role=="3")
    {
        $level="3";
    }
    elseif ($role=="6")
    {
        $level="2";
    }
    elseif($role=="5")
    {
        $level="1";
    }
    //取得權限
    $authority=array();
    [$ret,$res]=$this->request_server(sprintf("http://%s:%s/features/role/relation/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")),"POST");
    $jsondata=json_decode($res->getBody()->__toString(),true);
    if($jsondata["Data"] !=null)
    {
        foreach ($jsondata["Data"] as $role_authority) {
            if($role_authority["role_id"]==$role)
            {
                array_push( $authority, array(
//                    "no" => $role_authority["no"],
                    "features_id" => $role_authority["features_id"],
                ));
            }
        }
    }
    [$ret,$res]=$this->request_server(sprintf("http://%s:%s/features/user/relation/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")),"POST");
    $jsondata=json_decode($res->getBody()->__toString(),true);
    if($jsondata["Data"] !=null)
    {
        foreach ($jsondata["Data"] as $user_authority) {
            if($user_authority["user_id"]==$user_id)
            {
                array_push( $authority, array(
//                    "no" => $role_authority["no"],
                    "features_id" => $user_authority["features_id"],
                ));
            }
        }
    }


    // 取得人員資料
    $request->session()->all();
    $persongroupid = $request->session()->get("groupid");
    [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/group/relation/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
    $jsondata = json_decode($res->getBody()->__toString(), true);
    //dd($jsondata);
    $rowdata2 = array();
    $search_type = 1;
    $rowdata = array();
    $removeperson = array();
    $rowdata3 = array();
    if ($persongroupid != null) {
        foreach ($jsondata["Data"] as $personG) {
            if ($persongroupid != null) {
                switch ($search_type) {
                    case 1:
                        if ($persongroupid != $personG["PersonGroupID"]) {
                            // no match
                            continue 2;
                        }
                        break;
                    // 未選擇
                    default:
                        continue 2;
                        break;
                }
            }
            [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/select/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "GET");
            $jsondata2 = json_decode($res->getBody()->__toString(), true);
            if($jsondata2["Data"] != null){
                foreach ($jsondata2["Data"] as $personname) {
                    if ($persongroupid != null) {
                        switch ($search_type) {
                            case 1:
                                if ($personname["ID"] != $personG["PersonID"]) {
                                    continue 2;
                                }
                                break;
                            // 未選擇
                            default:
                                continue 2;
                                break;
                        }
                    }
                    array_push($rowdata2, array(
//                        "img" => sprintf("<img class='faceimg' src='%s/person/%s'>", sprintf("http://%s:%s", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), $personname["Photo"]),
                        "img" => sprintf("<img class='faceimg' src='/get/image?img_path=/person/%s'>", $personname["ID"]),
                        "id" => $personG["PersonGroupID"],
                        "name" => $personG["PersonID"],
                        "personname" => $personname["Name"],
                    ));
                }
                }
            array_push($removeperson, array(
                "name" => $personG["PersonID"],
            ));
        }
    }


        $rowdata3 = array();
        foreach ($rowdata2 as $data) {
            if (!$request->search_text == null) {
                switch ($request->search_type) {
                    // ID
                    case 1:
                        if (count(explode($request->search_text, $data["name"])) < 2) {
                            // no match
                            continue 2;
                        }
                        break;
                    // 姓名
                    case 2:
                        if (count(explode($request->search_text, $data["personname"])) < 2) {
                            // no match
                            continue 2;
                        }
                        break;
                    // 未選擇
                    default:
                        break;
                }
            }
            array_push($rowdata3, array(
                "img" => $data["img"],
                "id" => $data["id"],
                "name" => $data["name"],
                "personname" => $data["personname"],
            ));
        }

        //dd($rowdata3);
        if (count($rowdata3) == 0) {
            $msg = "查無結果";
        } else {
            $msg = "以下為查詢結果";
        }



        //人員群組新增表格顯示
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/select/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "GET");
        $jsondata = json_decode($res->getBody()->__toString(), true);
        if($jsondata["Data"] !=null)
        {
            foreach ($jsondata["Data"] as $person) {
                $check=0;
                foreach ($rowdata2 as $rd2){
                    if($rd2["name"] ==$person["ID"])
                    {
                        $check=1;
                    }
                }
                if($check==0)
                {
                    array_push($rowdata, array(
                        "id" => $person["ID"],
                        "name" => $person["Name"],
                    ));
                }
            }
        }

        if ($msg != null) {
            return view("Person_Group", ["title" => "人員群組管理","rowdata" => $rowdata, "rowdata2" => $rowdata3, "error_msg" => $msg,"level"=>$level,'authority'=>$authority]);
        } else {
            return view("Person_Group", ["title" => "人員群組管理","rowdata" => $rowdata, "rowdata2" => $rowdata3,"level"=>$level,'authority'=>$authority]);
        }
    }


    // 公用方法(別人寫的)
    // 取得所有設備清單 回傳 群組 設備名稱與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;
        }
    }

}
