<?php

namespace App\Http\Controllers;

use App\E3SCamera;
use App\Person;
use Faker\Provider\Image;
use GuzzleHttp\Exception\RequestException;
use http\Exception\RuntimeException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use mysql_xdevapi\Exception;
use phpDocumentor\Reflection\Types\Null_;
use PhpOption\None;
use function GuzzleHttp\Promise\all;

class PersonController extends Controller
{

    private $influxdb="http://192.168.5.17:8086";
    private $imgserver="http://192.168.5.185:8000";

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


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

        // 取得人員資料
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/person/select/all", env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"GET");
        $jsondata=json_decode($res->getBody()->__toString(),true);
        $rowdata=array();
        if($jsondata["Data"] !=null){
            foreach ($jsondata["Data"] as $person) {
                switch ($person["Type"]){
                    case 1:
                        $person_type="黑名單";
                        break;
                    case 2:
                        $person_type="白名單";
                        break;
                    case 3:
                        $person_type="VIP";
                        break;
                    default:
                        $person_type="訪客";
                        break;
                }
                $enabled="";
                if($person["Enabled"])
                    $enabled="V";
                else
                    $enabled="";
                array_push($rowdata,array(
    //                "img"=>sprintf("<img class='faceimg' src='%s/person/%s'>",sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")), $person["Photo"]),
                    "img"=>sprintf("<img class='faceimg' src='/get/image?img_path=/person/%s'>", $person["ID"]),
                    "id"=>$person["ID"],
                    "group"=>$person_type,
                    "name"=>$person["Name"],
                    "allow_camera"=>" ",
                    "modify"=>sprintf("<button class=\"btn btn-outline-dark\" title=\"修改人員資料\" data-toggle=\"modal\" data-target=\"#ModifyMemberModalCenter\" onclick=\"person_modify(this)\">修改</button>"),
                    "sex"=>$person["Sex"],
                    "enabled"=>$enabled,
                    "start"=>$person["Start"],
                    "end"=>$person["End"],
                    "token"=>$person["Token"],
                ));
            }
        }

        //取得人員群組資料
        $person_groups = array();
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/group/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
        $jsondata = json_decode($res->getBody()->__toString(), true);
        if($jsondata["Data"] != null){
            foreach ($jsondata["Data"] as $person_group) {
                array_push($person_groups, array(
                    "id" => $person_group["ID"],
                    "name" => $person_group["Name"],
                ));
            }
        }

//dd($groups_rows);
//         dd($jsondata);
        if($msg!=null){
            return view("Person",["title"=>"人員管理","rowdata"=>$rowdata,"error_msg"=>$msg,"person_groups"=>$person_groups,"level"=>$level,'authority'=>$authority]);
        }else{
            return view("Person",["title"=>"人員管理","rowdata"=>$rowdata,"person_groups"=>$person_groups,"level"=>$level,'authority'=>$authority]);
        }
    }

    //匯入檔案
    public function files(Request $request)
    {
            $client = new \GuzzleHttp\Client();
            $con_path=storage_path('app/');
            if($request->hasFile('excel')){
                if ($request->file('excel')->getClientOriginalExtension()=="xlsx"){
                    $path=$request->file('excel')->store('excel');
                    $res=$client->request('POST',sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT"))."/person/insert/excel",[
                            'multipart'=>[
                                [
                                    'name'=>'excel',
                                    'contents'=>fopen($con_path.$path,'r')
                                ],
                            ]
                        ]);
                         $jsondata=json_decode($res->getBody()->__toString(),true);
                //dd($files);
                    unlink($con_path.$path); //刪除檔案
                    $msg=$jsondata["Message"];
                    if($msg=="File format error"){
                        $insert_msg="匯入失敗，檔案格式錯誤";
                        return redirect()->route('person')>with(["error_msg"=>$insert_msg]);
                    }
                    $insert=array();
                    $insert= explode(' person ', $msg);
                    $fail=array();
                    $fail=explode('inserted, ', $insert[1]);
                    $failname=array();
                    $failname=explode('insert failed, ', $insert[2]);
                    if($fail[1]=="0") {
                        $insert_msg="$insert[0]人新增成功";
                    }elseif($insert[0]=="0"){
                        $insert_msg="$fail[1]人新增失敗：$failname[1]";
                    }else{
                        $insert_msg="$insert[0]人新增成功，$fail[1]人新增失敗：$failname[1]";
                    }
                    return redirect()->route('person')->with(["msg" => $insert_msg]);
//                    return $this->index()->with(["error_msg"=>$insert_msg]);
                }else{
                    $msg="未匯入成功，錯誤為檔案不是execl檔";
                    return redirect()->route('person')->with(["msg" => $msg]);
//                    return $this->index()->with(["error_msg"=>$msg]);
                }
            }else{
                $msg="未匯入成功，錯誤為未選擇檔案";
                return redirect()->route('person')->with(["msg" => $msg]);
//                return $this->index()->with(["error_msg"=>$msg]);
            }
            /*
            try{ }catch (\Exception $e){
            if ($e->getResponse()->getStatusCode() == '400') {

                $msg="就是400";
                return $this->index()->with(["error_msg"=>$msg]);
            }
        }*/

    }


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


        // 取得人員資料
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/person/select/all" ,env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"GET");
        $jsondata=json_decode($res->getBody()->__toString(),true);
        $rowdata=array();
        if($jsondata["Data"] !=null) {
            foreach ($jsondata["Data"] as $person) {
                switch ($person["Type"]) {
                    case 1:
                        $person_type = "黑名單";
                        break;
                    case 2:
                        $person_type = "白名單";
                        break;
                    case 3:
                        $person_type = "VIP";
                        break;
                    default:
                        $person_type = "訪客";
                        break;
                }

                // 搜尋類別
                if (!$request->search_text == null) {
                    switch ($request->search_type) {
                        // ID
                        case 1:
                            if (count(explode($request->search_text, $person["ID"])) < 2) {
                                // no match
                                continue 2;
                            }
                            break;
                        // 姓名
                        case 2:
                            if (count(explode($request->search_text, $person["Name"])) < 2) {
                                // no match
                                continue 2;
                            }
                            break;
                        // 類別
                        case 3:
                            if (count(explode($request->search_text, $person_type)) < 2) {
                                // no match
                                continue 2;
                            }
                            break;
                        // 未選擇
                        default:
                            break;
                    }
                }

                array_push($rowdata, array(
//                    "img" => sprintf("<img class='faceimg' src='%s/person/%s'>", sprintf("http://%s:%s", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), $person["Photo"]),
                    "img" => sprintf("<img class='faceimg' src='/get/image?img_path=/person/%s'>", $person["Photo"]),
                    "id" => $person["ID"],
                    "group" => $person_type,
                    "sex"=>$person["Sex"],
                    "name" => $person["Name"],
                    "allow_camera" => " ",
                    "modify"=>sprintf("<button class=\"btn btn-outline-dark\" title=\"修改人員資料\" data-toggle=\"modal\" data-target=\"#ModifyMemberModalCenter\" onclick=\"person_modify(this)\">修改</button>"),
                ));
            }
        }
        if(count($rowdata)==0){
            $msg="查無結果";
        }
