@extends('layout.default')

@section('title', '攝影機調閱')

@section('header')
    <script src="https://cdnjs.cloudflare.com/ajax/libs/video.js/6.0.0-RC.5/video.js"></script>
    <!-- PC 端浏览器不支持播放 hls 文件(m3u8), 需要 videojs-contrib-hls 来给我们解码 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/videojs-contrib-hls/5.3.3/videojs-contrib-hls.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/videojs-hotkeys/0.2.25/videojs.hotkeys.min.js"></script>
    <link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
    <script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>

@endsection


@section('body')
@endsection
@section('content')
<div class="pos-f-t">
{{--     上排  navbar區--}}
{{--<nav class="navbar navbar-dark bg-dark">--}}
{{--        <button onclick="setlayout()" id="cam_menu_btn" class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggleExternalContent" aria-controls="navbarToggleExternalContent" aria-expanded="false" aria-label="Toggle navigation">--}}
{{--            <span class="navbar-toggler-icon"></span>--}}
{{--        </button>--}}
{{--</nav>--}}

<div class="row">
    {{-- 攝影機 選單區--}}
    <div class="collapse p-4 bg-dark col-md-2 show"  id="navbarToggleExternalContent">
        <h2 class="text-white"style="font-size: 20pt">選擇 直播/回播</h2>
        <div style="padding: 1%;text-align: left;">
        <input id="toggle-event" type="checkbox" data-toggle="toggle" data-on="直播" data-off="回播" data-onstyle="danger" data-offstyle="info" data-width="100%" size="large">
        </div>
        @include('layout.menubtn')
        <h2 class="text-white"style="font-size: 20pt">攝影機選項</h2>
        <div id="cam_group_menu"></div>
  </div>
    {{--攝影機 畫面區--}}
    <div id="Screen-aria" class="col-md-10" style="padding: 2%; background:darkgray">
        <div class="row" style="visibility: hidden;" id="time_aria">
            <div class="col-auto">
                <h2>開始時間：</h2>
                <input id='st_time' style="text-align: center;width: 100%" name="st_time" type="text" required/>
            </div>
            <div class="col-auto">
                <h2>結束時間：</h2>
                <input id='en_time' style="text-align: center;width: 100%" name="en_time" type="text" required/>
            </div>
        </div>
        <div id="Screens">
        </div>
    </div>
</div>
</div>

{{-- 時間選擇回放表單 --}}
<div class="collapse" id="collapseExample" style="z-index: 3;position:absolute;top:10%;left:15%;width:auto;height:auto;">
    <div class="card card-body row"style="background-color:white;">

        <form id="send" action="http://192.168.5.217:8001/replay2" method="POST"  onsubmit="return false">
            @csrf
            <div class="col-auto">
                <span id="arg" style="color: black">開始時間:</span>
            </div>
            <div class="input-group date" id="datetimepicker1" data-target-input="nearest">
                <input type="hidden" id='start_time' style="text-align: center" name="start_time" type="text" class="form-control datetimepicker-input" data-target="#datetimepicker1" required/>
                <div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker">
                    <div class="input-group-text"><i class="fa fa-calendar"></i></div>
                </div>
            </div>
            <div class="col-auto">
                <span id="arg" style="color: black">結束時間:</span>
            </div>
            <div class="input-group date" id="datetimepicker2" data-target-input="nearest">
                <input  type="hidden"id='end_time' style="text-align: center" name="end_time" type="text" class="form-control datetimepicker-input" data-target="#datetimepicker2" required/>
                <div class="input-group-append" data-target="#datetimepicker2" data-toggle="datetimepicker">
                    <div class="input-group-text"><i class="fa fa-calendar"></i></div>
                </div>
            </div>
{{--            <input id="channel"type="hidden" name="camera_path"  required/>--}}
            <input type="text" id="cam_ids" name="cam_ids" hidden/>
            <input id="goup_name"  type='hidden' name="goup_name"  required/>
        </form>
        <div class="col-md-6"></div><button onclick="time_btn()" style="margin: 2% ; margin-left : 80%"  class="btn-lg btn-success btn">確認</button>
    </div>
</div>



    {{--隱藏表單請求realtime api--}}
{{--<form id="send" action="http://192.168.5.217:8001/realtime/play" method="POST"  onsubmit="return false">--}}
{{--    @csrf--}}
{{--    <input type="text" id="cam_ids" name="cam_ids" hidden/>--}}
{{--    <input type="text" id="goup_name" name="goup_name" hidden/>--}}
{{--    <input id='sub_btn' style="width: 100%" class="btn-lg btn-success btn" type="submit" value="送出" hidden/>--}}
{{--</form>--}}




{{--直播/回播 toggle--}}
<script>
    var Rp=true;
    $(function() {
        $('#toggle-event').bootstrapToggle('on');
        document.getElementById("menu").style.visibility="hidden";
        $('#toggle-event').change(function() {
            if ($(this).prop('checked'))
            {
                //直播
                Rp=true;
                document.getElementById("menu").style.visibility="hidden";
                document.getElementById("time_aria").style.visibility="hidden";
                document.getElementById("start_time").value="";
                document.getElementById("end_time").value="";
                document.getElementById("st_time").value="";
                document.getElementById("en_time").value="";
            }
            else
            {
                //回播
                Rp=false;
                document.getElementById("menu").style.visibility="visible";
                document.getElementById("time_aria").style.visibility="visible";
            }

            now_play_urls.length=0;
            disposeAllScreens();
            for (var i in now_group_list){
                unsetGroup_color(now_group_list[i])
            }
            now_group_list.length=0;
            for (var i in now_play_list){
                unsetCamid_color(now_play_list[i])
            }
            now_play_list.length=0;

        })
    })
</script>

{{--群組選擇播放--}}
<script>
    var now_group_list=new Array();
    function  SelectGroup(group) {
        var temp_play_list=[];
        var ul =document.getElementById(group);
        var lis=ul.getElementsByTagName('li');
        for (var i=0 ; i < lis.length;i++)
        {
            temp_play_list.push(lis[i].id);
        }
        SelectCam_group(temp_play_list,group);
    }
</script>

{{--遞迴所有群組及設備 以顯示現有設備於左側nav-bar--}}
<script type="text/javascript">
    str='';
    now_play_list=[];
    $(document).ready(function(){
        $.ajax({
            type: "GET",
            url: '{{url('play_v2')}}/'+"index",
            dataType: 'json',
            success: function(data)
            {
                //console.log(data);

                for (var k in data)
                {
                    //console.log(data[k]);
                    var goup_name='';
                    for (var j in data[k])
                    {
                        if (j==0) //顯示區域
                        {
                            str += "<div id=\""+data[k][j][k]['goup_name']+"_tag\" style=\"font-size: 18pt;color: white\" class=\"dropdown-toggle\" data-toggle=\"collapse\" href=\"#collapse"+data[k][j][k]['goup_id']+"\" role=\"button\" " +
                                "aria-expanded=\"false\" aria-controls=\"collapse"+data[k][j][k]['goup_id']+"\"><button id=\""+data[k][j][k]['goup_name']+"_btn\"ondblclick='SelectGroup(\""+data[k][j][k]['goup_name']+"\")' style='color:white;background-color:transparent;border: none;'>"+data[k][j][k]['goup_name']+"</button></div>\
                            <div class=\"collapse\" id=\"collapse"+data[k][j][k]['goup_id']+"\" style=\"color: white\">\<div><ul id='"+data[k][j][k]['goup_name']+"'>";
                            console.log(data[k][j][k]['goup_name']);
                            goup_name=data[k][j][k]['goup_name'];
                            continue;
                        }
                        str+="<li id=\""+data[k][j]['camera_id']+"\" ondblclick=\'SelectCam(\""+data[k][j]['camera_id']+"\",\""+goup_name+"\")\'><button id=\""+data[k][j]['camera_id']+"_btn\" style='color:white;background-color:transparent;border: none;'>"+data[k][j]['camera_id']+"</button></li>";
                        console.log(data[k][j]['camera_id']);
                    }
                    str+="</ul></div></div>";
                }

                document.getElementById("cam_group_menu").innerHTML=str;
            },
            error:function(data){
                alert(JSON.stringify(data)+'\n'+'發生錯誤');
                console.log(data);
            }
        });
    //console.log(str);
        $('#cam_menu_btn').click();
        setTimeout(function(){
            $('.dropdown-toggle').click();
        },500)
        setlayout();
    });
</script>

{{--    收起menu時 調整攝影機畫面大小--}}
{{--<script>--}}
{{--        function  setlayout() {--}}
{{--            var Sa =document.getElementById('Screen-aria').classList;--}}
{{--            if(Sa.contains("col-md-10")){--}}
{{--                Sa.toggle("col-md-10",false);--}}
{{--                Sa.toggle("col-md-12",true);--}}
{{--            }--}}
{{--            else{--}}
{{--                Sa.toggle("col-md-12",false);--}}
{{--                Sa.toggle("col-md-10",true);--}}
{{--            }--}}

{{--        }--}}
{{--    </script>--}}

{{--  觸發表單請求 api 回傳串流網址--}}
<script>
    var api_url =["http://192.168.5.217:8000/realtime/play","http://192.168.5.217:8000/replay2"];
    var now_play_urls = new Array();
    $("#send").submit(function(e) {
        var url='';
        var form = $(this);
        if (!Rp){
            if (document.getElementById("start_time").value && document.getElementById("end_time").value){
            url = api_url[1];
            }
            else {
                alert("請選擇回播時間區間");
            }
        }
        else {
            url = api_url[0];
        }
        if (url){
            var cam_ids=document.getElementById('cam_ids').value;
            $.ajax({
            type: "POST",
            url: url,
            data:form.serialize(),
            dataType: 'json',
            success: function(data)
            {
                disposeAllScreens();
                for (var i in cam_ids.split(',')){
                    if (cam_ids.split(',')[i]==''){
                        break;
                    }
                    setCamid_color(cam_ids.split(',')[i]);
                    now_play_list.push(cam_ids.split(',')[i]);
                    now_play_urls.push(data[i]);
                }
                console.log(now_play_urls);
                newScreens(now_play_urls);
            },
            error:function(data){
                alert('發生錯誤：'+JSON.stringify(data)+'\n');
                unsetCamid_color(now_play_list.pop());
            }
        });
        }
        else{
            unsetCamid_color(now_play_list.pop());
        }
        e.preventDefault(); // avoid to execute the actual submit of the form.
    });
</script>

{{--每從選單中 雙擊攝影機  即submit 表單--}}
    <script>
        function SelectCam($cam_id,$goup_name){
            setTimeout(function ()
            {
            if ((now_play_list.indexOf($cam_id))<0){
            //console.log($cam_id+":"+$goup_name);
            document.getElementById('cam_ids').value=$cam_id+",";
            document.getElementById('goup_name').value=$goup_name;
            $("#send").submit();
            }
            else{
                unsetCamid_color($cam_id);
                var index=now_play_list.indexOf($cam_id);
                now_play_list.splice(index,1);
                now_play_urls.splice(index,1);
                disposeAllScreens();
                newScreens(now_play_urls);
            }
            },1000);
        }
    </script>

{{--群組方式 雙擊群組  即submit 表單--}}
<script>
    function SelectCam_group($cam_ids,$goup_name){
        setTimeout(function ()
        {
            var txt='';
            for (var i in $cam_ids){
                txt+=$cam_ids[i]+',';
            }
            if ((now_group_list.indexOf($goup_name))<0) {
                document.getElementById('cam_ids').value = txt;
                document.getElementById('goup_name').value = $goup_name;
                $("#send").submit();
                now_group_list.push($goup_name);
                setGroup_color($goup_name);
            }
            else {
                for (var i in $cam_ids){
                    unsetCamid_color($cam_ids[i]);
                    var index=now_play_list.indexOf($cam_ids[i]);
                    now_play_list.splice(index,1);
                    now_play_urls.splice(index,1);
                }
                now_group_list.splice(now_group_list.indexOf($goup_name),1);
                unsetGroup_color($goup_name);
                disposeAllScreens();
                newScreens(now_play_urls);
            }
        },3000);
    }
</script>

{{--    選中的攝影機變為綠色  否則白色--}}
    <script>
        function setCamid_color($cam_id) {
            document.getElementById($cam_id+"_btn").setAttribute("style","background-color:transparent;color: #2fa360;font-weight: bolder;border: none;");
            document.getElementById($cam_id).setAttribute("style","color: #2fa360;font-weight: bolder;");
        }
        function unsetCamid_color($cam_id) {
            document.getElementById($cam_id+"_btn").setAttribute("style","background-color:transparent;color: white;border: none;");
            document.getElementById($cam_id).setAttribute("style","color: white;");
        }

        function setGroup_color($group) {
            document.getElementById($group+"_btn").setAttribute("style","background-color:transparent;color: #2fa360;font-weight: bolder;border: none;");
            document.getElementById($group+"_tag").setAttribute("style","color: #2fa360;font-weight: bolder;");
        }
        function unsetGroup_color($group) {
            document.getElementById($group+"_btn").setAttribute("style","background-color:transparent;color: white;border: none;");
            document.getElementById($group+"_tag").setAttribute("style","color: white;");
        }
    </script>

<!-- videojs 視窗調整事件 -->
<script>
    function update_video_width(){
        videos.forEach(element => {
            element.width(Math.floor(document.getElementById("Screens").clientWidth/columns_cam));
        });
    }

    window.onresize = function(){
        update_video_width()
    }
</script>

<!-- 刪除全部屏幕 -->
<script>
    function disposeAllScreens(){
        videos.forEach(function(obj){
            obj.dispose();
        });
    }
</script>

<!-- 準備串流後播放 -->
<script>
    var videos = new Array();
    function readyScreens(count_cam){
        videos.length = 0;
        var videoid =document.getElementsByClassName("vjs-control-bar");
        var video_option={
            preload: 'auto',
            autoplay:true,
            fluid: false
        };
        for(i=0;i<count_cam;i++){
            videos.push(videojs('video'+i,video_option));
            videos[i].ready(function() {
                this.hotkeys({
                    volumeStep: 0.1,
                    seekStep: 5,
                    enableVolumeScroll: false, //禁用鼠标滚轮调节问音量大小
                    enableModifiersForNumbers: false
                });

                this.on("error",function(e){
                    // alert(this.id()+"error");
                    var index = videos.indexOf(this);

                    videos[index].src([
                        {type: "application/x-mpegURL", src: "http://d2zihajmogu5jn.cloudfront.net/bipbop-advanced/bipbop_16x9_variant.m3u8"}
                    ]);
                });
            });
            videoid[i].style.setProperty("display", "none", "important");
            videos[i].play();
        }
    }
</script>

<!-- 新增屏幕 -->
<script>
    let count_cam=0;
    let columns_cam=0
    function newScreens(urls){
        // var playlists=["http://192.168.5.17:10008/record/ncut_mm/in/20190519/out.m3u8","http://192.168.5.17:10008/record/ncut_mm/in/20190520/out.m3u8","http://192.168.5.17:10008/record/ncut_mm/in/20190522/out.m3u8","http://60.249.6.104:10308/record/2019-08-14/IM001/10/replay.m3u8"];
        var playlists = urls;
        count_cam=playlists.length;
        columns_cam=Math.floor(Math.sqrt(count_cam));
        if (columns_cam <=1 ){
            columns_cam=count_cam;
        }
        // var columns_cam=3;
        var rows_cam=Math.ceil(count_cam/columns_cam);
        var str='';
        str+=("<div class=\"container-fluid\">");
        for(i=0;i<rows_cam;i++){
            str+=("<div class=\"row\">");
            //基數欄位左右補齊
            if(12-(Math.floor(12/columns_cam))!= 0)
            {
                str+=("<div class=\"col-"+(12-Math.floor(12/columns_cam)*columns_cam)/2+"\" style=\"padding-left: 0px; padding-right: 0px;\">");
                str+=("</div>");
            }
            // document.write("<div class=\"col-1\"></div>");
            for(j=0;j<columns_cam && (i*columns_cam+j)!=count_cam;j++){
                str+=("<div class=\"col-"+Math.floor(12/columns_cam)+"\" style=\"padding-left: 0px; padding-right: 0px;\">");
                // document.write("<div class=\"col\">");
                // document.write("<h1>"+(i*columns_cam+j)+"</h1>");
                str+=("<video id=\"video"+(i*columns_cam+j)+"\""+ "width=\""+(Math.floor(document.getElementById("Screens").clientWidth/columns_cam))+"\"  class=\"video-js vjs-default-skin\"");
                // document.write("<video id=\"video"+(i*columns_cam+j)+"\""+ "width=\"100%\" height=\"100%\" class=\"video-js vjs-default-skin\"");

                str+=("playsinline webkit-playsinline autoplay controls preload=\"auto\"");
                str+=("x-webkit-airplay=\"true\" x5-video-player-fullscreen=\"true\" x5-video-player-typ=\"h5\" muted=\"muted\">");
                str+=("<source src=\""+urls[(i*columns_cam+j)]+"\"");
                // str+=("<source src="+"http://60.249.6.104:10308/record/replay/IM001/"+(i*columns_cam+j)+"/replay.m3u8"+" ");
                // str+=("<source src=\""+'http://d2zihajmogu5jn.cloudfront.net/bipbop-advanced/bipbop_16x9_variant.m3u8'+"\"");
                str+=("type=\"application/x-mpegURL\">");
                str+=("</video>");
                str+=("</div>");
            }
            // document.write("<div class=\"col-1\"></div>");
            str+=("</div>");
        }
        str+=("</div>");
        document.getElementById('Screens').innerHTML=str;
        setTimeout(readyScreens(count_cam),1000);
    }
</script>


<!-- 時間選擇器 -->
<!-- datetimepicker1 物件  -->
<script type="text/javascript">
    $(function () {
        $('#datetimepicker1').datetimepicker({
            locale:'zh-tw',
            format: 'YYYY/MM/DD a hh:mm:ss ',
            weekStart: 1,
            autoclose: 1,
            todayHighlight: 1,
            inline:true,
            sideBySide:true,
            stepping:0,
            minView:0,
            maxView:0,
            maxDate:new Date(),
            startView: 0,  // 0 ＝月曆   1＝月份  2 =年份
        });
    });


</script>

<!-- datetimepicker2 物件  -->
<script type="text/javascript">
    $(function () {
        $('#datetimepicker2').datetimepicker({
            locale:'zh-tw',
            format: 'YYYY/MM/DD a hh:mm:ss ',
            weekStart: 1,
            autoclose: 0,
            todayHighlight: 1,
            inline:true,
            sideBySide:true,
            stepping:0,
            minView:0,
            maxView:0,
            useCurrent:false,
            startView: 0,  // 0 ＝月曆   1＝月份  2 =年份
        });
        $("#datetimepicker1").on("change.datetimepicker", function (e) {
            $('#datetimepicker2').datetimepicker("minDate",e.date);
        });
        $("#datetimepicker2").on("change.datetimepicker", function (e) {
            $('#datetimepicker1').datetimepicker("maxDate",e.date);
        });
    });
</script>

<script>
        function  time_btn() {
            $('#menu').click();
            document.getElementById("st_time").value=document.getElementById("start_time").value;
            document.getElementById("en_time").value=document.getElementById("end_time").value;
        }
    </script>
@endsection
