<?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()
    {
        $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"));
        // dd($camera_list);
        // dd($groups);
        // 取得人員資料
        [$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();
        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=\"person_modify(this)\">修改</button>"),
            ));
        }
        //$persontest=implode("",$persondata);
        //$personGer=array();
        //$personGer=explode(',',"$persondata");
        //$data =array('name' => 'ray','age' => 25);
        return view("Person_Search_Group", ["title" => "人員群組", "groups" => $groups, "camera_list" => $camera_list, "rowdata" => $rowdata]);
    }

    //新增人員群組
    public function insert_Group(Request $request)
    {
        $server_ip = "192.168.6.240";
        $server_port = "5000";
        $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,
            ));
        }
        $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;
        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 = "請填寫群組名稱，未新增成功";
        }
        return $this->Group_index()->with(["error_msg" => $error_msg]);
    }

    //搜尋人員群組
    public function search_Group(Request $request)
    {
        $server_ip = "192.168.6.240";
        $server_port = "5000";
        $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"));
        // dd($camera_list);
        // dd($groups);
        // 取得人員資料
        [$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();
        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=\"person_modify(this)\">修改</button>"),
            ));
        }
        if (count($rowdata) == 0) {
            $msg = "查無結果";
        } else {
            $msg = "以下為查詢結果";
        }
        if ($msg != null) {
            return view("Person_Search_Group", ["title" => "人員群組", "groups" => $groups, "camera_list" => $camera_list, "rowdata" => $rowdata, "error_msg" => $msg]);
        } else {
            return view("Person_Search_Group", ["title" => "人員群組", "groups" => $groups, "camera_list" => $camera_list, "rowdata" => $rowdata]);
        }

    }

    //修改人員群組
    public function modify_Group(Request $request)
    {
        $server_ip = "192.168.6.240";
        $server_port = "5000";
        $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"));
        $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);
        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 $this->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 $this->Group_index()->with(["error_msg" => $msg]);
                }else{
                    $msg = "已有重複群組名稱";
                    return $this->Group_index()->with(["error_msg" => $msg]);
                }

    }

    //刪除人員群組
    public function delete_Group(Request $request)
    {
        $server_ip = "192.168.6.240";
        $server_port = "5000";
        if ($request->selectedId != null) {
            $client = new \GuzzleHttp\Client();
            $id = $request->selectedId;
            $ids = explode(",", $id);
            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 $this->Group_index();
        } else {
            $msg = "未選擇刪除群組名稱";
            return $this->Group_index()->with(["error_msg" => $msg]);
        }
    }


    //人員群組首頁
    public function index_Group(Request $request)
    {
        $server_ip = "192.168.6.240";
        $server_port = "5000";
        $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);
            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"]),
                        "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)
    {
        $server_ip = "192.168.6.240";
        $server_port = "5000";
        $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()->put('groupid', $request->selectedId);
        $persongroupid = $request->selectedId;
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/group/relation/all", $server_ip, $server_port), "POST");
        $jsondata = json_decode($res->getBody()->__toString(), true);
        //dd($jsondata);
        $rowdata2 = array();
        $search_type = 1;
        $rowdata = array();
        $removeperson=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);
                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"]),
                        "id" => $personG["PersonGroupID"],
                        "name" => $personG["PersonID"],
                        "personname"=>$personname["Name"],
                    ));

                }  array_push($removeperson, array(
                    "name" => $personG["PersonID"],
                ));

            }  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]);
       else{
            $msg="請選擇搜尋群組";
            return $this->Group_index()->with(["error_msg"=>$msg]);
        }
    }*/
    public function search_personGroup(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()->put('groupid', $request->selectedId);
        $persongroupid = $request->selectedId;
        if(strpos($persongroupid,',')!==false){
            $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 ($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]);
        }else{
                $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){
            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"]),
                        "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]);
        }else{
            $msg="請選擇搜尋群組";
            return $this->Group_index()->with(["error_msg"=>$msg]);
        }

    }


    //新增人員群組關係
    public function insert_personG(Request $request) {
        $server_ip="192.168.6.240";
        $server_port="5000";
        $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,
            ));
        }
        $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 $this->index_Group($request)->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  $this->index_Group($request)->with(["error_msg" => $msg]);
        }else{
            $msg="未選擇刪除人員編號";
            return  $this->index_Group($request)->with(["error_msg" => $msg]);
        }

    }

    //查詢群組首頁名稱
    public function personG_search(Request $request)
{
    $server_ip = "192.168.6.240";
    $server_port = "5000";
    $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();
    $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);
            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"]),
                    "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);
        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" => "人員群組管理", "groups" => $groups, "camera_list" => $camera_list, "rowdata" => $rowdata, "rowdata2" => $rowdata3, "error_msg" => $msg]);
        } else {
            return view("Person_Group", ["title" => "人員群組管理", "groups" => $groups, "camera_list" => $camera_list, "rowdata" => $rowdata, "rowdata2" => $rowdata3]);
        }


}


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

}