//dd($rowdata);
        //取得人員群組資料
        $person_groups = array();
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/group/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
        $jsondata = json_decode($res->getBody()->__toString(), true);
        if($jsondata["Data"] != null){
            foreach ($jsondata["Data"] as $person_group) {
                array_push($person_groups, array(
                    "id" => $person_group["ID"],
                    "name" => $person_group["Name"],
                ));
            }
        }
        if($msg!=null){
            return view("Person",["title"=>"人員管理","rowdata"=>$rowdata,"error_msg"=>$msg,"person_groups"=>$person_groups,"level"=>$level,'authority'=>$authority]);
        }else{
            return view("Person",["title"=>"人員管理","rowdata"=>$rowdata,"person_groups"=>$person_groups,"level"=>$level,'authority'=>$authority]);
        }
    }

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


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

        $export = array("In"=>"08:30", "Out"=>"17:30", "LunchBreak"=>60);
        //取得人員群組資料
        $person_groups = array();
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/group/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
        $jsondata = json_decode($res->getBody()->__toString(), true);
        if($jsondata["Data"] != null){
            foreach ($jsondata["Data"] as $person_group) {
                array_push($person_groups, array(
                    "id" => $person_group["ID"],
                    "name" => $person_group["Name"],
                ));
            }
        }
        if($msg!=null){
            return view("Person_Attendance",["title"=>"出勤管理","export_arg"=>$export,"error_msg"=>$msg,"person_groups"=>$person_groups,"level"=>$level,'authority'=>$authority]);
        }else{
            return view("Person_Attendance",["title"=>"出勤管理","export_arg"=>$export,"person_groups"=>$person_groups,"level"=>$level,'authority'=>$authority]);
        }
    }


    // 舊的 棄用 取得區間內出勤考核狀態
    public function post_attendance_old(Request $request)
    {
        date_default_timezone_set('Asia/Taipei');
        $stime="'".$request->start_time."T00:00:00Z'";
        $etime="'".$request->end_time."T00:00:00Z'";
        $tz="'Asia/Taipei'";
        $client = new \GuzzleHttp\Client();
        $res = $client->request('GET', $this->influxdb.'/query?q=select+*+from+rd01+where+time+>='.$stime.'and+time+<'.$etime.'tz('.$tz.')'.'&db=FACE');
        // 將json string 轉換成 array
        $jsondata=json_decode($res->getBody()->__toString(),true);
        if(!isset($jsondata["results"][0]["series"])){
            // 判斷是否有結果
            // 否回傳查無結果
            // 取得所有設備資訊
            // $devices_info=$this->get_all_device();
            // 取得攝影機群組與清單
            // $groups=$devices_info[0];
            // $camera_list=$devices_info[1];
            $devices = array();
            $groups = array();
            $camera_list = array();
            //        return $camera_list["RD"];
            return view("Person_Attendance",["title"=>"人員管理","groups"=>$groups,"camera_list"=>$camera_list,"error_msg"=>"查無結果"]);
        }
        $columns=$jsondata["results"][0]["series"][0]["columns"];
        $values=$jsondata["results"][0]["series"][0]["values"];
        $index_time=array_search("time",$columns);
        $index_id=array_search("id",$columns);
        $index_ip=array_search("ip",$columns);
        $index_snapshot=array_search("snapshot",$columns);
//        整理後之array
//        格式如下
//        {
//            "RD001":{
//                "2020-01-01":{
//                    "stime":"08:01:00",
//                    "etime":"22:00:05"
//                },
//                ..........
//           }
//        }
        $results=array();
        foreach ($values as $value){
            // 遇到Unknow跳過
            if($value[$index_id]=="Unknow"){
                continue;
            }
            if(array_key_exists($value[$index_id],$results)){
                // 判斷是否有此人的資料
                // 時間日期切割轉換
                $datetime=date("Y-m-d H:i:s",strtotime($value[$index_time]));
                $day=explode(" ",$datetime)[0];
                $time=explode(" ",$datetime)[1];
                if(array_key_exists($day,$results[$value[$index_id]])){
                    // 判斷是否有此日期的資料
                    if(strtotime($time) < strtotime($results[$value[$index_id]][$day]['stime'])){
                        // 與已存在日期比較時間
                        // 判斷是否小於當前stime
                        // 是即更新stime
                        $results[$value[$index_id]][$day]['stime']=$time;
                    }
                    if(strtotime($time) > strtotime($results[$value[$index_id]][$day]['etime'])){
                        // 與已存在日期比較時間
                        // 判斷是否大於當前etime
                        // 是即更新etime
                        $results[$value[$index_id]][$day]['etime']=$time;
                    }
                }else{
                    // 否即建立一筆
                    $results[$value[$index_id]][$day]=array(
                      "stime"=>$time,
                      "etime"=>$time
                    );
                }
            }else{
                // 否先建立一筆
                // 時間日期切割轉換
                $datetime=date("Y-m-d H:i:s",strtotime($value[$index_time]));
                $day=explode(" ",$datetime)[0];
                $time=explode(" ",$datetime)[1];
                $results[$value[$index_id]]=array(
                    $day=>array(
                        "stime"=>$time,
                        "etime"=>$time
                    )
                );
            }
        }
//        dd(array_keys($results));
        // 計算加班時間
        $attendance=array();
        foreach (array_keys($results) as $id){
            foreach (array_keys($results[$id]) as $day){
                $wsecond=strtotime($results[$id][$day]["etime"])-strtotime($results[$id][$day]["stime"]);
                $other="";
                if(strtotime($results[$id][$day]["stime"])>strtotime("08:31:00")){
                    // 遲到判斷
                    $other.="遲到 ";
                }
                if(strtotime($results[$id][$day]["etime"])<strtotime("17:30:00")){
                    // 早退到判斷
                    $other.="早退 ";
                }
                $otime="";
                if(strtotime($results[$id][$day]["etime"])>strtotime("17:31:00")){
                    // 判斷是否加班
                    // 加班時數計算
                    $over=strtotime($results[$id][$day]["etime"])-strtotime("17:31:00");
                    // 轉換為小時
                    $otime=floor($over/3600);
                    if(($over/ 60 % 60)>= 15 and ($over/ 60 % 60)<45){
                        $otime+=0.5;
                    }elseif(($over/ 60 % 60)>=45){
                        $otime+=1;
                    }
                    $otime.=" 小時";

                }
                array_push($attendance,array(
                    "day"=>$day,
                    "id"=>$id,
                    "stime"=>$results[$id][$day]["stime"],
                    "etime"=>$results[$id][$day]["etime"],
                    "wtime"=>sprintf('%02d:%02d:%02d', ($wsecond/ 3600),($wsecond/ 60 % 60), $wsecond% 60),
                    "otime"=>$otime,
                    "other"=>$other,
                ));
            }
        }
//        dd(json_encode($attendance,false));
        // 取得所有設備資訊
        // $devices_info=$this->get_all_device();
        // 取得攝影機群組與清單
        // $groups=$devices_info[0];
        // $camera_list=$devices_info[1];
        $devices = array();
        $groups = array();
        $camera_list = array("Enabled"=>array());

        // 取得 Device 資料
        $client = new \GuzzleHttp\Client();
        $res = $client->request('GET', sprintf("http://%s:%s/device/select/all",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")));
        $jsondata = json_decode($res->getBody()->__toString(),true);
        foreach ($jsondata["Data"] as $device) {
            if ($device["Location"] == "") {
                $name = $device["ID"];
            }
            else {
                $name = $device["Location"];
            }
            array_push($camera_list["Enabled"],array(
                "id"=>$device["ID"],
                "name"=>$name,
            ));
        }
        array_push($groups, array("group"=> "Enabled"));

        //        return $camera_list["RD"];
        return view("Person_Attendance",["title"=>"人員管理","groups"=>$groups,"camera_list"=>$camera_list,"rowdata"=>$attendance]);
    }

    // 取得區間內出勤考核狀態
    public function post_attendance(Request $request)
    {
        // request回調
        session()->flashInput($request->input());

        $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)
            {
                $person_id=$user["person_id"];
                $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"],
                    ));
                }
            }
        }


        $group_id=$request->groupid;
        $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"]);
                }
            }
        }
        date_default_timezone_set('Asia/Taipei');
