<?php

namespace App\Http\Controllers;

use App\E3SCamera;
use App\Person;
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)
    {
        $username = $request->session()->get('Tusername');
        $msg = request()->session()->get('msg');
        // 取得所有設備資訊
        // $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"));
        // dd($camera_list);
        // dd($groups);
        // 取得人員資料
        [$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"],
            ));
        }
        }

        //取得人員群組資料
        $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"],
            ));
        }

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

//匯入檔案
    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"];
                    $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 $this->index($request)->with(["error_msg"=>$insert_msg]);
                }else{
                    $msg="未匯入成功，錯誤為檔案不是execl檔";
                    return $this->index($request)->with(["error_msg"=>$msg]);
                }
            }else{
                $msg="未匯入成功，錯誤為未選擇檔案";
                return $this->index($request)->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)
    {
        $username = $request->session()->get('Tusername');
        // request回調
        session()->flashInput($request->input());
        $msg =null;
        // 取得所有設備資訊
        // $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"));
        // dd($camera_list);
        // dd($groups);
        // 取得人員資料
        [$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"]),
                    "id" => $person["ID"],
                    "group" => $person_type,
                    "name" => $person["Name"],
                    "allow_camera" => " "
                ));
            }
        }
        if(count($rowdata)==0){
            $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);
        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"=>"人員管理","groups"=>$groups,"camera_list"=>$camera_list,"rowdata"=>$rowdata,"error_msg"=>$msg,"person_groups"=>$person_groups,"msg"=> $username]);
        }else{
            return view("Person",["title"=>"人員管理","groups"=>$groups,"camera_list"=>$camera_list,"rowdata"=>$rowdata,"person_groups"=>$person_groups,"msg"=> $username]);
        }
    }

    // 出勤狀態頁面
    public function attendance_index(Request $request)
    {
        $username = $request->session()->get('Tusername');
        $msg = request()->session()->get('msg');
        // 取得所有設備資訊
        // $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"));
        $export = array("In"=>"08:30", "Out"=>"17:30", "LunchBreak"=>60);
        if($msg!=null){
            return view("Person_Attendance",["title"=>"出勤管理","export_arg"=>$export,"groups"=>$groups,"camera_list"=>$camera_list,"error_msg"=>$msg,"msg"=> $username]);
        }else{
            return view("Person_Attendance",["title"=>"出勤管理","export_arg"=>$export,"groups"=>$groups,"camera_list"=>$camera_list,"msg"=> $username]);
        }
    }


    // 取得區間內出勤考核狀態
    public function post_attendance_old(Request $request)
    {
        $username = $request->session()->get('Tusername');
        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,"msg"=> $username]);
    }

    // 取得區間內出勤考核狀態
    public function post_attendance(Request $request)
    {
        // request回調
        session()->flashInput($request->input());
        $username = $request->session()->get('Tusername');
        // 取得所有設備資訊
        // $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"));

        date_default_timezone_set('Asia/Taipei');
        $stime=$request->start_time." 00:00:00";
        $etime=$request->end_time." 23:59:59";
        $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");
        }
        $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 $this->attendance_index($request)->with(["error_msg"=>$error_msg]);
        }

        // 轉換成 boostrap-table js格式
        $attendance=array();
        foreach (array_keys($jsondata['Data']) as $id){
            // 獲取人員名單
            [$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"];
                }

                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),
                    "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,"groups"=>$groups,"camera_list"=>$camera_list,"rowdata"=>$attendance,"msg"=> $username]);
    }

    // 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);
        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');

        $client = new \GuzzleHttp\Client();

        $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);

    }


    //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);
        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);

//        $test=array($in_hour,$in_minute,$out_hour,$out_minute,$time_break,$stime,$etime);
//        dd($test);

        $filename = sprintf("../storage/export/%s.xlsx", $stime);
        $file = fopen($filename, 'w');

        $client = new \GuzzleHttp\Client();
        $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
        ]);

//        [$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)
    {
        $username = $request->session()->get('Tusername');
        // 取得所有設備資訊
        // $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_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"]
                ));
            }
        }

        //        return $camera_list["RD"];
        return view("Person_Comparison",["title"=>"比對紀錄","groups"=>$groups,"camera_list"=>$camera_list,"imgserver"=>sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"person_noimage"=>$person_noimage,"msg"=> $username]);
    }

    // 取得區間內比對紀錄
    public function post_comparison(Request $request)
    {
        $username = $request->session()->get('Tusername');
        // 表單傳值回帶
        session()->flashInput($request->input());
        // 取得所有設備資訊
        // $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"));
        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);
        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 (($rowdata["Type"] == -1 or $rowdata["Type"] == 0 )and $rowdata['ID']=="unknown") {
                $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]);
                $unknown = "<a>Created</a>";
            }
            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"]),
                "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);
        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"]
                ));
            }
        }

            return view("Person_Comparison",["title"=>"比對紀錄","groups"=>$groups,"camera_list"=>$camera_list,"rowdata"=>$comparison,"imgserver"=>sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"person_noimage"=>$person_noimage,"msg"=> $username]);
    }

    // 新增人員頁面
    public function insert_index(Request $request)
    {
        $username = $request->session()->get('Tusername');
        // 取得所有設備資訊
        // $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,"msg"=> $username]);
    }

    // post 新增人員處理

    public function insert(Request $request)
    {
        $username = $request->session()->get('Tusername');
        // 取得所有設備資訊
        // $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"=>"新增成功","msg"=> $username]);

        }else{
            // 判斷是否有相同資料存在
            // 使用人臉庫圖片特徵比對
            return view("Person_Insert",["title"=>"新增人員","groups"=>$groups,"camera_list"=>$camera_list,"error_msg"=>"已有重複人員在庫","msg"=> $username]);
        }

    }
