@extends('layouts.template')
@section('header')
    <script type="text/javascript" src="{{asset('bower_components/moment/moment.js')}}"></script>
    <script type="text/javascript" src="{{asset('bower_components/moment/locale/zh-tw.js')}}"></script>
    <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 rel="stylesheet" href="{{asset('css/video_replay.css')}}">
@stop

@section('content')
@include('video_replay.layout.menubtn')
<div class="collapse" id="collapseExample" style="margin: 5%">
    <div class="card card-body border border-white"style="background-color:steelblue;">
        <div class="icon" style="position: absolute;right:5%;top:0"><img style="transform:scaleY(-1);transform:scaleX(-1);" width=400px height=400px src="https://www.flaticon.com/premium-icon/icons/svg/1982/1982068.svg" alt="無法顯示圖片"></div>
        <div class="row " style="margin-bottom: 2%;margin-top: 2%;">
            <div class="dropdown col-xs-6 col-md-3"style='margin:1%;display:inline;'>
                <button  class="btn-lg btn btn-outline-warning dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                    <span style="color:navajowhite" id="seleted_goup">選擇群組</span>
                    <span class="caret"></span>
                </button>
                <ul id="goup_ids" class="dropdown-menu" aria-labelledby="dropdownMenu1">
                    @foreach($Goups as $goup)
                        <li id="l"style="margin-left: 5%" onclick="select_goup('{{$goup->goup_id}}'),goup_name.value='{{$goup->goup_name}}',seleted_goup.innerHTML='{{$goup->goup_name}}'">{{$goup->goup_name}}</li>
                    @endforeach
                </ul>
            </div>
            <div style="color:#000" class="dropdown col-xs-6 col-md-3"style='margin:1%;display:inline;'>
                <button  class="btn-lg btn btn-outline-warning dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                    <span style="color:navajowhite" id="seleted">選擇攝影機</span>
                    <span class="caret"></span>
                </button>
                <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
                    <li id="l"style="margin-left: 5%" onclick="group([1,2,3]),seleted.innerHTML='群組1'">群組1</li>
                    <li id="l"style="margin-left: 5%" onclick="group([4,5,6]),seleted.innerHTML='群組2'">群組2</li>
                    <li id="l"style="margin-left: 5%" onclick="group([7,8,9]),seleted.innerHTML='群組3'">群組3</li>
                    <li id="l"style="margin-left: 5%" class="dropdown-divider"></li>
                    <li id="l"style="margin-left: 2%" onclick="group('all'),multiSelet.style.display='block',seleted.innerHTML='全選攝影機'">全選攝影機</li>
                    <li id="l"style="margin-left: 5%" class="dropdown-divider"></li>
                    <li id="l"style="margin-left: 2%" onclick="group('del'),multiSelet.style.display='block',seleted.innerHTML='選擇攝影機'">取消全部選擇</li>
                </ul>
            </div>
        </div>

        <div style="color:#000" class="row" style="margin: 5%">
            <div class="col-md-6">
                <form  id="multiSelet"  name="multiSelet"   onsubmit="return false">
                    <div class="bg-light border border-primary">
                        <div  style="text-align: center" class="bg-primary"><h3>選擇多台攝影機</h3></div>
                        <div style="margin-left: 15%" id="channel_info">請先選擇地區DVR...</div>
                    </div>
                </form>
            </div>
        </div>

        <form id="send" action="http://60.249.6.104:10300/replay2" method="POST"  onsubmit="return false">
            {{ csrf_field() }}
            <div class="row" >
                <div class="col-xs-6 col-md-3">
                    <label id="arg"  for="stime">選擇所需要回播片段的</label>
                </div>
                <div class="col-xs-6 col-md-2">
                    <span id="arg">開始時間:</span>
                </div>
                <div class="form-group" style="margin-left: 2%" >
                    <div class="input-group date" id="datetimepicker1" data-target-input="nearest">
                        <input 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>
            </div>
            <div class="row"><div class="col-md-6" style="margin-left: 2%">到</div></div>
            <div class="row">
                <div class="col-xs-6 col-md-3">
                    <label id="arg" for="stime">選擇所需要回播片段的</label>
                </div>
                <div class="col-xs-6 col-md-2">
                    <span id="arg">結束時間:</span>
                </div>
                <div class="form-group" style="margin-left: 2%">
                    <div class="input-group date" id="datetimepicker2" data-target-input="nearest">
                        <input 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>
                </div>
            </div>
            <input id="channel"type="hidden" name="camera_path"  required/>
            <input id="goup_name"  type='hidden' name="goup_name"  required/>

            <div class="row">
                <div class="col-md-6"></div><input id='sub_btn' style="margin: 2% ; margin-left : 80%"  class="btn-lg btn-success btn" type="submit" value="送出"/>
            </div>
        </form>
@include('video_replay.layout.progressbar')

    </div>
</div>
<span id='buttom'></span>

<div id="Screens"></div>

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

    window.onresize = function(){
        update_video_width()
    }
</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"}
                    ]);
                    // this.dispose();
                    // var content_test=document.getElementById("vdiv"+index);
                    // content_test.innerHTML="<img id=\"video"+index+"\" class=\"img-responsive errorimg\" src=\"https://cdn2.iconfinder.com/data/icons/interactive-shadow-pack/100/_-3-512.png\">"
                    // delete videos[index];
                    // vcontent_test.style.backgroundImage = "url('https://cdn2.iconfinder.com/data/icons/interactive-shadow-pack/100/_-3-512.png')";
                });
            });


            videoid[i].style.setProperty("display", "none", "important");
            videos[i].play();
            // sleep
            // var now = new Date().getTime();
            // var millisecondsToWait = 500; /* i.e. 1 second */
            // while ( new Date().getTime() < now + millisecondsToWait )
            // {
            // /* do nothing; this will exit once it reached the time limit */
            // /* if you want you could do something and exit*/
            // /* mostly I prefer to use this */
            // }
            // console.log(videos[i]);
        }
    }