//        $stime=$request->start_time." 00:00:00";
//        $etime=$request->end_time." 23:59:59";
        $stime=$request->start_time;
        $etime=$request->end_time;
        $time_in=explode(":",$request->time_in);
        $time_out=explode(":",$request->time_out);
        $time_break=$request->time_break;
        if(count($time_in)!=2 or count($time_out)!=2){
            return redirect()->route("attendance");
        }
        //取得人員群組資料
        $person_groups = array();
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/group/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
        $jsondata = json_decode($res->getBody()->__toString(), true);
        if($jsondata["Data"] != null){
            foreach ($jsondata["Data"] as $person_group) {
                array_push($person_groups, array(
                    "id" => $person_group["ID"],
                    "name" => $person_group["Name"],
                ));
            }
        }
        $tz="'Asia/Taipei'";
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/punch/card/record",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"POST","form_params",
            [
                "start"=>$stime,
                "end"=>$etime,
                "inHour"=>$time_in[0],
                "inMinute"=>$time_in[1],
                "outHour"=>$time_out[0],
                "outMinute"=>$time_out[1],
                "lunchBreak"=>$time_break
            ]);
        $jsondata=json_decode($res->getBody()->__toString(),true);
        if ($jsondata['Data']==null){
            $error_msg="查無資料";
            return redirect()->route('attendance')->with(["error_msg"=>$error_msg,"person_groups"=>$person_groups]);
//            return $this->attendance_index($request)->with(["error_msg"=>$error_msg,"person_groups"=>$person_groups]);
        }

        // 轉換成 boostrap-table js格式
        $attendance=array();
        foreach (array_keys($jsondata['Data']) as $id){
            // 判斷是否為群組搜尋
            if(!is_null($request->groupid) and !in_array($id,$group_persons))
            {
                continue ;
            }
            // 判斷是否帶字串搜尋
            if(!is_null($request->search_text) and !str_contains($id, $request->search_text))
            {
                continue ;
            }
            // 獲取人員名單
            [$ret,$res]=$this->request_server(sprintf("http://%s:%s/person/select/%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT"),$id),"GET");
            $person_list_json=json_decode($res->getBody()->__toString(),true);
            
            foreach (array_keys($jsondata['Data'][$id]) as $day){
                $remark="";
                // 指定類別
                switch ($request->search_type){
                    // 遲到
                    case "late":
                        if ($jsondata['Data'][$id][$day]["WorkBeLate"]==0){
                            // no match
                            continue 2;
                        }
                        break;
                    // 早退
                    case "early":
                        if ($jsondata['Data'][$id][$day]["WorkLeaveEarlier"]==0){
                            // no match
                            continue 2;
                        }
                        break;
                    // 加班
                    case "over":
                        if ($jsondata['Data'][$id][$day]["Over"]==0){
                            // no match
                            continue 2;
                        }
                        break;
                    // 未出席
                    case "noarrived":
                        if ($jsondata['Data'][$id][$day]["Start"]["Time"] != null){
                            // no match
                            continue 2;
                        }
                        $remark="未出席";
                        break;
                    default:
                        break;
                }
                $over=sprintf("%02d:%02d:%02d",$jsondata['Data'][$id][$day]["Over"]*60 / 60,$jsondata['Data'][$id][$day]["Over"]*60 % 60,0);
                $late=sprintf("%02d:%02d:%02d",$jsondata['Data'][$id][$day]["WorkBeLate"] / 60,$jsondata['Data'][$id][$day]["WorkBeLate"] % 60,0);
                $early=sprintf("%02d:%02d:%02d",$jsondata['Data'][$id][$day]["WorkLeaveEarlier"] / 60,$jsondata['Data'][$id][$day]["WorkLeaveEarlier"] % 60,0);

                // 只打卡一次過濾下班時間
                if ($jsondata['Data'][$id][$day]["Start"]["Time"]==$jsondata['Data'][$id][$day]["End"]["Time"]){
                    $etime=null;
                }else{
                    $etime=$jsondata['Data'][$id][$day]["End"]["Time"];
                }
                if($level=="2")
                {
                    if(in_array ($id , $group_persons))
                    {
                        array_push($attendance,array(
                            "day" =>$day,
                            "name" =>$person_list_json["Data"]["Name"],
//                    "img"=>sprintf("<img class='faceimg' src='%s/person/%s'>", sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),$id),
                            "img"=>sprintf("<img class='faceimg' src='/get/image?img_path=/person/%s'>",$id),
                            "id"=>$id,
                            "stime"=>$jsondata['Data'][$id][$day]["Start"]["Time"],
                            "etime"=>$etime,
                            "over"=>$over,
                            "late"=>$late,
                            "early"=>$early,
                            "remarks"=>$remark
                        ));
                    }
                }
                else
                {
                    array_push($attendance,array(
                        "day" =>$day,
                        "name" =>$person_list_json["Data"]["Name"],
//                    "img"=>sprintf("<img class='faceimg' src='%s/person/%s'>", sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),$id),
                        "img"=>sprintf("<img class='faceimg' src='/get/image?img_path=/person/%s'>",$id),
                        "id"=>$id,
                        "stime"=>$jsondata['Data'][$id][$day]["Start"]["Time"],
                        "etime"=>$etime,
                        "over"=>$over,
                        "late"=>$late,
                        "early"=>$early,
                        "remarks"=>$remark
                    ));
                }


            }
        }
        $export = array("In"=>"08:30", "Out"=>"17:30", "LunchBreak"=>60);

        return view("Person_Attendance",["title"=>"出勤管理", "export_arg"=>$export,"rowdata"=>$attendance,"person_groups"=>$person_groups,"level"=>$level,'authority'=>$authority]);
    }

    // Export 出勤考核狀態
    public function post_attendance_download(Request $request)
    {
//        dd($request->all())
//        return $request->all();
        // 取得所有設備資訊
        // $devices_info=$this->get_all_device();
        // 取得攝影機群組與清單
        // $groups=$devices_info[0];
        // $camera_list=$devices_info[1];
        $devices = array();
        $groups = array();
        $camera_list = array("Enabled"=>array());

        // 取得 Device 資料
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/device/select/all",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"GET");
        $jsondata = json_decode($res->getBody()->__toString(),true);
        if($jsondata["Data"] !=null)
        {
            foreach ($jsondata["Data"] as $device) {
                if ($device["Location"] == "") {
                    $name = $device["ID"];
                }
                else {
                    $name = $device["Location"];
                }
                array_push($camera_list["Enabled"],array(
                    "id"=>$device["ID"],
                    "name"=>$name,
                ));
            }
            array_push($groups, array("group"=> "Enabled"));
        }


        // request post to api
        $date = $request->export_date;
        list($y, $m) = explode('-', $date);
        $time = $request->export_time_in;
        list($in_hour, $in_minute) = explode(':', $time);
        $time = $request->export_time_out;
        list($out_hour, $out_minute) = explode(':', $time);
        $client = new \GuzzleHttp\Client();
        $filename = sprintf("../storage/export/%s.xlsx", $date);
        $file = fopen($filename, 'w');
        $group_id=$request->choses_group;

        $client = new \GuzzleHttp\Client();
        if ( $group_id!=null){
            $res=$client->request('POST', sprintf("http://%s:%s/punch/card/record/group/%s/%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT"), $y, $m),[
                'form_params'=>[
                    'InHour'=>$in_hour,
                    'InMinute'=>$in_minute,
                    'OutHour'=>$out_hour,
                    'OutMinute'=>$out_minute,
                    'LunchBreak'=>$request->export_time_break,
                    'GroupId'=> $group_id
                ],
                'save_to' => $file
            ]);
            return response()->download($filename);
        }else{
            $res=$client->request('POST', sprintf("http://%s:%s/punch/card/record/%s/%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT"), $y, $m),[
                'form_params'=>[
                    'InHour'=>$in_hour,
                    'InMinute'=>$in_minute,
                    'OutHour'=>$out_hour,
                    'OutMinute'=>$out_minute,
                    'LunchBreak'=>$request->export_time_break
                ],
                'save_to' => $file
            ]);
            return response()->download($filename);
        }


    }

    //圖表呈現
    public function graph_attendance(Request $request)
    {
        $request->session()->all();
        $username=$request->session()->get('Tusername');    //帳號
        $role="";
        $department="";
        $level="";
        $user_id="";
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/user/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")),"POST");
        $jsondata=json_decode($res->getBody()->__toString(),true);
        foreach ($jsondata["Data"] as $user) {
            if($user["username"]==$username)
            {
                $role=$user["role"];
                $department=$user["department"];
                $user_id=$user["id"];
            }
        }
        if($role=="7")
        {
            $level="4";
        }
        elseif ($role=="3")
        {
            $level="3";
        }
        elseif ($role=="6")
        {
            $level="2";
        }
        elseif($role=="5")
        {
            $level="1";
        }
        //取得權限
        $authority=array();
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/features/role/relation/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")),"POST");
        $jsondata=json_decode($res->getBody()->__toString(),true);
        if($jsondata["Data"] !=null)
        {
            foreach ($jsondata["Data"] as $role_authority) {
                if($role_authority["role_id"]==$role)
                {
                    array_push( $authority, array(
//                    "no" => $role_authority["no"],
                        "features_id" => $role_authority["features_id"],
                    ));
                }
            }
        }
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/features/user/relation/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")),"POST");
        $jsondata=json_decode($res->getBody()->__toString(),true);
        if($jsondata["Data"] !=null)
        {
            foreach ($jsondata["Data"] as $user_authority) {
                if($user_authority["user_id"]==$user_id)
                {
                    array_push( $authority, array(
//                    "no" => $role_authority["no"],
                        "features_id" => $user_authority["features_id"],
                    ));
                }
            }
        }
        return view("Person_Graph_Attendance",["title"=>"出勤管理","level"=>$level,'authority'=>$authority]);
    }


    //Export 出勤考核-單日
    public function post_attendance_download_day(Request $request)
    {
        $groups = array();
        $camera_list = array("Enabled"=>array());
        // 取得 Device 資料
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/device/select/all",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"GET");
        $jsondata = json_decode($res->getBody()->__toString(),true);
        if($jsondata["Data"] !=null)
        {
            foreach ($jsondata["Data"] as $device) {
                if ($device["Location"] == "") {
                    $name = $device["ID"];
                }
                else {
                    $name = $device["Location"];
                }
                array_push($camera_list["Enabled"],array(
                    "id"=>$device["ID"],
                    "name"=>$name,
                ));
            }
            array_push($groups, array("group"=> "Enabled"));
        }
        //匯出
        date_default_timezone_set('Asia/Taipei');
        $stime=$request->start_time;
        $etime=$request->end_time;
        $time_in=$request->time_in;
        $time_out=$request->time_out;
        $time_break=$request->time_break;
        list($in_hour, $in_minute) = explode(':', $time_in);
        list($out_hour, $out_minute) = explode(':', $time_out);
        $group_id=$request->groupid;
//        $test=array($in_hour,$in_minute,$out_hour,$out_minute,$time_break,$stime,$etime);
//        dd($test);

        $filename = sprintf("../storage/export/%s to %s.xlsx", explode(" ",$stime)[0],explode(" ",$etime)[0]);
        $file = fopen($filename, 'w');
        $client = new \GuzzleHttp\Client();
        if ($group_id==null){
            $res=$client->request('POST', sprintf("http://%s:%s/punch/card/dayrecord",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),[
                'form_params'=>[
                    'InHour'=>$in_hour,
                    'InMinute'=>$in_minute,
                    'OutHour'=>$out_hour,
                    'OutMinute'=>$out_minute,
                    'LunchBreak'=>$time_break,
                    'Start'=>$stime,
                    'End'=>$etime
                ],
                'save_to' => $file
            ]);
        }else{
            $res=$client->request('POST', sprintf("http://%s:%s/punch/card/dayrecord/group",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),[
                'form_params'=>[
                    'InHour'=>$in_hour,
                    'InMinute'=>$in_minute,
                    'OutHour'=>$out_hour,
                    'OutMinute'=>$out_minute,
                    'LunchBreak'=>$time_break,
                    'Start'=>$stime,
                    'End'=>$etime,
                    'GroupId'=>$group_id
                ],
                'save_to' => $file
            ]);
        }
//        dd($request->all());

//        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/punch/card/dayrecord", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
//            "multipart",
//            [
//                [
//                    'name'=>"InHour",
//                    "contents"=>$in_hour
//                ],
//                [
//                    'name'=>"InMinute",
//                    "contents"=>$in_minute
//                ],
//                [
//                    'name'=>"OutHour",
//                    "contents"=>$out_hour
//                ],
//                [
//                    'name'=>"OutMinute",
//                    "contents"=>$out_minute
//                ],
//                [
//                    'name'=>"LunchBreak",
//                    "contents"=>$time_break
//                ],
//                [
//                    'name'=>"Start",
//                    "contents"=>$stime
//                ],
//                [
//                    'name'=>"End",
//                    "contents"=>$etime
//                ],
//            ]);
        return response()->download($filename);


    }

    // 比對狀態頁面
    public function comparison_index(Request $request)
    {
        $request->session()->all();
        $username=$request->session()->get('Tusername');    //帳號
        $role="";
        $department="";
        $level="";
        $person_name="";
        $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"];
                $person_name=$user["name"];
                $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"],
                    ));
                }
            }
        }


        $msg = request()->session()->get('msg');
        //沒照片的人員資料
        $person_noimage=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)
            {
                if($person["Photo"]==null)
                {
                    array_push($person_noimage, array(
                        "id" => $person["ID"],
                        "name" => $person["Name"],
                        "sex" =>$person["Sex"],
                        "type" =>$person["Type"]
                    ));
                }
            }
        }

        $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"],
                ));
            }
        }
        //        return $camera_list["RD"];
        if($msg!=null){
            return view("Person_Comparison",["title"=>"比對紀錄","imgserver"=>sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"person_noimage"=>$person_noimage,"error_msg"=>$msg,"level"=>$level,"person_name"=>$person_name,"persons"=>$persons,'authority'=>$authority]);
        }else{
            return view("Person_Comparison",["title"=>"比對紀錄","imgserver"=>sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"person_noimage"=>$person_noimage,"level"=>$level,"person_name"=>$person_name,"persons"=>$persons,'authority'=>$authority]);
        }
    }

    // 取得區間內比對紀錄
    public function post_comparison(Request $request)
    {
        // 表單傳值回帶
        session()->flashInput($request->input());
        $request->session()->all();
        $username=$request->session()->get('Tusername');    //帳號
        $role="";
        $department="";
        $level="";
        $person_name="";
        $person_id="";
        $department_person_name=array();
        $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"];
                $person_name=$user["name"];
                $person_id=$user["person_id"];
                $user_id=$user["id"];
            }
        }
        if($role=="7")
        {
            $level="4";
        }
        elseif ($role=="3")
        {
            $level="3";
        }
        elseif ($role=="6")
        {
            $level="2";
        }
        elseif($role=="5")
        {
            $level="1";
            // 取得人員資料
            $user_person_name="";
            [$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)
                    {
                        $user_person_name=$person["Name"];
                    }
                }
            }
        }
        //取得權限
        $authority=array();
        $user_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) {
                if($role_authority["role_id"]==$role)
                {
                    array_push( $authority, array(
//                    "no" => $role_authority["no"],
                        "features_id" => $role_authority["features_id"],
                    ));
                    array_push( $user_auth,$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"],
                    ));
                    array_push( $user_auth,$user_authority["features_id"]);
                }
            }
        }

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


        $person_att=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) {
                if($person["Enabled"])
                {
                    array_push( $person_att, array(
                        "person_id"=>$person["ID"],
                        "person_name"=>$person["Name"],
                        "attendance"=>"缺席"
                    ));
                }
            }
        }

        //dd($user_person_name);
        date_default_timezone_set('Asia/Taipei');
        $stime=$request->start_time." 00:00:00";
        $etime=$request->end_time." 23:59:59";
        $tz="'Asia/Taipei'";
        $client = new \GuzzleHttp\Client();
        $res=$client->request('POST', sprintf("http://%s:%s/punch/card/record/all",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),[
            'form_params'=>[
                "start"=>$stime,
                "end"=>$etime
            ]
        ]);
        $jsondata=json_decode($res->getBody()->__toString(),true);
