<?php

namespace App\Http\Controllers;

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

class UserController extends Controller
{
    //user登入頁面
    public function index(Request $request)
    {
        $request->session()->all();
        $username = $request->session()->get('Tusername');
        $userpwd = $request->session()->get('Tuserpwd');
        $auth = $request->session()->get('auth');
        $user=$username." ".$userpwd." ".$auth;
        $userroles= array();
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/user/role/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) {
                array_push( $userroles, array(
                    "id" => $role["id"],
                    "name" => $role["name"],
                ));
            }
        }
        return view("User_login",["title"=>"使用者登入","uername"=>$username,"userpwd"=>$userpwd,"auth"=>$auth,"userroles"=>$userroles]);
    }
    //user登入後驗證
    public function user_login(Request $request){
        $request->session()->put('Tusername',$_POST["user_name"]);
        if($request->Auto_live=="right")
        {
            $request->session()->put('Tuserpwd',$_POST["user_pwd"]);
        }
        $request->session()->put('ailock','deflut');
        $_SESSION['user_name']=$_POST["user_name"];
        $_SESSION['user_pwd']=$_POST["user_pwd"];
        $username = $request->session()->get('user_name',$_POST["user_name"]);
        $userpwd = $request->session()->get('user_pwd',$_POST["user_pwd"]);
        if($username!=null || $userpwd!=null)
        {
            $client = new \GuzzleHttp\Client();
            $res=$client->request('POST', sprintf("http://%s:%s/user/auth", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")),[
                'form_params'=>[
                    "username"=>$username,
                    "password"=>$userpwd
                ]
            ]);
            $jsondata = json_decode($res->getBody()->__toString(), true);
            if(isset($jsondata["Data"]) ){
                $request->session()->put('lostring',$jsondata["Data"]);
                if ($request->Auto_live=="right") {
                    $request->session()->put('auth','1');
                }else{
                    $value1 = $request->session()->pull('auth');
                }
                $name="";
                $role="";
                $person_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"]==$_SESSION["user_name"])
                    {
                        $role=$user["role"];
                        $name=$user["name"];
                        $person_id=$user["person_id"];
                    }
                }
                $error_msg=$name." 登入成功";
                $check_delete=true;
                [$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){
                        if($person["ID"]==$person_id)
                        {
                            $check_delete=$person["Enabled"];
                        }
                    }
                }
                if(!$check_delete)
                {
                    $error_msg="登入失敗，帳號已停用";
                    return $this->index($request)->with(["error_msg" =>$error_msg ]);
                }
                if($role=="3")
                    return redirect()->route('comparison');
                return redirect()->route('comparison');
            }else{
                $request->session()->put('lostring',$jsondata["Data"]);
                $error_msg="登入失敗，請重新輸入帳號密碼";
                return $this->index($request)->with(["error_msg" => $error_msg]);
            }
        }else{
            $error_msg="請輸入帳號密碼";
            return $this->index($request)->with(["title"=>"使用者登入","error_msg" => $error_msg]);
        }
    }
    //user登出
    public function user_logout(Request $request){
        $value = $request->session()->pull('lostring');
        $value1 = $request->session()->pull('auth');
        //$request->session()->flush();
        return redirect('/');
    }
    //user首頁
    public function index_insert(Request $request){
        $request->session()->all();
        $msg = request()->session()->get('error_msg');
        $username=$request->session()->get('Tusername');    //帳號
        $role="";
        $department="";
        $level="";
        $user_id="";
        $person_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"];
                $person_id=$user["person_id"];
            }
        }