</script>

<!-- 刪除屏幕 -->
<script>
    function disposeScreens(){
        videos.forEach(function(obj){
            obj.dispose();
        });
    }
</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.body.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>

<!-- 檢查 form 欄位 -->
<script>
    function checkform(){
        if (!(document.getElementById('start_time').value)){
            alert('請選擇 "開始時間" !!')
            return true;
        };

        if (!(document.getElementById('end_time').value)){
            alert('請選擇 "結束時間" !!')
            return true;
        };
        return false;
    }
</script>


<script>
    $('#menu').click();
    // var urls= ['http://d2zihajmogu5jn.cloudfront.net/bipbop-advanced/bipbop_16x9_variant.m3u8'];
    // newScreens(urls);
</script>

<!-- {{--呼叫api 取得回傳--}} -->
<script>
    $("#send").submit(function(e) {
        btn=document.getElementById('sub_btn');
        prg_div=document.getElementById('prg_div');
        var form = $(this);
        btn.setAttribute('disabled','disabled');
        if (checkform()){
            btn.removeAttribute('disabled');
            prg_div.style.visibility='hidden';
        }
        else{
            if (!(document.getElementById('goup_name').value)){
                alert('請選擇 群組 ！！');
                btn.removeAttribute('disabled');
                prg_div.style.visibility='hidden';
                return false;
            }
            else{
                var url = form.attr('action');
                var channel = document.forms['multiSelet'];
                var txt = "";
                var i;
                var nums=0;
                for (i = 0; i < channel.length; i++) {
                    if (channel[i].checked) {
                        txt = txt + channel[i].value +',';
                        nums+=1;
                    }
                }
                document.getElementById('channel').value=txt;

                if (!(document.getElementById('channel').value)){
                    alert('請選擇 頻道 ！！');
                    btn.removeAttribute('disabled');
                    prg_div.style.visibility='hidden';
                    return false;
                }
                proset(nums);
                prg_div.style.visibility='';
                window.location.hash='#buttom';
                window.location.hash='';

                disposeScreens();
                $.ajax({
                    type: "POST",
                    url: url,
                    data:form.serialize(),
                    dataType: 'json',
                    success: function(data)
                    {
                        // alert(JSON.stringify(data))
                        // console.log(data.length);
                        newScreens(data);
                        completed();
                        setTimeout(function(){
                            $('#menu').click();
                        },1000)
                        btn.removeAttribute('disabled');
                    },
                    error:function(data){
                        alert(JSON.stringify(data)+'\n'+'發生錯誤')
                        failure();
                        btn.removeAttribute('disabled');
                    }

                });
                e.preventDefault(); // avoid to execute the actual submit of the form.
            }
        }
    });
</script>

<!-- 群組選擇 -->
<script>
    function group(list){

        var channel = document.forms['multiSelet'];
        // init all checkebox
        for (i = 0; i < channel.length; i++) {
            channel[i].checked=false;
        }
        if (list == 'del'){return true}
        if (list == 'all'){
            for (i = 0; i < channel.length; i++) {
                channel[i].checked=true;
            }
        }
        else{
            // set group options to checkebox
            for (i = 0; i < list.length; i++) {
                channel[list[i]-1].checked=true;
            }
        }
    }

</script>

<!-- 時間選擇器 -->
<!-- datetimepicker1 物件  -->
<script type="text/javascript">
    $(function () {
        $('#datetimepicker1').datetimepicker({
            locale:'zh-tw',
            format: 'YYYY/MM/DD a hh:mm:ss ',
            weekStart: 1,
            autoclose: 0,
            todayHighlight: 1,
            // sideBySide:true,
            stepping:0,
            minView:0,
            maxView:0,
            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,
            // sideBySide:true,
            stepping:0,
            minView:0,
            maxView:0,

            startView: 0,  // 0 ＝月曆   1＝月份  2 =年份
        });
    });
</script>


{{--選擇群組後 顯示現有設備--}}
<script>
    function select_goup(goup_id)
    {
        $.ajax({
            type: "GET",
            url: '{{url('replay/select_goup/')}}/'+goup_id,
            dataType: 'json',
            success: function(data)
            {
                str = '';
                var i=0
                for (var k in data)
                {
                    if (i % 3 == 0){ str+="<div class=\"row\">"; };
                    str+="<div style=\"margin: 1%\" class=\"form-check form-check-inline\">" +
                        "<input class=\"form-check-input\" type=\"checkbox\" id=\"inlineCheckbox"+i.toString()+"\" value=\""+data[k]['camera_path']+"\">" +
                        "<label class=\"form-check-label\" for=\"inlineCheckbox"+i.toString()+"\"><span></span>"+data[k]['camera_id']+"</label></div>";
                    if (i % 3 == 2){ str+="</div>"; };
                    i++;
                }

                document.getElementById("channel_info").innerHTML=str;
            },
            error:function(data){
                alert(JSON.stringify(data)+'\n'+'發生錯誤')
            }

        });
    }
</script>
@endsection