//        $jsondata = array_reverse($jsondata['Data'], true);
        // 轉換成 boostrap-table js格式
        $comparison=array();
         //dd($jsondata);
        if($request->search_text==null){
            $text=$request->search_number;
        }else{
            $text=$request->search_text;
        }
        //dd($text);
        if($jsondata['Data'] != null){
            foreach ($jsondata['Data'] as $rowdata){
            switch ($rowdata["Type"]){
                case 1:
                    $person_type="黑名單";
                    break;
                case 2:
                    $person_type="白名單";
                    break;
                case 3:
                    $person_type="VIP";
                    break;
                default:
                    $person_type="訪客";
                    break;
            }

            // 搜尋類別
            $remark="";
            if ($text ==null){
                switch ($request->search_type){
                    // 全部
                    // 黑名單
                    case "black":
                        if($person_type!="黑名單"){
                            // no match
                            continue 2;
                        }
                        break;
                    // 訪客
                    case "unknow":
                        if($person_type!="訪客"){
                            // no match
                            continue 2;
                        }
                        break;
                    // 溫度異常
                    case "overtemp":
                        if ($rowdata["Temperature"]<37.5){
                            // no match
                            continue 2;
                        }
                        $remark="溫度異常";
                        break;
                    // 未選擇
                    default:
                        break;
                }
            }else{
                    switch ($request->search_type){
                        // 全部
                        case "all":
                            if(count(explode($text,$rowdata["Name"]))<2){
                                // no match
                                continue 2;
                            }
                            break;
                        // 黑名單
                        case "black":
                            if($person_type!="黑名單" or count(explode($text,$rowdata["Name"]))<2){
                                // no match
                                continue 2;
                            }
                            break;
                        // 訪客
                        case "unknow":
                            if($person_type!="訪客" or count(explode($text,$rowdata["Name"]))<2){
                                // no match
                                continue 2;
                            }
                            break;
                        // 溫度異常
                        case "overtemp":
                            if ($rowdata["Temperature"]<$text){
                                // no match
                                continue 2;
                            }
                            $remark="溫度異常";
                            break;
                        // 未選擇
                        default:
                            break;
                    }
                }

            $id_datetime=explode("_",$rowdata["Image"]);
            if ($person_type=="訪客") {
                $ID = sprintf('"%s"', $rowdata["Image"]);
//                $image = sprintf("<a>%s</a>", $rowdata["ID"]);
                $image = "";
                $unknown = sprintf("<button class='btn btn-outline-dark float-right' onclick='insert_user(%s)' style='margin-right: 10px;' data-toggle='modal' data-target='#InsertMemberModalCenter'>新增人員</button>", $ID);
            }
            else {
//                $image = sprintf("<img class='faceimg' src='%s/person/%s'>",sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),$id_datetime[0]);
                $image = sprintf("<img class='faceimg' src='/get/image?img_path=/person/%s'>",$id_datetime[0]);
                $unknown = "<a>Created</a>";
            }
                if($rowdata["ID"]!="unknown")
                {
                    $count=0;
                    foreach ($person_att as $person_a) {
                        if($person_a["person_id"]==$rowdata["ID"])
                        {
                            $person_att[$count]["attendance"]="出席"."(".$id_datetime[4].":".$id_datetime[5].":".$id_datetime[6].")";
                            //$person_a["attendance"]="出席".$id_datetime[4].":".$id_datetime[5].":".$id_datetime[6];
                            //dd($person_att);
                        }
                        $count++;
                    }
                }
            if($level=="3" or $level=="4")
            {
                array_push($comparison,array(
                    "day" =>sprintf("%s-%s-%s",$id_datetime[1],$id_datetime[2],$id_datetime[3]),
                    "time" =>sprintf("%s:%s:%s",$id_datetime[4],$id_datetime[5],$id_datetime[6]),
                    "name" =>$rowdata["Name"],
                    "group"=>$person_type,
                    "db_img"=>$image,
//                "target_img"=>sprintf("<img class='faceimg' src='%s/punch/card/image/%s'>",sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),$rowdata["Image"]),
                    "target_img"=>sprintf("<img class='faceimg' src='/get/image?img_path=/punch/card/image/%s'>",$rowdata["Image"]),
                    "temp"=>$rowdata["Temperature"],
                    "location"=>$rowdata["Location"],
                    "remarks"=>$remark,
                    "unknown"=>$unknown,
                    "type"=>$rowdata["Type"],
                ));
            }
            elseif($level=="2")
            {
                    if(in_array ($rowdata["ID"] , $group_persons))
                    {
                        array_push($comparison,array(
                            "day" =>sprintf("%s-%s-%s",$id_datetime[1],$id_datetime[2],$id_datetime[3]),
                            "time" =>sprintf("%s:%s:%s",$id_datetime[4],$id_datetime[5],$id_datetime[6]),
                            "name" =>$rowdata["Name"],
                            "group"=>$person_type,
                            "db_img"=>$image,
//                "target_img"=>sprintf("<img class='faceimg' src='%s/punch/card/image/%s'>",sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),$rowdata["Image"]),
                            "target_img"=>sprintf("<img class='faceimg' src='/get/image?img_path=/punch/card/image/%s'>",$rowdata["Image"]),
                            "temp"=>$rowdata["Temperature"],
                            "location"=>$rowdata["Location"],
                            "remarks"=>$remark,
                            "unknown"=>$unknown,
                            "type"=>$rowdata["Type"],
                        ));
                    }
            }
            else
            {
                if($rowdata["Name"]==$user_person_name)
                {
                    array_push($comparison,array(
                        "day" =>sprintf("%s-%s-%s",$id_datetime[1],$id_datetime[2],$id_datetime[3]),
                        "time" =>sprintf("%s:%s:%s",$id_datetime[4],$id_datetime[5],$id_datetime[6]),
                        "name" =>$rowdata["Name"],
                        "group"=>$person_type,
                        "db_img"=>$image,
//                "target_img"=>sprintf("<img class='faceimg' src='%s/punch/card/image/%s'>",sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),$rowdata["Image"]),
                        "target_img"=>sprintf("<img class='faceimg' src='/get/image?img_path=/punch/card/image/%s'>",$rowdata["Image"]),
                        "temp"=>$rowdata["Temperature"],
                        "location"=>$rowdata["Location"],
                        "remarks"=>$remark,
                        "unknown"=>$unknown,
                        "type"=>$rowdata["Type"],
                    ));
                }
            }
        }
        }
        //沒照片的人員資料
        $person_noimage=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)
            {
                if($person["Photo"]==null)
                {
                    array_push($person_noimage, array(
                        "id" => $person["ID"],
                        "name" => $person["Name"],
                        "sex" =>$person["Sex"],
                        "type" =>$person["Type"]
                    ));
                }
            }
        }

        $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"],
                ));
            }
        }
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/person/leave/all", env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"POST");
        $jsondata=json_decode($res->getBody()->__toString(),true);