//        dd($department);
        if($role=="7")
        {
            $level="4";
        }
        elseif ($role=="3")
        {
            $level="3";
        }
        elseif ($role=="6")
        {
            $level="2";
        }
        elseif($role=="5")
        {
            $level="1";
        }
        //取得權限
        $authority=array();
        $roles_auth=array();
        $users_auth=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) {
                array_push( $roles_auth, array(
                    "no" => $role_authority["no"],
                    "role_id" => $role_authority["role_id"],
                    "features_id" => $role_authority["features_id"],
                ));
                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) {
                array_push( $users_auth, array(
                    "no" => $user_authority["no"],
                    "user_id" => $user_authority["user_id"],
                    "features_id" => $user_authority["features_id"],
                ));
                if($user_authority["user_id"]==$user_id)
                {
                    array_push( $authority, array(
//                    "no" => $user_authority["no"],
                        "features_id" => $user_authority["features_id"],
                    ));
                }
            }
        }

        $departments= array();
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/department/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 $department_1) {
                array_push( $departments, array(
                    "no" => $department_1["no"],
                    "department" => $department_1["department"],
                ));
            }
        }
        $persons= array();
        [$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( $persons, array(
                    "id" => $person["ID"],
                    "name" => $person["Name"],
                ));
            }
        }

        $group_id="";
        $person_group_relation=array();
        $group_persons=array();
        [$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);
        if($jsondata["Data"] !=null)
        {
            foreach ($jsondata["Data"] as $person_group) {
                array_push( $person_group_relation, array(
                    "person_id" => $person_group["PersonID"],
                    "group_id" => $person_group["PersonGroupID"],
                ));
                if($person_group["PersonID"]==$person_id)
                {
                    $group_id=$person_group["PersonGroupID"];
                }
            }
            foreach ($person_group_relation as $person_group_1) {
                if($person_group_1["group_id"]==$group_id)
                {
                    array_push( $group_persons,$person_group_1["person_id"]);
                }
            }
        }

        // 取得所有使用者資料
        $userroles= array();
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/user/role/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) {
                array_push( $userroles, array(
                    "id" => $role["id"],
                    "name" => $role["name"],
                ));
            }
        }
        $rowdata=array();
        [$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) {
            $user_authority="";
            foreach ($userroles as $userrole){
                switch ($user["role"]){
                    case $userrole["id"]:
                        $user_role=$userrole["name"];
                        break;
                    default:
                        break;
                }
            }
            foreach ($roles_auth as $role_auth)
            {
                if($user["role"]==$role_auth["role_id"])
                {
                    $user_authority=$user_authority.",".$role_auth["features_id"];
                }
            }
            foreach($users_auth as $user_auth)
            {
                if($user["id"]==$user_auth["user_id"])
                {
                    $user_authority=$user_authority.",".$user_auth["features_id"];
                }
            }
            $person_name="";
            foreach($persons as $person)
            {
                if($person["id"]==$user["person_id"])
                {
                    //dd($person["name"]);
                    $person_name=$person["name"];
                }
            }
            $department_name="";
            foreach($departments as $department_2)
            {
                if($department_2["no"]==$user["department"])
                {
                    $department_name=$department_2["department"];
                }
            }

            if($level =="4" || $level =="3"){
                array_push($rowdata,array(
                    "id"=>$user["id"],
                    "person_id"=>$user["person_id"],
                    "name"=>$user["name"],
                    "department"=>$user["department"],
                    "role"=>$user_role,
                    "on_board"=>$user["on_board"],
                    "username"=>$user["username"],
                    //"modify"=>sprintf("<button class=\"btn btn-outline-dark\" title=\"修改人員資料\" data-toggle=\"modal\" data-target=\"#ModifyMemberPWDModalCenter\" onclick=\"person_modify_pwd(this)\">修改密碼</button>"),
                    "modify"=>sprintf("<button class=\"btn btn-outline-dark\" title=\"修改人員資料\" data-toggle=\"modal\" data-target=\"#ModifyMemberModalCenter\" onclick=\"person_modify(this)\">修改</button> <button class=\"btn btn-outline-dark\" title=\"修改人員資料\" data-toggle=\"modal\" data-target=\"#ModifyMemberPWDModalCenter\" onclick=\"person_modify_pwd(this)\">修改密碼</button>  <button class=\"btn btn-outline-dark\" style=\"margin-right: 10px;\" data-toggle=\"modal\" data-target=\"#InsertAuthority\" onclick=\"features_modify(this)\">修改權限</button>"),
                    "role_id"=>$user["role"],
                    "email"=>$user["email"],
                    "authority"=>$user_authority,
                ));
            }
            elseif($level=="2")
            {
                if(in_array ($user["person_id"] , $group_persons))
                {
                    array_push($rowdata,array(
                        "id"=>$user["id"],
                        "person_id"=>$user["person_id"],
                        "name"=>$user["name"],
                        "department"=>$user["department"],
                        "role"=>$user_role,
                        "on_board"=>$user["on_board"],
                        "username"=>$user["username"],
                        "modify"=>sprintf("<button class=\"btn btn-outline-dark\" title=\"修改人員資料\" data-toggle=\"modal\" data-target=\"#ModifyMemberModalCenter\" onclick=\"person_modify(this)\">修改</button> <button class=\"btn btn-outline-dark\" title=\"修改人員資料\" data-toggle=\"modal\" data-target=\"#ModifyMemberPWDModalCenter\" onclick=\"person_modify_pwd(this)\">修改密碼</button>"),
                        "role_id"=>$user["role"],
                        "email"=>$user["email"],
                        "authority"=>$user_authority,
                        "person_name"=>$person_name,
                        "department_name"=>$department_name,
                    ));
                }
            }
            else
            {
                if($user["id"]==$user_id){
                    array_push($rowdata,array(
                        "id"=>$user["id"],
                        "person_id"=>$user["person_id"],
                        "name"=>$user["name"],
                        "department"=>$user["department"],
                        "role"=>$user_role,
                        "on_board"=>$user["on_board"],
                        "username"=>$user["username"],
                        "modify"=>sprintf("<button class=\"btn btn-outline-dark\" title=\"修改人員資料\" data-toggle=\"modal\" data-target=\"#ModifyMemberModalCenter\" onclick=\"person_modify(this)\">修改</button> <button class=\"btn btn-outline-dark\" title=\"修改人員資料\" data-toggle=\"modal\" data-target=\"#ModifyMemberPWDModalCenter\" onclick=\"person_modify_pwd(this)\">修改密碼</button> "),
                        "role_id"=>$user["role"],
                        "email"=>$user["email"],
                        "authority"=>$user_authority,
                        "person_name"=>$person_name,
                        "department_name"=>$department_name,
                    ));
                }
            }

        }
        /*if($request->session()->has('Tusername')){
             $error_msg="有第一位登入者".$request->session()->get('lostring')."  "."第二個測試位置".$request->session()->get('Tusername');//測試登入者是否可以存進去session
        }else{"error_msg"=>$error_msg,
         $error_msg="沒有登入者";
        }*/
        $usermsg=$request->session()->get('Tusername');
