<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use GuzzleHttp\Exception\RequestException;
use phpDocumentor\Reflection\Types\Null_;


class DeviceController extends Controller
{
    public function index(Request $request)
    {
        $msg = request()->session()->get('msg');

        $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"],
                    ));
                }
            }
        }


        $count=0;
        // 取得 Device 資料
        $drives = array();
        [$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) {
                $count=$count+1;
                array_push($drives,array(
                    "id"=>$device["ID"],
                    "location" =>$device["Location"],
                    "host" =>$device["Host"],
                    "port" =>$device["Port"],
                    "type" =>$device["Type"],
                ));
            }
        }


        //取得類型資料
        $type = array();
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/device/type/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 $device_type) {
                array_push($type, array(
                    "id" => $device_type["ID"],
                    "name" => $device_type["Name"],
                ));
            }
        }

        if($msg!=null){
            return view("Device",["title"=>"設備管理","error_msg"=>$msg,"devices"=>$drives,"count"=>$count, "types" => $type,"level"=>$level,'authority'=>$authority]);
        }else{
            return view("Device",["title"=>"設備管理","devices"=>$drives,"count"=>$count, "types" => $type,"level"=>$level,'authority'=>$authority]);
        }
    }

    public function device_select(Request $request)
    {
        $msg = request()->session()->get('msg');

        $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"],
                    ));
                }
            }
        }


        $count=0;
        //取得搜尋的Device
        $select_devices = array();
        $set = $request->set;
        $value = $request->value;
        [$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 ($set != null and $jsondata["Data"]!=null){
            switch ($set) {
                case "ID":
                    foreach ($jsondata["Data"] as $select_id) {
                        if ($select_id["ID"] == $value)
                        {
                            $count=$count+1;
                            array_push($select_devices, array(
                                "id"=>$select_id["ID"],
                                "location" =>$select_id["Location"],
                                "host" =>$select_id["Host"],
                                "port" =>$select_id["Port"],
                                "type" =>$select_id["Type"],
                            ));
                        }
                    }
                    break;
                case "Location":
                    foreach ($jsondata["Data"] as $select_location) {
                        if ($select_location["Location"] == $value)
                        {
                            $count=$count+1;
                            array_push($select_devices, array(
                                "id"=>$select_location["ID"],
                                "location" =>$select_location["Location"],
                                "host" =>$select_location["Host"],
                                "port" =>$select_location["Port"],
                                "type" =>$select_location["Type"],
                            ));
                        }
                    }
                    break;
            }
        }
        //取得類型資料
        $type = array();
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/device/type/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
        $jsondata2 = json_decode($res->getBody()->__toString(), true);
        if($jsondata2["Data"]!=null)
        {
            foreach ($jsondata2["Data"] as $device_type) {
                array_push($type, array(
                    "id" => $device_type["ID"],
                    "name" => $device_type["Name"],
                ));
            }
        }
        if($select_devices==null)
        {
            $msg='無資料';
            if($jsondata["Data"]!=null)
            {
                foreach ($jsondata["Data"] as $select) {
                    array_push($select_devices, array(
                        "id" => $select["ID"],
                        "location" => $select["Location"],
                        "host" =>$select["Host"],
                        "port" =>$select["Port"],
                        "type" =>$select["Type"],
                    ));
                }
            }
        }

        if ($msg != null) {
            return view("Device", ["title" => "設備管理", "error_msg" => $msg, "devices" => $select_devices,"count"=>$count, "types" => $type,"level"=>$level,'authority'=>$authority	]);
        } else {
            return view("Device", ["title" => "設備管理", "devices" => $select_devices,"count"=>$count, "types" => $type,"level"=>$level,'authority'=>$authority	]);
        }

    }

    public function device_update(Request $request)
    {
//        $test=array($request->id,$request->host,$request->port,$request->location);
//        dd($test);
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/device/update",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"POST",
            "multipart",
            [
                [
                    'name'=>"id",
                    "contents"=>$request->id
                ],
                [
                    'name'=>"host",
                    "contents"=>$request->host
                ],
                [
                    'name'=>"port",
                    "contents"=>$request->port
                ],
                [
                    'name'=>"location",
                    "contents"=>$request->location
                ],
            ]);

        return redirect()->route('device');
    }

    public function device_delete(Request $request)
    {
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/device/delete", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
            "multipart",
            [
                [
                    'name'=>"id",
                    "contents"=>$request->id
                ],
            ]
        );
        $jsondata = json_decode($res->getBody()->__toString(),true);
        if($jsondata["Code"]==1)
        {
            $error_msg=$jsondata["Message"];
        }

        return redirect()->route('device');
    }

    public function type(Request $request)
    {
        $msg = request()->session()->get('msg');

        $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"],
                    ));
                }
            }
        }

        //取得類型資料
        $type = array();
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/device/type/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 $device_type) {
                array_push($type, array(
                    "id" => $device_type["ID"],
                    "name" => $device_type["Name"],
                    "vendor" => $device_type["Vendor"],
                    "vendorContactPerson" => $device_type["VendorContactPerson"],
                    "vendorContactWay" => $device_type["VendorContactWay"],
                ));
            }
        }
        if ($msg != null) {
            return view("Device_type", ["title" => "類型管理", "error_msg" => $msg, "types" => $type,"level"=>$level,'authority'=>$authority]);
        } else {
            return view("Device_type", ["title" => "類型管理", "types" => $type,"level"=>$level,'authority'=>$authority]);
        }
    }

    public function type_select(Request $request)
    {
        $msg = request()->session()->get('msg');

        $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"],
                    ));
                }
            }
        }


        $select_types = array();
        $set = $request->set;
        $value = $request->value;
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/device/type/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
        $jsondata = json_decode($res->getBody()->__toString(), true);
        if ($set != null and $jsondata["Data"]!=null) {
            switch ($set) {
                case "Name":
                    foreach ($jsondata["Data"] as $select_name) {
                        if ($select_name["Name"] == $value)
                            array_push($select_types, array(
                                "id" => $select_name["ID"],
                                "name" => $select_name["Name"],
                                "vendor" => $select_name["Vendor"],
                                "vendorContactPerson" => $select_name["VendorContactPerson"],
                                "vendorContactWay" => $select_name["VendorContactWay"],
                            ));
                    }
                    break;
                case "Vendor":
                    foreach ($jsondata["Data"] as $select_vendor) {
                        if ($select_vendor["Vendor"] == $value)
                            array_push($select_types, array(
                                "id" => $select_vendor["ID"],
                                "name" => $select_vendor["Name"],
                                "vendor" => $select_vendor["Vendor"],
                                "vendorContactPerson" => $select_vendor["VendorContactPerson"],
                                "vendorContactWay" => $select_vendor["VendorContactWay"],
                            ));
                    }
                    break;
            }
        }

        if($select_types==null)
        {
            $msg='無資料';
            if($jsondata["Data"]!=null)
            {
                foreach ($jsondata["Data"] as $select) {
                    array_push($select_types, array(
                        "id" => $select["ID"],
                        "name" => $select["Name"],
                        "vendor" => $select["Vendor"],
                        "vendorContactPerson" => $select["VendorContactPerson"],
                        "vendorContactWay" => $select["VendorContactWay"],
                    ));
                }
            }
        }

        if ($msg != null) {
            return view("Device_type", ["title" => "類型管理", "error_msg" => $msg, "types" => $select_types,"level"=>$level,'authority'=>$authority]);
        } else {
            return view("Device_type", ["title" => "類型管理", "types" => $select_types,"level"=>$level,'authority'=>$authority]);
        }

    }

    public function type_insert(Request $request)
    {
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/device/type/insert",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"POST",
            "multipart",
            [
                [
                    'name'=>"id",
                    "contents"=>$request->id
                ],
                [
                    'name'=>"name",
                    "contents"=>$request->name
                ],
                [
                    'name'=>"vendor",
                    "contents"=>$request->vendor
                ],
                [
                    'name'=>"vendor_contact_person",
                    "contents"=>$request->vendor_contact_person
                ],
                [
                    'name'=>"vendor_contact_way",
                    "contents"=>$request->vendor_contact_way
                ],
            ]);
        $jsondata = json_decode($res->getBody()->__toString(),true);
        if($jsondata["Code"]==1)
        {
            $error_msg=$jsondata["Message"];
        }

        return redirect()->route('type');
    }

    public function type_update(Request $request)
    {
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/device/type/update",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"POST",
            "multipart",
            [
                [
                    'name'=>"id",
                    "contents"=>$request->id
                ],
                [
                    'name'=>"name",
                    "contents"=>$request->name
                ],
                [
                    'name'=>"vendor",
                    "contents"=>$request->vendor
                ],
                [
                    'name'=>"vendor_contact_person",
                    "contents"=>$request->vendor_contact_person
                ],
                [
                    'name'=>"vendor_contact_way",
                    "contents"=>$request->vendor_contact_way
                ],
            ]);

        return redirect()->route('type');
    }

    public function type_delete(Request $request)
    {
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/device/type/delete", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
            "multipart",
            [
                [
                    'name'=>"id",
                    "contents"=>$request->id
                ],
            ]
        );
        return redirect()->route('type');
    }


    public function group(Request $request)
    {
        $msg = request()->session()->get('msg');

        $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"],
                    ));
                }
            }
        }


        //取得關係資料
        $relation = array();
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/device/group/relation/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
        $jsondata_rel = json_decode($res->getBody()->__toString(), true);
        if($jsondata_rel["Data"]!=null)
        {
            foreach ($jsondata_rel["Data"] as $device_relation) {
                array_push($relation, array(
                    "device_group_id" => $device_relation["DeviceGroupID"],
                    "device_id" => $device_relation["DeviceID"],
                ));
            }
        }


        //取得群組資料
        $device_groups = array();
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/device/group/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
        $jsondata = json_decode($res->getBody()->__toString(), true);
        if($jsondata_rel["Data"]==null)
        {
            if($jsondata["Data"]!=null)
            {
                foreach ($jsondata["Data"] as $device_group) {
                    $count = 0;
                    array_push($device_groups, array(
                        "id" => $device_group["ID"],
                        "name" => $device_group["Name"],
                        "count" => $count,
                    ));
                }
            }
        }
        if($jsondata["Data"]!=null and $jsondata_rel["Data"]!=null) {
            foreach ($jsondata["Data"] as $device_group) {
                $count = 0;
                foreach ($jsondata_rel["Data"] as $device_relation) {
                    if ($device_relation["DeviceGroupID"] == $device_group["ID"])
                        $count = $count + 1;
                }
                array_push($device_groups, array(
                    "id" => $device_group["ID"],
                    "name" => $device_group["Name"],
                    "count" => $count,
                ));
            }
        }

        if ($msg != null) {
            return view("Device_group", ["title" => "群組管理", "error_msg" => $msg, "device_groups" => $device_groups,"level"=>$level,'authority'=>$authority]);
        } else {
            return view("Device_group", ["title" => "群組管理", "device_groups" => $device_groups,"level"=>$level,'authority'=>$authority]);
        }
    }

    public function group_select(Request $request)
    {
        $msg = request()->session()->get('msg');

        $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"],
                    ));
                }
            }
        }


        //取得關係資料
        $relation = array();
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/device/group/relation/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
        $jsondata_rel = json_decode($res->getBody()->__toString(), true);
        if($jsondata_rel["Data"]!=null)
        {
            foreach ($jsondata_rel["Data"] as $device_relation) {
                array_push($relation, array(
                    "device_group_id" => $device_relation["DeviceGroupID"],
                    "device_id" => $device_relation["DeviceID"],
                ));
            }
        }

        $select_groups = array();
        $set = $request->set;
        $value = $request->value;
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/device/group/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
        $jsondata = json_decode($res->getBody()->__toString(), true);
        if($jsondata["Data"]!=null)
        {
            if ($set != null) {
                switch ($set) {
                    case "ID":
                        foreach ($jsondata["Data"] as $select_id) {
                            if ($select_id["ID"] == $value)
                            {
                                $count=0;
                                foreach ($jsondata_rel["Data"] as $device_relation) {
                                    if( $device_relation["DeviceGroupID"]== $select_id["ID"])
                                        $count=$count+1;
                                }
                                array_push($select_groups, array(
                                    "id" => $select_id["ID"],
                                    "name" => $select_id["Name"],
                                    "count" =>$count,
                                ));
                            }

                        }
                        break;
                    case "Name":
                        foreach ($jsondata["Data"] as $select_name) {
                            if ($select_name["Name"] == $value)
                            {
                                $count=0;
                                foreach ($jsondata_rel["Data"] as $device_relation) {
                                    if( $device_relation["DeviceGroupID"]== $select_name["ID"])
                                        $count=$count+1;
                                }
                                array_push($select_groups, array(
                                    "id" => $select_name["ID"],
                                    "name" => $select_name["Name"],
                                    "count" =>$count,
                                ));
                            }

                        }
                        break;

                }
            }
        }


        if($select_groups==null and $jsondata["Data"]!=null and $jsondata_rel["Data"])
        {
            $msg='無資料';
            foreach ($jsondata["Data"] as $select) {
                $count=0;
                foreach ($jsondata_rel["Data"] as $device_relation) {
                    if( $device_relation["DeviceGroupID"]== $select["ID"])
                        $count=$count+1;
                }
                array_push($select_groups, array(
                    "id" => $select["ID"],
                    "name" => $select["Name"],
                    "count" =>$count,
                ));
            }
        }

        if ($msg != null) {
            return view("Device_group", ["title" => "群組管理", "error_msg" => $msg, "device_groups" => $select_groups,"level"=>$level,'authority'=>$authority]);
        } else {
            return view("Device_group", ["title" => "群組管理", "device_groups" => $select_groups,"level"=>$level,'authority'=>$authority]);
        }
    }

    public function group_insert(Request $request)
    {

        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/device/group/insert",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"POST",
            "multipart",
            [
                [
                    'name'=>"name",
                    "contents"=>$request->name
                ],
            ]);
        $jsondata = json_decode($res->getBody()->__toString(),true);
        if($jsondata["Code"]==1)
        {
            $error_msg=$jsondata["Message"];
        }

        return redirect()->route('group');

    }

    public function group_update(Request $request)
    {
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/device/group/update",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"POST",
            "multipart",
            [
                [
                    'name'=>"id",
                    "contents"=>$request->id
                ],
                [
                    'name'=>"name",
                    "contents"=>$request->name
                ],
            ]);

        return redirect()->route('group');

    }

    public function group_delete(Request $request)
    {
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/device/group/delete", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
            "multipart",
            [
                [
                    'name'=>"id",
                    "contents"=>$request->id
                ],
            ]
        );

        return redirect()->route('group');
    }

    public function relation(Request $request)
    {
        $msg = request()->session()->get('msg');

        $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"],
                    ));
                }
            }
        }


        //取得群組資料
        $device_groups = array();
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/device/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 $device_group) {
                array_push($device_groups, array(
                    "id" => $device_group["ID"],
                    "name" => $device_group["Name"],
                ));
            }
        }
        // 取得 Device 資料
        $devices = array();
        [$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) {
                array_push($devices,array(
                    "id"=>$device["ID"],
                ));
            }
        }


        //取得關係資料
        $relation = array();
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/device/group/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 $device_relation) {
                array_push($relation, array(
                    "device_group_id" => $device_relation["DeviceGroupID"],
                    "device_id" => $device_relation["DeviceID"],
                ));
            }
        }


        if ($msg != null) {
            return view("Device_relation", ["title" => "設備群組關係", "error_msg" => $msg, "relations" => $relation, "device_groups" => $device_groups,"devices"=>$devices,"level"=>$level,'authority'=>$authority]);
        } else {
            return view("Device_relation", ["title" => "設備群組關係", "relations" => $relation, "device_groups" => $device_groups,"devices"=>$devices,"level"=>$level,'authority'=>$authority]);
        }
    }

    public function relation_select(Request $request)
    {
        $msg = request()->session()->get('msg');

        $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"],
                    ));
                }
            }
        }


        //取得群組資料
        $device_groups = array();
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/device/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 $device_group) {
            array_push($device_groups, array(
                "id" => $device_group["ID"],
                "name" => $device_group["Name"],
            ));
        }
        }

        // 取得 Device 資料
        $devices = array();
        [$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) {
                array_push($devices,array(
                    "id"=>$device["ID"],
                ));
            }
        }


        $count=0;
        $select_relations = array();
        $set = $request->set;
        $value = $request->value;
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/device/group/relation/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
        $jsondata = json_decode($res->getBody()->__toString(), true);
        if($jsondata["Data"]!=null)
        {
            if ($set != null) {
                switch ($set) {
                    case "DeviceID":
                        foreach ($jsondata["Data"] as $select_id) {
                            if ($select_id["DeviceID"] == $value)
                            {
                                $count=$count+1;
                                array_push($select_relations, array(
                                    "device_group_id" => $select_id["DeviceGroupID"],
                                    "device_id" => $select_id["DeviceID"],
                                ));
                            }
                        }
                        break;
                    case "DeviceGroupID":
                        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/device/group/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
                        $jsondata2 = json_decode($res->getBody()->__toString(), true);
                        $name_id=null;
                        foreach ($jsondata2["Data"] as $select_nameid) {
                            if($select_nameid["Name"]==$value)
                                $name_id=$select_nameid["ID"];
                        }
                        if($name_id!=null)
                        {
                            foreach ($jsondata["Data"] as $select_name) {
                                if ($select_name["DeviceGroupID"] == $name_id)
                                {
                                    $count=$count+1;
                                    array_push($select_relations, array(
                                        "device_group_id" => $select_name["DeviceGroupID"],
                                        "device_id" => $select_name["DeviceID"],
                                    ));
                                }
                            }
                        }
                        break;
                }
            }
        }


        if($select_relations==null)
        {
            $msg='無資料';
            if($jsondata["Data"]!=null)
            {
                foreach ($jsondata["Data"] as $select) {
                    array_push($select_relations, array(
                        "device_group_id" => $select["DeviceGroupID"],
                        "device_id" => $select["DeviceID"],
                    ));
                }
            }

        }

        if ($msg != null) {
            return view("Device_relation", ["title" => "設備群組關係", "error_msg" => $msg, "relations" => $select_relations, "device_groups" => $device_groups,"devices"=>$devices,"count"=>$count,"level"=>$level,'authority'=>$authority]);
        } else {
            return view("Device_relation", ["title" => "設備群組關係", "relations" => $select_relations, "device_groups" => $device_groups,"devices"=>$devices,"count"=>$count,"level"=>$level,'authority'=>$authority]);
        }
    }

    public function relation_insert(Request $request)
    {
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/device/group/relation/insert",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"POST",
            "multipart",
            [
                [
                    'name'=>"device_id",
                    "contents"=>$request->device_id
                ],
                [
                    'name'=>"device_group_id",
                    "contents"=>$request->group_id
                ],
            ]);
        $jsondata = json_decode($res->getBody()->__toString(),true);
        if($jsondata["Code"]==1)
        {
            $error_msg=$jsondata["Message"];
        }

        return redirect()->route('relation');
    }

    public function relation_delete(Request $request)
    {
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/device/group/relation/delete", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
            "multipart",
            [
                [
                    'name'=>"device_id",
                    "contents"=>$request->device_id
                ],
                [
                    'name'=>"device_group_id",
                    "contents"=>$request->device_group_id
                ],
            ]
        );

        return redirect()->route('relation');
    }

    //班別
    public function shift_index(Request $request)
    {
        $msg = request()->session()->get('msg');

        $request->session()->all();
        $username=$request->session()->get('Tusername');    //帳號
        $role="";
        $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"];
                $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"],
                    ));
                }
            }
        }


        // 取得 Device 資料
        $devices = array();
        [$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) {
                array_push($devices,array(
                    "id"=>$device["ID"],
                    "location" =>$device["Location"],
                    "shift_list" =>"",
                    "modify"=>sprintf("<button class=\"btn btn-outline-dark\" style=\"margin-right: 10px;\" data-toggle=\"modal\" data-target=\"#DeviceShift\" onclick=\"device_shift_data(this)\">修改班別</button>"),
                ));
            }
        }

        //all shift
        $shifts = array();
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/shift/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 $shift) {
                array_push( $shifts, array(
                    "no" => $shift["no"],
                    "name" => $shift["name"],
                    "start" => $shift["start"],
                    "end" => $shift["end"],
                    "note" => $shift["note"],
                ));
            }
        }

        //all device shift relation
        $device_shift_relations = array();
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/device/shift/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 $device_shift_relation) {
                $name="";
                $start="";
                $end="";
                foreach($shifts as $shift)
                {
                    if($device_shift_relation["shift_no"]==$shift["no"])
                    {
                        $name=$shift["name"];
                        $start=$shift["start"];
                        $end=$shift["end"];
                    }
                }
                array_push( $device_shift_relations, array(
                    "no" => $device_shift_relation["no"],
                    "device_id" => $device_shift_relation["device_id"],
                    "shift_no" => $device_shift_relation["shift_no"],
                    "note" => $device_shift_relation["note"],
                    "shift_name" => $name,
                    "shift_start" => $start,
                    "shift_end" => $end,
                ));
            }
        }
        $count=0;
        foreach ($devices as $device)
        {
            $shift_note="";
            foreach($device_shift_relations as $relation)
            {
                if($relation["device_id"]==$device["id"])
                {
                    //dd($relation["shift_name"]);
                    if($shift_note=="")
                    {
                        $shift_note=$relation["shift_name"];
                    }
                    else
                    {
                        $shift_note=$shift_note.",".$relation["shift_name"];
                    }
                    //dd($device["shift_list"]);
                }
            }
            $devices[$count]["shift_list"]=$shift_note;
            $count++;
        }
        //dd($devices);

        if($msg!=null){
            return view("Shift",["title"=>"班別管理","error_msg"=>$msg,"devices"=>$devices,"level"=>$level,'authority'=>$authority,'shifts'=>$shifts,'device_shift_relations'=>$device_shift_relations]);
        }else{
            return view("Shift",["title"=>"班別管理","devices"=>$devices,"level"=>$level,'authority'=>$authority,'shifts'=>$shifts,'device_shift_relations'=>$device_shift_relations]);
        }
    }

    public function shift_insert(Request $request)
    {
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/shift/insert", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
            "multipart",
            [
                [
                    'name' => "name",
                    "contents" => $request->name
                ],
                [
                    'name' => "start",
                    "contents" => $request->start
                ],
                [
                    'name' => "end",
                    "contents" => $request->end
                ],
                [
                    'name' => "note",
                    "contents" => $request->note
                ],
            ]);