//        dd($jsondata);
        if($jsondata["Data"] !=null)
        {
            foreach ($jsondata["Data"] as $leave){
                $date=str_replace("-","/",$request->start_time);
                $start=substr($leave["start"],0,10);
                $end=substr($leave["end"],0,10);
                if((strtotime($start)<=strtotime($date) and strtotime($date)<=strtotime($end)))
                {
                    $count=0;
                    foreach($person_att as $person_a)
                    {
                        if($person_a["person_id"]==$leave["person_id"])
                        {
                            //dd($person_a);
                            if($person_a["attendance"]=="缺席")
                                $person_att[$count]["attendance"]=$leave["category"];
                        }
                        $count++;
                    }
                }
            }
        }




        //dd($person_att);
        return view("Person_Comparison",["title"=>"比對紀錄","rowdata"=>$comparison,"imgserver"=>sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"person_noimage"=>$person_noimage,"level"=>$level,"person_name"=>$person_name,"persons"=>$persons,'authority'=>$authority,"rowdata2"=>$person_att]);
    }

    //補登打卡
    public function post_punch_card(Request $request){
        $client = new \GuzzleHttp\Client();
        $person=$request->person;
        $time=$request->time;
        $user=$request->user;
        $temperature=$request->temperature;
        $res=$client->request('POST', sprintf("http://%s:%s/punch/card/upload/%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT"), $person),[
            'form_params'=>[
                'Time'=>$time,
                'User'=>$user,
                'Temperature'=>$temperature,
            ],
        ]);
        return redirect()->route('comparison');
    }
    //Excel匯入打卡資料
    public function punch_card_insert_excel(Request $request)
    {
        $client = new \GuzzleHttp\Client();
        $con_path=storage_path('app/');
        if($request->hasFile('excel')){
            if ($request->file('excel')->getClientOriginalExtension()=="xlsx"){
                $path=$request->file('excel')->store('excel');
                $res=$client->request('POST',sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT"))."/punch/card/excel/insert",[
                    'multipart'=>[
                        [
                            'name'=>'excel',
                            'contents'=>fopen($con_path.$path,'r')
                        ],
                    ]
                ]);
                $jsondata=json_decode($res->getBody()->__toString(),true);
                //dd($files);
                unlink($con_path.$path); //刪除檔案
                $msg=$jsondata["Message"];
                return redirect()->route('comparison')->with(["msg" => $msg]);
            }else{
                $msg="未匯入成功，錯誤為檔案不是execl檔";
                return redirect()->route('comparison')->with(["msg" => $msg]);
            }
        }else{
            $msg="未匯入成功，錯誤為未選擇檔案";
            return redirect()->route('comparison')->with(["msg" => $msg]);
        }
        return redirect()->route('comparison');
    }

    // 新增人員頁面--沒用
    public function insert_index()
    {
        // 取得所有設備資訊
        // $devices_info=$this->get_all_device();
        // 取得攝影機群組與清單
        // $groups=$devices_info[0];
        // $camera_list=$devices_info[1];
        $devices = array();
        $groups = array();
        $camera_list = array("Enabled"=>array());

        // 取得 Device 資料
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/device/select/all",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"GET");
        $jsondata = json_decode($res->getBody()->__toString(),true);
        foreach ($jsondata["Data"] as $device) {
            if ($device["Location"] == "") {
                $name = $device["ID"];
            }
            else {
                $name = $device["Location"];
            }
            array_push($camera_list["Enabled"],array(
                "id"=>$device["ID"],
                "name"=>$name,
            ));
        }
        array_push($groups, array("group"=> "Enabled"));
        //        return $camera_list["RD"];
        return view("Person_Insert",["title"=>"新增人員","groups"=>$groups,"camera_list"=>$camera_list]);
    }

    // post 新增人員處理--沒用
    public function insert(Request $request)
    {
        // 取得所有設備資訊
        // $devices_info=$this->get_all_device();
        // 取得攝影機群組與清單
        // $groups=$devices_info[0];
        // $camera_list=$devices_info[1];
        $devices = array();
        $groups = array();
        $camera_list = array("Enabled"=>array());

        // 取得 Device 資料
        $client = new \GuzzleHttp\Client();
        $res = $client->request('GET', sprintf("http://%s:%s/device/select/all",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")));
        $jsondata = json_decode($res->getBody()->__toString(),true);
        foreach ($jsondata["Data"] as $device) {
            if ($device["Location"] == "") {
                $name = $device["ID"];
            }
            else {
                $name = $device["Location"];
            }
            array_push($camera_list["Enabled"],array(
                "id"=>$device["ID"],
                "name"=>$name,
            ));
        }
        array_push($groups, array("group"=> "Enabled"));
        $person=new Person();
        if($person->where("state","=",$request->group)
            ->where("name","=",$request->name)
            ->count()==0){
            $person->name=$request->name;
            $person->state=$request->group;
            $person->save();
            return view("Person_Insert",["title"=>"新增人員","groups"=>$groups,"camera_list"=>$camera_list,"error_msg"=>"新增成功"]);
//            return redirect()->route('person')->with(["error_msg"=>"新增成功"]);
        }else{
            // 判斷是否有相同資料存在
            // 使用人臉庫圖片特徵比對
            return view("Person_Insert",["title"=>"新增人員","groups"=>$groups,"camera_list"=>$camera_list,"error_msg"=>"已有重複人員在庫"]);
//            return redirect()->route('person')->with(["error_msg"=>"已有重複人員在庫"]);
        }

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

//        dd($request->all());
        [$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);
        $rowdata=array();
        if($jsondata["Data"] !=null){
            foreach ($jsondata["Data"] as $person) {
                switch ($person["Type"]){
                    case 1:
                        $person_type="黑名單";
                        break;
                    case 2:
                        $person_type="白名單";
                        break;
                    case 3:
                        $person_type="VIP";
                        break;
                    default:
                        $person_type="訪客";
                        break;
                }
                array_push($rowdata,array(
                    "img"=>sprintf("<img class='faceimg' src='/get/image?img_path=/person/%s'>", $person["Photo"]),
                    "id"=>$person["ID"],
                    "group"=>$person_type,
                    "name"=>$person["Name"],
                    "allow_camera"=>" ",
                    "modify"=>sprintf("<button class=\"btn btn-outline-dark\" title=\"修改人員資料\" data-toggle=\"modal\" data-target=\"#ModifyMemberModalCenter\" onclick=\"person_modify(this)\">修改</button>"),
                    "sex"=>$person["Sex"],
                    "enabled"=>$person["Enabled"],
                    "start"=>"",
                    "end"=>"",
                    "token"=>"",
                ));
            }
        }
        $errors=array();
        if ($request->hasFile("face_img")){
            $path=$request->file("face_img")->store("face");
        }else{
            array_push($errors,"未上傳人臉圖片");
        }
        $id=$request->face_id;
        $sex=$request->face_sex;
        if (!isset($sex)){
            $sex=0;
        }
        $type="2";
        $group=$request->face_group;
        if (!isset($group)){
            array_push($errors,"未選擇人員群組");
        }
        $expiry_date=$request->face_expiry_date;
        if($expiry_date =='2'){
            $stime=str_replace("/","-",$request->start_time).":00";
            $etime=str_replace("/","-",$request->end_time).":59";
        }else{
            $stime=null;
            $etime=null;
        }
        if (count($errors)>0){
            // 取得所有設備資訊
            // $devices_info=$this->get_all_device();
            // 取得攝影機群組與清單
            // $groups=$devices_info[0];
            // $camera_list=$devices_info[1];

            $error_msg="上傳失敗錯誤如下: ";

            //取得人員群組資料
            $person_groups = array();
            [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/group/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
            $jsondata = json_decode($res->getBody()->__toString(), true);
            if($jsondata["Data"]!=null){
            foreach ($jsondata["Data"] as $person_group) {
                array_push($person_groups, array(
                    "id" => $person_group["ID"],
                    "name" => $person_group["Name"],
                ));
            }}
            foreach ($errors as $error){
                $error_msg=$error_msg."，".$error;
            }
            [$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);
            $rowdata=array();
            if($jsondata["Data"] !=null){
                foreach ($jsondata["Data"] as $person) {
                    switch ($person["Type"]){
                        case 1:
                            $person_type="黑名單";
                            break;
                        case 2:
                            $person_type="白名單";
                            break;
                        case 3:
                            $person_type="VIP";
                            break;
                        default:
                            $person_type="訪客";
                            break;
                    }
                    array_push($rowdata,array(
                        "img"=>sprintf("<img class='faceimg' src='%s/person/%s'>",sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")), $person["Photo"]),
                        "id"=>$person["ID"],
                        "group"=>$person_type,
                        "name"=>$person["Name"],
                        "allow_camera"=>" ",
                        "modify"=>sprintf("<button class=\"btn btn-outline-dark\" title=\"修改人員資料\" data-toggle=\"modal\" data-target=\"#ModifyMemberModalCenter\" onclick=\"person_modify(this)\">修改</button>"),
                        "sex"=>$person["Sex"],
                        "enabled"=>$person["Enabled"],
                        "start"=>"",
                        "end"=>"",
                        "token"=>"",
                    ));
                }
            }

            return view("Person",["title"=>"人員管理","rowdata"=>$rowdata,"error_msg"=>$error_msg,"person_groups"=>$person_groups,"level"=>$level,'authority'=>$authority]);
        }
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/person/insert",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"POST",
            "multipart",
            [
                [
                    'name'=>"id",
                    "contents"=>$id
                ],
                [
                    'name'=>"name",
                    "contents"=>$request->face_name
                ],
                [
                    'name'=>"sex",
                    "contents"=>$sex
                ],
                [
                    'name'=>"type",
                    "contents"=>$type
                ],
                [
                    'Content-type' => 'multipart/form-data',
                    'name'     => 'photo',
                    'contents' => fopen(Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix().$path,'r')
                ],
                [
                    'name'     => 'start',
                    'contents' => $stime
                ],
                [
                    'name'     => 'end',
                    'contents' => $etime

                ]
            ]);

        $jsondata=json_decode($res->getBody()->__toString(),true);
//        dd($jsondata);
        switch ($jsondata["Code"]){
            case 1:
                // 成功
                $error_msg="新增成功";
                break;
            case 10:
                // ID無法使用
                $error_msg="ID錯誤無法使用";
                break;
            case 11:
                // 人臉偵測失敗
                $error_msg="偵測不到人臉請重新上傳";
                break;
            default:
                return abort("500","伺服器無法回應");
                break;
        }

        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/group/relation/insert",env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
            "multipart",
            [
                [
                    'name' => "person_group_id",
                    "contents" => $group
                ],
                [
                    'name' => "person_id",
                    "contents" => $id
                ],
            ]);


        //取得人員群組資料
        $person_groups = array();
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/group/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
        $jsondata = json_decode($res->getBody()->__toString(), true);
        if($jsondata["Data"] !=null)
        {
            foreach ($jsondata["Data"] as $person_group) {
                array_push($person_groups, array(
                    "id" => $person_group["ID"],
                    "name" => $person_group["Name"],
                ));
            }
        }

//        dd($jsondata);
        [$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);
        $rowdata=array();
        if($jsondata["Data"] !=null){
            foreach ($jsondata["Data"] as $person) {
                switch ($person["Type"]){
                    case 1:
                        $person_type="黑名單";
                        break;
                    case 2:
                        $person_type="白名單";
                        break;
                    case 3:
                        $person_type="VIP";
                        break;
                    default:
                        $person_type="訪客";
                        break;
                }
                array_push($rowdata,array(
                    "img"=>sprintf("<img class='faceimg' src='%s/person/%s'>",sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")), $person["Photo"]),
                    "id"=>$person["ID"],
                    "group"=>$person_type,
                    "name"=>$person["Name"],
                    "allow_camera"=>" ",
                    "modify"=>sprintf("<button class=\"btn btn-outline-dark\" title=\"修改人員資料\" data-toggle=\"modal\" data-target=\"#ModifyMemberModalCenter\" onclick=\"person_modify(this)\">修改</button>"),
                    "sex"=>$person["Sex"],
                    "enabled"=>$person["Enabled"],
                    "start"=>$person["Start"],
                    "end"=>$person["End"],
                    "token"=>$person["Token"],
                ));
            }
        }
        return view("Person",["title"=>"人員管理","rowdata"=>$rowdata,"error_msg"=>$error_msg,"person_groups"=>$person_groups,"level"=>$level,'authority'=>$authority]);
    }

    public function insert_face_no_image(Request $request)
    {

        //dd($request->all());
        $errors=array();
        $client = new \GuzzleHttp\Client();
        // if ($request->hasFile("face_img")){
        //     $path=$request->file("face_img")->store("face");
        // }else{
        //     array_push($errors,"未上傳人臉圖片");
        // }
        $id=$request->face_id;
        $sex=$request->face_sex;
        if (!isset($sex)){
            $sex=0;
        }
        $type="2";
        if (!isset($type)){
            array_push($errors,"未選擇人員類型");
        }
        $expiry_date=$request->face_expiry_date;
        if($expiry_date =='2'){
            $stime=str_replace("/","-",$request->start_time).":00";
            $etime=str_replace("/","-",$request->end_time).":59";
        }else{
            $stime=null;
            $etime=null;
        }

        if (count($errors)>0){
            $error_msg="上傳失敗錯誤如下: ";

            foreach ($errors as $error){
                $error_msg=$error_msg."，".$error;
            }
            //取得人員群組資料
            $person_groups = array();
            [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/group/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
            $jsondata = json_decode($res->getBody()->__toString(), true);
            foreach ($jsondata["Data"] as $person_group) {
                array_push($person_groups, array(
                    "id" => $person_group["ID"],
                    "name" => $person_group["Name"],
                ));
            }
            return redirect()->route('person')->with(["msg" => $error_msg]);
//            return view("Person",["title"=>"人員管理","rowdata"=>"","error_msg"=>$error_msg,"person_groups"=>$person_groups,"level"=>$level]);
        }else{

//            $facnames=explode("/",$facname);
            $res=$client->request('POST',sprintf("http://%s:%s/person/insert/no/image", env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),[
                'form_params'=>[
                    "id"=>$id,
                    "name"=>$request->personname,
                    "sex"=>$sex,
                    "type"=>$type,
                    "photo"=>$request->face_img,
                    "start"=>$stime,
                    "end"=>$etime
                ]
            ]);

            $jsondata=json_decode($res->getBody()->__toString(),true);
            $msg=$jsondata["Message"];

            //沒照片的人員資料
//            $person_noimage=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);
//            foreach($jsondata["Data"] as $person)
//            {
//                if($person["Photo"]==null)
//                {
//                    array_push($person_noimage, array(
//                        "id" => $person["ID"],
//                        "name" => $person["Name"],
//                        "sex" =>$person["Sex"],
//                        "type" =>$person["Type"]
//                    ));
//                }
//            }
            //dd($jsondata);
            return redirect()->route('comparison')->with(["msg" => $msg]);
//            return view("Person_Comparison",["title"=>"比對紀錄","imgserver"=>sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"error_msg"=>$jsondata["Message"],"person_noimage"=>$person_noimage,"level"=>$level]);
//            return view("Person_Comparison",["title"=>"比對紀錄","groups"=>$groups,"camera_list"=>$camera_list,"imgserver"=>sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"error_msg"=>$jsondata["Message"],"person_noimage"=>$person_noimage]);
        }
//



        // $res=$client->request('POST',sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT"))."/person/insert",[
        //     'multipart'=>[
        //     [
        //       'name'=>"id",
        //       "contents"=>$id
        //     ],
        //     [
        //         'name'=>"name",
        //         "contents"=>$request->face_name
        //     ],
        //     [
        //         'name'=>"sex",
        //         "contents"=>$sex
        //     ],
        //     [
        //         'name'=>"type",
        //         "contents"=>$type
        //     ],
        //     [
        //         'Content-type' => 'multipart/form-data',
        //         'name'     => 'photo',
        //         'contents' => fopen(Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix().$path,'r')
        //     ],
        //     [
        //         'name'     => 'start',
        //         'contents' => $stime
        //     ],
        //     [
        //         'name'     => 'end',
        //         'contents' => $etime

        //     ]
        //     ]
        // ]);

    }

    // 刪除人臉
    public function delete_face(Request $request)
    {
//        dd($request->selectedId);
        if($request->selectedId!=null) {
            $ids=explode(",",$request->selectedId);
            $v_personrelation=0;
            [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/group/relation/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
            $jsondata = json_decode($res->getBody()->__toString(), true);
            if($jsondata["Data"] !=null)
            {
                foreach ($ids as $id){
                    if ($jsondata["Data"]!=null){
                        foreach ($jsondata["Data"]as $person){
                            if ($id==$person["PersonID"]){
                                $v_personrelation=1;
                            }else{
                                $v_personrelation=0;
                            }}
                    }
                }
            }


        if($v_personrelation==0){
            $client = new \GuzzleHttp\Client();
            $error_ids=array();
            foreach ($ids as $id){
//                dd($id);
                $res=$client->request('POST',sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT"))."/person/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="刪除成功";
                return redirect()->route('person')->with("msg",$msg);
            }else{
                $msg=$error_ids[0];
                for ($i=1;$i<count($error_ids);$i++){
                    $msg=$msg.",".$error_ids[$i];
                }
                $msg=$msg."刪除失敗";
                return redirect()->route('person')->with("msg",$msg);
            }
        }else{
            $msg="人員還存在群組";
            return redirect()->route('person')->with("msg",$msg);
        }

        }else{
            $msg="未選擇刪除人員";
            return redirect()->route('person')->with("msg",$msg);
        }

    }

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


//        dd($request->all());
        $errors=array();
        if ($request->hasFile("modify_face_img")){
            $path=$request->file("modify_face_img")->store("face");
            $img=fopen(Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix().$path,'r');
        }else{
//            array_push($errors,"未上傳人臉圖片");
            $img=null;
        }
        $id=$request->modify_face_id;
        $sex=$request->modify_face_sex;
        if (!isset($sex)){
            $sex=0;
        }
        $type="2";

        $expiry_date=$request->modify_face_expiry_date;
        if($expiry_date =='2'){
            $stime=str_replace("/","-",$request->modify_start_time).":00";
            $etime=str_replace("/","-",$request->modify_end_time).":59";
        }else{
            $stime=null;
            $etime=null;
        }
        if (count($errors)>0){
            // 取得所有設備資訊
            // $devices_info=$this->get_all_device();
            // 取得攝影機群組與清單
            // $groups=$devices_info[0];
            // $camera_list=$devices_info[1];

            $error_msg="上傳失敗錯誤如下: ";

            foreach ($errors as $error){
                $error_msg=$error_msg."，".$error;
            }

            //取得人員群組資料
            $person_groups = array();
            [$ret, $res] = $this->request_server(sprintf("http://%s:%s/person/group/all", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST");
            $jsondata = json_decode($res->getBody()->__toString(), true);
            if($jsondata["Data"] !=null)
            {
                foreach ($jsondata["Data"] as $person_group) {
                    array_push($person_groups, array(
                        "id" => $person_group["ID"],
                        "name" => $person_group["Name"],
                    ));
                }
            }


            return view("Person",["title"=>"人員管理","rowdata"=>"","error_msg"=>$error_msg,"person_groups"=>$person_groups,"level",$level,'authority'=>$authority]);
        }


        if($request->deleted=="1")
            $deleted="0";
        else
            $deleted="1";

        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/person/update", env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"POST",
            "multipart",
            [
                [
                    'name'=>"id",
                    "contents"=>$id
                ],
                [
                    'name'=>"name",
                    "contents"=>$request->modify_face_name
                ],
                [
                    'name'=>"sex",
                    "contents"=>$sex
                ],
                [
                    'name'=>"type",
                    "contents"=>$type
                ],
                [
                    'Content-type' => 'multipart/form-data',
                    'name'     => 'photo',
                    'contents' =>$img
                ],
                [
                    'name'     => 'start',
                    'contents' => $stime
                ],
                [
                    'name'     => 'end',
                    'contents' => $etime

                ],
                [
                'name'     => 'token',
                'contents' => $request->modify_face_line_token
                ],
                [
                'name'     => 'deleted',
                'contents' =>$deleted
                ]
            ]);
        $jsondata=json_decode($res->getBody()->__toString(),true);
//        dd($jsondata);
        return redirect()->route('person');
    }

    // 下載批量匯入人員樣本
    public function download_import_person_excel(Request $request)
    {
        $filename ="../storage/空白人員匯入表.xlsx";
        //dd($filename);
        return response()->download($filename,"空白人員匯入表.xlsx");
    }
    //下載匯入假期範本
    public function download_excel_holiday_example(Request $request)
    {
        $filename ="../storage/匯入假期範例(含補班).xlsx";
        //dd($filename);
        return response()->download($filename,"匯入假期範例(含補班).xlsx");
    }
    //匯入假期
    public function insert_holiday_excel(Request $request)
    {
        $client = new \GuzzleHttp\Client();
        $con_path=storage_path('app/');
        if($request->hasFile('excel')){
            if ($request->file('excel')->getClientOriginalExtension()=="xlsx"){
                $path=$request->file('excel')->store('excel');
                $res=$client->request('POST',sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT"))."/holiday/insert/excel",[
                    'multipart'=>[
                        [
                            'name'=>'excel',
                            'contents'=>fopen($con_path.$path,'r')
                        ],
                    ]
                ]);
                $jsondata=json_decode($res->getBody()->__toString(),true);
                //dd($files);
                unlink($con_path.$path); //刪除檔案
                $msg=$jsondata["Message"];
                return redirect()->route('attendance')->with(["msg" => $msg]);
            }else{
                $msg="未匯入成功，錯誤為檔案不是execl檔";
                return redirect()->route('attendance')->with(["msg" => $msg]);
            }
        }else{
            $msg="未匯入成功，錯誤為未選擇檔案";
            return redirect()->route('attendance')->with(["msg" => $msg]);
        }
    }

    // 後端獲取圖片流測試
    public function get_remote_image(Request $request)
    {
        if(isset($request->img_path)){
            $remote_img_path = sprintf("http://%s:%s%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT"),$request->img_path);
            return response()->stream(function () use ($remote_img_path){
                echo file_get_contents($remote_img_path);
            },200,['Content-Type' => 'image/jpeg']);
        }else{
            return response(200)->header('Content-Type','image/jpeg');
        }

    }
    // 公用方法
    // 取得所有設備清單 回傳 群組 設備名稱與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];
    }
    
    
    
  //部門編修
    //新增部門
    public function insert_department(Request $request)
    {
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/department/insert", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
            "multipart",
            [
                [
                    'name' => "department",
                    "contents" => $request->department_name
                ],
            ]);
        $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('insert_user')->with(["error_msg" => $error_msg]);
    }
    //修改部門
    public function update_department(Request $request)
    {
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/department/update", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
            "multipart",
            [
                [
                    'name' => "no",
                    "contents" => $request->department_no
                ],
                [
                    'name' => "department",
                    "contents" => $request->department_name
                ],
            ]);
        $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('insert_user')->with(["error_msg" => $error_msg]);
    }
    //刪除部門
    public function delete_department(Request $request)
    {
        [$ret, $res] = $this->request_server(sprintf("http://%s:%s/department/delete", env("IMAGE_SERVER_HOST"), env("IMAGE_SERVER_PORT")), "POST",
            "multipart",
            [
                [
                    'name' => "no",
                    "contents" => $request->department_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('insert_user')->with(["error_msg" => $error_msg]);
    }
   
    
    
    // 狀態碼檢查
    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;
        }
    }
}