//        foreach($rowdata as $user_auth)
//        {
//            if($user_auth["name"]==$usermsg)
//                $auth=$user_auth["role"];
//        }
//        if($auth!="經理")
//        {
//            $msg="身份不對";
//            return redirect()->route('AI')->with(["error_msg"=>$msg]);
//        }
//        dd($userroles);


        $features= array();
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/features/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 $feature) {
                array_push( $features, array(
                    "no" => $feature["no"],
                    "major_title" => $feature["major_title"],
                    "name" => $feature["name"],
                ));
            }
        }
//        dd($rowdata);
        if($msg!=null)
            return view("User",["title"=>"使用者管理","rowdata"=>$rowdata,"msg"=>$usermsg,"userroles"=>$userroles,"level"=>$level,"error_msg"=>$msg,"departments"=>$departments,"persons"=>$persons,'authority'=>$authority,'features'=>$features]);
        else
            return view("User",["title"=>"使用者管理","rowdata"=>$rowdata,"msg"=>$usermsg,"userroles"=>$userroles,"level"=>$level,"departments"=>$departments,"persons"=>$persons,'authority'=>$authority,'features'=>$features]);
        }

    //新增使用者
    public function insert_user(Request $request)
        {
//            $request->session()->all();
//            $username=$request->session()->get('Tusername');    //帳號
//            $role="";
//            $department="";
//            $level="";
//            [$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"];
//                }
//            }
//            if($department=="7")
//            {
//                $level="3";
//            }
//            elseif ($department=="6")
//            {
//                $level="4";
//            }
//            elseif ($role=="3")
//            {
//                $level="2";
//            }
//            elseif($role=="5")
//            {
//                $level="1";
//            }
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/user/insert", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
            "multipart",
            [
                [
                    'name' => "id",
                    "contents" => $request->user_id
                ],
                [
                    'name' => "person_id",
                    "contents" => $request->user_personid
                ],
                [
                    'name' => "name",
                    "contents" => $request->user_name
                ],
                [
                    'name' => "department",
                    "contents" => $request->user_department
                ],
                [
                    'name' => "role",
                    "contents" => $request->user_role
                ],
                [
                    'name' => "on_board",
                    "contents" => $request->user_onboard
                ],
                [
                    'name'=>"username",
                    "contents"=>$request->user_username
                ],
                [
                  'name'=>"password",
                  "contents"=>$request->user_password
                ],
                [
                    'name' => "email",
                    "contents" => $request->user_email
                ],
                ]);
        $jsondata = json_decode($res->getBody()->__toString(), true);
         $error=$jsondata["Message"];
         $msg=explode(" ",$error);
        if ($msg[1]=="is"){
            $error_msg="ID已有重複，新增失敗";
        }else{
            $error_msg="新增成功";
        }
            return redirect()->route('insert_user')->with(["error_msg" => $error_msg]);
    }
    //刪除使用者
    public function delete_user(Request $request){
             $request->session()->all();

             if($request->selectedId!=null) {
                 $client = new \GuzzleHttp\Client();
                 $error_ids=array();
                 $ids=explode(",",$request->selectedId);
                 foreach ($ids as $id){
                     $res=$client->request('POST',sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT"))."/user/delete",[
                         'form_params'=>[
                             "id"=>$id
                         ]
                     ]);
                     $jsondata=json_decode($res->getBody()->__toString(),true);
                     if($res->getStatusCode()!=200){
                         array_push($error_ids,$id);
                     }
                 }
                 if (count($error_ids)==0){
                     $msg="刪除成功";
                 }else{
                     $msg=$error_ids[0];
                     for ($i=1;$i<count($error_ids);$i++){
                         $msg=$msg.",".$error_ids[$i];
                     }
                     $msg=$msg."刪除失敗";
                 }
                 return redirect()->route('insert_user')->with(["error_msg" => $msg]);
             }else{
                 $msg="未選擇刪除人員";
                 return redirect()->route('insert_user')->with(["error_msg" => $msg]);
             }
         }
    //修改使用者
    public function post_modifyuser(Request $request)
    {
        $request->session()->all();
         //dd($request->all());
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/user/update", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
            "multipart",
            [
                [
                    'name' => "id",
                    "contents" => $request->modify_user_id
                ],
                [
                    'name' => "person_id",
                    "contents" => $request->modify_user_personid
                ],
                [
                    'name' => "name",
                    "contents" => $request->modify_user_name
                ],
                [
                    'name' => "department",
                    "contents" => $request->modify_user_department
                ],
                [
                    'name' => "role",
                    "contents" => $request->modify_user_role
                ],
                [
                    'name' => "on_board",
                    "contents" => $request->modify_user_onboard
                ],
//                [
//                    'name' => 'username',
//                    'contents' => $request->modify_username
//                ],
//                [
//                    'name' => 'password',
//                    'contents' => $request->modify_password
//
//                ],
                [
                    'name' => "email",
                    "contents" => $request->modify_user_email
                ],
            ]);
        return redirect()->route('insert_user');
    }
    //修改使用者密碼
    public function update_userpwd(Request $request)
    {
        $request->session()->all();
        //dd($request->all());
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/user/update/password", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
            "multipart",
            [
                [
                    'name' => "id",
                    "contents" => $request->modify_user_id
                ],
                [
                    'name' => 'username',
                    'contents' => $request->modify_username
                ],
                [
                    'name' => 'password',
                    'contents' => $request->modify_password

                ],
            ]);
        return redirect()->route('insert_user');
    }

    //搜尋使用者
    public function search_user(Request $request){
        $request->session()->all();
        $username=$request->session()->get('Tusername');    //帳號
        $role="";
        $department="";
        $level="";
        $user_id="";
        $person_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"];
                $person_id=$user["person_id"];
            }
        }
        if($role=="7")
        {
            $level="4";
        }
        elseif ($role=="3")
        {
            $level="3";
        }
        elseif ($role=="6")
        {
            $level="2";
        }
        elseif($role=="5")
        {
            $level="1";
        }
        //取得權限
        //取得權限
        $authority=array();
        $roles_auth=array();
        $users_auth=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);
        foreach ($jsondata["Data"] as $role_authority) {
            array_push( $roles_auth, array(
                "no" => $role_authority["no"],
                "role_id" => $role_authority["role_id"],
                "features_id" => $role_authority["features_id"],
            ));
            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);
        foreach ($jsondata["Data"] as $user_authority) {
            array_push( $users_auth, array(
                "no" => $user_authority["no"],
                "user_id" => $user_authority["user_id"],
                "features_id" => $user_authority["features_id"],
            ));
            if($user_authority["user_id"]==$user_id)
            {
                array_push( $authority, array(
//                    "no" => $user_authority["no"],
                    "features_id" => $user_authority["features_id"],
                ));
            }
        }

        $departments= array();
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/department/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 $department_1) {
                array_push( $departments, array(
                    "no" => $department_1["no"],
                    "department" => $department_1["department"],
                ));
            }
        }
        $persons= array();
        [$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( $persons, array(
                    "id" => $person["ID"],
                    "name" => $person["Name"],
                ));
            }
        }

        $group_id="";
        $person_group_relation=array();
        $group_persons=array();
        [$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);
        if($jsondata["Data"] !=null)
        {
            foreach ($jsondata["Data"] as $person_group) {
                array_push( $person_group_relation, array(
                    "person_id" => $person_group["PersonID"],
                    "group_id" => $person_group["PersonGroupID"],
                ));
                if($person_group["PersonID"]==$person_id)
                {
                    $group_id=$person_group["PersonGroupID"];
                }
            }
            foreach ($person_group_relation as $person_group_1) {
                if($person_group_1["group_id"]==$group_id)
                {
                    array_push( $group_persons,$person_group_1["person_id"]);
                }
            }
        }

        $userroles= array();
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/user/role/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) {
                array_push( $userroles, array(
                    "id" => $role["id"],
                    "name" => $role["name"],
                ));
            }
        }

        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/user/all",env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")),"POST");
        $jsondata=json_decode($res->getBody()->__toString(),true);
        $rowdata=array();
        foreach ($jsondata["Data"] as $user) {
            foreach ($userroles as $userrole){
                switch ($user["role"]){
                    case $userrole["id"]:
                        $user_role=$userrole["name"];
                        break;
                    default:
                        break;
                }
            }
            $user_authority="";
            foreach ($roles_auth as $role_auth)
            {
                if($user["role"]==$role_auth["role_id"])
                {
                    $user_authority=$user_authority.",".$role_auth["features_id"];
                }
            }
            foreach($users_auth as $user_auth)
            {
                if($user["id"]==$user_auth["user_id"])
                {
                    $user_authority=$user_authority.",".$user_auth["features_id"];
                }
            }
            if (!$request->search_text ==null){
                switch ($request->search_type){
                    // ID
                    case 1:
                        if(count(explode($request->search_text,$user["username"]))<2){
                            // no match
                            continue 2;
                        }
                        break;
                    // 姓名
                    case 2:
                        if(count(explode($request->search_text,$user_role))<2){
                            // no match
                            continue 2;
                        }
                        break;
                    // 類別
                    case 3:
                        if(count(explode($request->search_text,$user["name"]))<2){
                            // no match
                            continue 2;
                        }
                        break;
                    // 未選擇
                    default:
                        break;
                }
            }
            $person_name="";
            foreach($persons as $person)
            {
                if($person["id"]==$user["person_id"])
                {
                    //dd($person["name"]);
                    $person_name=$person["name"];
                }
            }
            $department_name="";
            foreach($departments as $department_2)
            {
                if($department_2["no"]==$user["department"])
                {
                    $department_name=$department_2["department"];
                }
            }
            if($level =="4" || $level =="3"){
                array_push($rowdata,array(
                    "id"=>$user["id"],
                    "person_id"=>$user["person_id"],
                    "name"=>$user["name"],
                    "department"=>$user["department"],
                    "role"=>$user_role,
                    "on_board"=>$user["on_board"],
                    "username"=>$user["username"],
                    "modify"=>sprintf("<button class=\"btn btn-outline-dark\" title=\"修改人員資料\" data-toggle=\"modal\" data-target=\"#ModifyMemberModalCenter\" onclick=\"person_modify(this)\">修改</button> <button class=\"btn btn-outline-dark\" title=\"修改人員資料\" data-toggle=\"modal\" data-target=\"#ModifyMemberPWDModalCenter\" onclick=\"person_modify_pwd(this)\">修改密碼</button>  <button class=\"btn btn-outline-dark\" style=\"margin-right: 10px;\" data-toggle=\"modal\" data-target=\"#InsertAuthority\" onclick=\"features_modify(this)\">修改權限</button>"),
                    "role_id"=>$user["role"],
                    "email"=>$user["email"],
                    "authority"=>$user_authority,
                ));
            }
            elseif($level=="2")
            {
                if(in_array ($user["person_id"] , $group_persons))
                {
                    array_push($rowdata,array(
                        "id"=>$user["id"],
                        "person_id"=>$user["person_id"],
                        "name"=>$user["name"],
                        "department"=>$user["department"],
                        "role"=>$user_role,
                        "on_board"=>$user["on_board"],
                        "username"=>$user["username"],
                        "modify"=>sprintf("<button class=\"btn btn-outline-dark\" title=\"修改人員資料\" data-toggle=\"modal\" data-target=\"#ModifyMemberModalCenter\" onclick=\"person_modify(this)\">修改</button> <button class=\"btn btn-outline-dark\" title=\"修改人員資料\" data-toggle=\"modal\" data-target=\"#ModifyMemberPWDModalCenter\" onclick=\"person_modify_pwd(this)\">修改密碼</button>"),
                        "role_id"=>$user["role"],
                        "email"=>$user["email"],
                        "authority"=>$user_authority,
                        "person_name"=>$person_name,
                        "department_name"=>$department_name,
                    ));
                }
            }
            else
            {
                if($user["id"]==$user_id){
                    array_push($rowdata,array(
                        "id"=>$user["id"],
                        "person_id"=>$user["person_id"],
                        "name"=>$user["name"],
                        "department"=>$user["department"],
                        "role"=>$user_role,
                        "on_board"=>$user["on_board"],
                        "username"=>$user["username"],
                        "modify"=>sprintf("<button class=\"btn btn-outline-dark\" title=\"修改人員資料\" data-toggle=\"modal\" data-target=\"#ModifyMemberModalCenter\" onclick=\"person_modify(this)\">修改</button> <button class=\"btn btn-outline-dark\" title=\"修改人員資料\" data-toggle=\"modal\" data-target=\"#ModifyMemberPWDModalCenter\" onclick=\"person_modify_pwd(this)\">修改密碼</button> "),
                        "role_id"=>$user["role"],
                        "email"=>$user["email"],
                        "authority"=>$user_authority,
                        "person_name"=>$person_name,
                        "department_name"=>$department_name,
                    ));
                }
            }
        }
        $usermsg=$request->session()->get('Tusername');


        $features= array();
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/features/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 $feature) {
                array_push( $features, array(
                    "no" => $feature["no"],
                    "major_title" => $feature["major_title"],
                    "name" => $feature["name"],
                ));
            }
        }
        return view("User",["title"=>"使用者管理","rowdata"=>$rowdata,"msg"=>$usermsg,"userroles"=>$userroles,"level"=>$level,"departments"=>$departments,"persons"=>$persons,'authority'=>$authority,'features'=>$features]);
    }

    //匯出申請表
    public function user_word(Request $request)
    {
        $request->session()->all();
        $name="";
        $department_id="";
        $department="";
        $email="";
        $date=date("Y/m/d");
        $username=$request->session()->get('Tusername');    //帳號
        [$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)
            {
                $name=$user["name"];
                $department_id=$user["department"];
                $email=$user["email"];
            }
        }
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/department/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 $departments) {
                if($department_id==$departments["no"])
                {
                    $department=$departments["department"];
                }
            }
        }
        $filename = sprintf("../storage/export/申請單%s.docx", $name);
        $file = fopen($filename, 'w');
        $client = new \GuzzleHttp\Client();
        $res = $client->request('POST', sprintf("http://%s:%s/user/insertword", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), [
            'multipart' => [
                [
                    'name'=>"name",
                    "contents"=>$name
                ],
                [
                    'name'=>"department",
                    "contents"=>$department
                ],
                [
                    'name'=>"email",
                    "contents"=>$email
                ],
                [
                    'name'=>"date",
                    "contents"=>$date
                ],
                [
                    'name'=>"username",
                    "contents"=>$username
                ],
            ],
            'save_to' => $file
        ]);
        return response()->download($filename);

    }
    //首頁註冊(包含匯出word)--沒用
    public function insert_user_word(Request $request)
    {

//        dd($request);

        $request->session()->all();
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/user/insert", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
            "multipart",
            [
                [
                    'name' => "id",
                    "contents" => $request->user_id
                ],
                [
                    'name' => "person_id",
                    "contents" => $request->user_personid
                ],
                [
                    'name' => "name",
                    "contents" => $request->user_name
                ],
                [
                    'name' => "department",
                    "contents" => $request->user_department
                ],
                [
                    'name' => "role",
                    "contents" => $request->user_role
                ],
                [
                    'name' => "on_board",
                    "contents" => $request->user_onboard
                ],
                [
                    'name'=>"username",
                    "contents"=>$request->user_username
                ],
                [
                    'name'=>"password",
                    "contents"=>$request->user_password
                ],
                [
                    'name' => "email",
                    "contents" => $request->user_email
                ],
            ]);
        $jsondata = json_decode($res->getBody()->__toString(), true);
        $error = $jsondata["Message"];
        $msg = explode(" ", $error);
        if ($msg[1] == "is") {
            $error_msg = "ID已有重複，新增失敗";
            return $this->index_insert($request)->with(["error_msg" => $error_msg]);
        } else {
            $error_msg = "新增成功";
        }
        $department = $request->user_department;
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/department/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 $depart) {
                if($department==$depart["no"])
                {
                    $department=$depart["department"];
                }
            }
        }
        //匯出
        date_default_timezone_set('Asia/Taipei');
        $name = $request->user_name;
        $job = $request->user_job;