//        $jsondata = json_decode($res->getBody()->__toString(), true);
//        $error=$jsondata["Message"];
//        $msg=explode(" ",$error);
//        if (strstr($error,"failed")!=false){
//            $error_msg="修改失敗";
//        }
//        elseif (strstr($error,"exist")!=false)
//        {
//            $error_msg="編號不存在，修改失敗";
//        }
//        else{
//            $error_msg="修改成功";
//        }
        return redirect()->route('shift_index');
    }

    public function shift_update(Request $request)
    {
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/shift/update", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
            "multipart",
            [
                [
                    'name' => "no",
                    "contents" => $request->no
                ],
                [
                    'name' => "name",
                    "contents" => $request->name
                ],
                [
                    'name' => "start",
                    "contents" => $request->start
                ],
                [
                    'name' => "end",
                    "contents" => $request->end
                ],
                [
                    'name' => "note",
                    "contents" => $request->note
                ],
            ]);
        $jsondata = json_decode($res->getBody()->__toString(), true);
        $error=$jsondata["Message"];
        $msg=explode(" ",$error);
        if (strstr($error,"failed")!=false){
            $error_msg="修改失敗";
        }
        elseif (strstr($error,"exist")!=false)
        {
            $error_msg="編號不存在，修改失敗";
        }
        else{
            $error_msg="修改成功";
        }
        return redirect()->route('shift_index')->with(["msg" => $error_msg]);
    }

    public function shift_delete(Request $request)
    {
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/shift/delete", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
            "multipart",
            [
                [
                    'name' => "no",
                    "contents" => $request->no
                ],
            ]);
        $jsondata = json_decode($res->getBody()->__toString(), true);
        $error=$jsondata["Message"];
        $msg=explode(" ",$error);
        if (strstr($error,"failed")!=false){
            $error_msg="修改失敗";
        }
        elseif (strstr($error,"exist")!=false)
        {
            $error_msg="編號不存在，修改失敗";
        }
        else{
            $error_msg="修改成功";
        }
        return redirect()->route('shift_index')->with(["msg" => $error_msg]);
    }

    public function device_shift_update(Request $request)
    {
        $new_shift = $request->all();
        $device_id = $request->device_id;
        //dd($new_shift);
        $old_shift = array();
        $device_shifts = array();
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/device/shift/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 $device_shift_relation) {
                if($device_shift_relation["device_id"]==$device_id)
                {
                    array_push( $old_shift, $device_shift_relation["shift_no"]);
                    array_push( $device_shifts, array(
                        "no" => $device_shift_relation["no"],
                        "shift_no" => $device_shift_relation["shift_no"],
                    ));
                }
            }
        }
        $insert_shift = array();
        $delete_shift = array();
        $shifts = array();
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/shift/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 $shift) {
                array_push( $shifts, array(
                    "no" => $shift["no"],
                ));
                if(in_array($shift["no"],$old_shift))
                {
                    if(!in_array($shift["no"],$new_shift))
                    {
                        array_push( $delete_shift, array(
                            "no" => $shift["no"],
                        ));
                    }
                }
                if(in_array($shift["no"],$new_shift))
                {
                    if(!in_array($shift["no"],$old_shift))
                    {
                        array_push( $insert_shift, array(
                            "no" => $shift["no"],
                        ));
                    }
                }
            }

        }

        //dd($insert_shift);
        //isert
        foreach($insert_shift as $insert)
        {
            [$ret, $res] = $this->request_server(sprintf("http://%s:%s/device/shift/relation/insert", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
                "multipart",
                [
                    [
                        'name' => "device_id",
                        "contents" => $device_id
                    ],
                    [
                        'name' => "shift_no",
                        "contents" => $insert["no"]
                    ],
                    [
                        'name' => "note",
                        "contents" => ""
                    ],
                ]);
        }

        //delete
        foreach($delete_shift as $delete)
        {
            foreach($device_shifts as $device_shift)
            {
                if($delete["no"]==$device_shift["shift_no"])
                {
                    [$ret, $res] = $this->request_server(sprintf("http://%s:%s/device/shift/relation/delete", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
                        "multipart",
                        [
                            [
                                'name' => "no",
                                "contents" => $device_shift["no"]
                            ],
                        ]);
                }
            }

        }



        return redirect()->route('shift_index');
    }

    public function shift_punch_card_export(Request $request)
    {
        $date = "";
        $date_explode = explode(" ",$request->start_time);
        $date = str_replace("-","",$date_explode[0]);
        $filename = sprintf("../storage/export/%s.txt", $date);
        $file = fopen($filename, 'w');
        $client = new \GuzzleHttp\Client();
        $res=$client->request('POST', sprintf("http://%s:%s/device/shift/export",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),[
            'form_params'=>[
                'start'=>$request->start_time,
                'end'=>$request->end_time,
            ],
            'save_to' => $file
        ]);
        return response()->download($filename);
    }


    public function set_datetime_index(Request $request)
    {

        $msg = request()->session()->get('msg');

        $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"],
                    ));
                }
            }
        }

        date_default_timezone_set("Asia/Taipei");
        //dd(date('Y-m-d H:i:s',time()));
        //$msg = request()->session()->get('msg');

        // 取得 Device 資料
        $groups = array();
        $camera_list = array("Enabled"=>array());
        [$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,
                    "location" =>$device["Location"],
                ));
            }
        }
        array_push($groups, array("group"=> "Enabled"));

        $count=0;
        // 取得 Device 資料
        $drives = array();
        [$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) {
                $count=$count+1;
                array_push($drives,array(
                    "id"=>$device["ID"],
                    "location" =>$device["Location"],
                    "host" =>$device["Host"],
                    "port" =>$device["Port"],
                    "type" =>$device["Type"],
                ));
            }
        }

        //取得類型資料
        $type = array();
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/device/type/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
        $jsondata = json_decode($res->getBody()->__toString(), true);
        foreach ($jsondata["Data"] as $device_type) {
            array_push($type, array(
                "id" => $device_type["ID"],
                "name" => $device_type["Name"],
            ));
        }

        if($msg!=null){
            return view("Device_time",["title"=>"時間設置","groups"=>$groups,"camera_list"=>$camera_list,"error_msg"=>$msg,"devices"=>$drives,"count"=>$count, "types" => $type,"server_time" => date('Y-m-d H:i:s',time()),'authority'=>$authority]);
        }else{
            return view("Device_time",["title"=>"時間設置","groups"=>$groups,"camera_list"=>$camera_list,"devices"=>$drives,"count"=>$count, "types" => $type,"server_time" => date('Y-m-d H:i:s',time()),'authority'=>$authority]);
        }
    }

    public function set_datetime(Request $request)
    {

        $user_dt = str_replace("-","",$request->user_dt);
        //dd(str_replace(" ","-",$user_dt));
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/set/dt/%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT"),str_replace(" ","-",$user_dt)),"GET");
        $jsondata = json_decode($res->getBody()->__toString(),true);
        //dd($jsondata);
        return redirect()->route("device_time");
    }



    //取得API資料的方法
    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;
        }
    }
}