//    新增人臉
    public function insert_face(Request $request)
    {
        $username = $request->session()->get('Tusername');
        $devices = array();
        $groups = array();
        $camera_list = array("Enabled"=>array());

        // 取得 Device 資料
        [$ret,$res]=$this->request_server(sprintf("http://%s:%s/device/select/all",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT")),"GET");
        $jsondata = json_decode($res->getBody()->__toString(),true);
        foreach ($jsondata["Data"] as $device) {
            if ($device["Location"] == "") {
                $name = $device["ID"];
            }
            else {
                $name = $device["Location"];
            }
            array_push($camera_list["Enabled"],array(
                "id"=>$device["ID"],
                "name"=>$name,
            ));
        }
        array_push($groups, array("group"=> "Enabled"));
//        dd($request->all());
        $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);
            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;
            }
            return view("Person",["title"=>"人員管理","groups"=>$groups,"camera_list"=>$camera_list,"rowdata"=>"","error_msg"=>$error_msg,"person_groups"=>$person_groups,"msg"=> $username]);
        }

        [$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);
        foreach ($jsondata["Data"] as $person_group) {
            array_push($person_groups, array(
                "id" => $person_group["ID"],
                "name" => $person_group["Name"],
            ));
        }
//        dd($jsondata);
        return view("Person",["title"=>"人員管理","groups"=>$groups,"camera_list"=>$camera_list,"rowdata"=>"","error_msg"=>$error_msg,"person_groups"=>$person_groups,"msg"=> $username]);
    }

    public function insert_face_no_image(Request $request)
    {
        $username = $request->session()->get('Tusername');
//        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;
        }

            // 取得所有設備資訊
            // $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"));
        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 view("Person",["title"=>"人員管理","groups"=>$groups,"camera_list"=>$camera_list,"rowdata"=>"","error_msg"=>$error_msg,"person_groups"=>$person_groups,"msg"=> $username]);
        }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);


            //沒照片的人員資料
//            $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"]
//                    ));
//                }
//            }
            $person_noimage=array();
            //dd($jsondata);
            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,"msg"=> $username]);
//            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)
    {
        if($request->selectedId!=null) {
            $client = new \GuzzleHttp\Client();
            $error_ids=array();
            $ids=explode(",",$request->selectedId);
            foreach ($ids as $id){
                $res=$client->request('POST',sprintf("http://%s:%s",env("IMAGE_SERVER_HOST"),env("IMAGE_SERVER_PORT"))."/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="刪除成功";
            }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);
        }

    }

    public function post_modify(Request $request)
    {
        $username = $request->session()->get('Tusername');
//        dd($request->all());
        $devices = array();
        $groups = array();
        $camera_list = array("Enabled"=>array());

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

            return view("Person",["title"=>"人員管理","groups"=>$groups,"camera_list"=>$camera_list,"rowdata"=>"","error_msg"=>$error_msg,"person_groups"=>$person_groups,"msg"=> $username]);
        }

        [$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

            ]
            ]);

        $jsondata=json_decode($res->getBody()->__toString(),true);
//        dd($jsondata);
        return $this->index($request);
    }

    // 公用方法
    // 取得所有設備清單 回傳 群組 設備名稱與id
    public function get_all_device(){
        $e3scamera=new E3SCamera;
        $groups=$e3scamera->distinct('group')->get('group');
        $rowdata=$e3scamera->select("id","group","name")->get();

        // 建立攝影機清單
        $camera_list=array();
        foreach ($rowdata as $data){
            if(array_key_exists($data->group,$camera_list)){
                array_push($camera_list[$data->group],array("name"=>$data->name,"id"=>$data->id));
            }else{
                $camera_list[$data->group]=array(array("name"=>$data->name,"id"=>$data->id));
            }
        }

        return [$groups,$camera_list];
    }
    // 狀態碼檢查
    private function check_status_code($status_code){
        switch ($status_code){
            case 200:
                return true;
                break;
            case 500:
                return abort("500","伺服器沒有回應");
            case 503:
                return abort("503","伺服器沒有回應");
            default:
                break;
        }
        return true;
    }
    private function request_server($url,$method,$data_format=null,$data=null){
        $status_code=404;
        $client=new \GuzzleHttp\Client();
        switch ($method){
            case "GET":
                try {
                    $res = $client->request('GET',$url);
                    $status_code=$res->getStatusCode();
                }catch (RequestException $e){
                    if (!$e->hasResponse()) {
                        // 伺服器沒有回應
                        $status_code=503;
                    }
                }
                break;
            case "POST":
                if ($data!=null and $data_format !=null){
                    if ($data_format =="form_params" or $data_format =="multipart"){
                        try {
                            $res=$client->request('POST',$url,[
                                $data_format=>$data
                            ]);
                            $status_code=$res->getStatusCode();
                        }catch (RequestException $e){
                            if (!$e->hasResponse()) {
                                // 伺服器沒有回應
                                $status_code=503;
                            }
                        }
                    }else{
                        $status_code=404;
                    }
                }else{
                    try {
                        $res=$client->request('POST',$url);
                        $status_code=$res->getStatusCode();
                    }catch (RequestException $e){
                        if (!$e->hasResponse()) {
                            // 伺服器沒有回應
                            $status_code=503;
                        }
                    }
                }
                break;
            default:
                break;
        }

        switch ($status_code){
            case 200:
                return [true,$res];
                break;
            case 404:
                return abort("404","查無此頁");
            case 500:
                return abort("500","內部伺服器錯誤");
            case 503:
                return abort("503","伺服器沒有回應");
            default:
                return abort("404","查無此頁");
                break;
        }
    }
}