//        $department = $request->user_department;
        $email = $request->user_email;
        $phone = $request->user_phone;
        $date = date("Y-m-d");
        $username = $request->user_username;

        $filename = sprintf("../storage/export/申請單%s.docx", $name);
        $file = fopen($filename, 'w');
        $client = new \GuzzleHttp\Client();
        $res = $client->request('POST', sprintf("http://%s:%s/user/insertword", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), [
                'multipart' => [
                    [
                        'name'=>"name",
                        "contents"=>$name
                    ],
                    [
                        'name'=>"job",
                        "contents"=>$job
                    ],
                    [
                        'name'=>"department",
                        "contents"=>$department
                    ],
                    [
                        'name'=>"email",
                        "contents"=>$email
                    ],
                    [
                        'name'=>"phone",
                        "contents"=>$phone
                    ],
                    [
                        'name'=>"date",
                        "contents"=>$date
                    ],
                    [
                        'name'=>"username",
                        "contents"=>$username
                    ],
                ],
                'save_to' => $file
            ]);
            return response()->download($filename);
    }
    //修改使用者權限
    public function insert_user_features(Request $request)
    {
//        dd($request->all());
        $new_authority=$request->all();
        //dd($r);
        $role="";
        [$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["id"]==$request->features_user)
            {
                $role=$user["role"];
            }
        }

        //取得舊權限
        $old_authority=array();
        $users_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);
        foreach ($jsondata["Data"] as $role_authority) {
            if($role_authority["role_id"] == $role)
            {
                array_push( $old_authority, $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) {
                array_push( $users_authority, array(
                    "no" => $user_authority["no"],
                    "user_id" => $user_authority["user_id"],
                    "features_id" => $user_authority["features_id"],
                ));
                if($user_authority["user_id"] == $request->features_user)
                {
                    array_push( $old_authority,$user_authority["features_id"]);
                }
            }
        }

        $i_auth=array();
        $d_auth=array();
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/features/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 $feature) {
                //新增
                if(! in_array ( $feature["no"] , $old_authority))
                {
                    if(in_array ( $feature["no"] , $new_authority))
                    {
                        array_push( $i_auth, array(
                            "no" => $feature["no"],
                            "major_title" => $feature["major_title"],
                            "name" => $feature["name"],
                        ));
                    }
                }
                //刪除
                if(in_array ( $feature["no"] , $old_authority))
                {
                    if(!in_array ( $feature["no"] , $new_authority))
                    {
                        array_push( $d_auth, array(
                            "no" => $feature["no"],
                            "major_title" => $feature["major_title"],
                            "name" => $feature["name"],
                        ));
                    }
                }
            }
        }
        //dd($d_auth);

        foreach($i_auth as $insert)
        {
            [$ret, $res] = $this->request_server(sprintf("http://%s:%s/features/user/relation/insert", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
                "multipart",
                [
                    [
                        'name' => "user_id",
                        "contents" => $request->features_user
                    ],
                    [
                        'name' => "features_id",
                        "contents" => $insert["no"]
                    ],
                ]);
        }

        foreach($d_auth as $delete)
        {
            foreach ($users_authority as $user_authority)
            {
                if($user_authority["user_id"]==$request->features_user and $user_authority["features_id"]==$delete["no"])
                {
//                    dd( $user_authority);
                    [$ret, $res] = $this->request_server(sprintf("http://%s:%s/features/user/relation/delete", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
                        "multipart",
                        [
                            [
                                'name' => "no",
                                "contents" => $user_authority["no"]
                            ],
                        ]);
                }
            }

        }

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



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