{{ define "kas/archive_video_edit.htm" }}
<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <title>编辑视频 - 后台管理 - 看丽人</title>
    <script type="text/javascript">
        const ISGOKEEP = true;
    </script>
    {{ template "_common.htm" .}}
    <link rel="stylesheet" href="{{.global.host_img}}/assets/css/jquery.fileupload.css">
    <script src="{{.global.host_img}}/assets/js/jsrender.min.js"></script>
    <script src="{{.global.host_img}}/assets/js/md5.min.js"></script>
    <link href="{{.global.host_img}}/assets/css/cropper.min.css" rel="stylesheet">
    <script src="{{.global.host_img}}/assets/js/cropper.min.js"></script>
    <script type="text/javascript" src="{{.global.host_img}}/assets/js/moment.min.js"></script>
    <script type="text/javascript" src="{{.global.host_img}}/assets/js/daterangepicker.min.js"></script>
    <link rel="stylesheet" type="text/css" href="{{.global.host_img}}/assets/css/daterangepicker.css" />
    <style type="text/css">
        .template-upload td {
            max-width: 120px;
        }

        .itempreview {
            width: 400px;
        }
    </style>
    <script type="text/javascript">
        LoadMemberInfo();
    </script>
</head>

<body>
    {{ template "kas/_header.htm" .}}
    <main role="main">
        <div class="album py-3 bg-light">
            <div class="container">
                {{ template "kas/_nav.htm" .}}
                <input type="hidden" name="unqid" id="iptUnqid" value="{{.archive.UnqID}}">
                <div class="alert alert-dark border-bottom"><a href="/kas/archive/video_main">视频管理</a> > 添加视频</span>
                </div>
                <div class="form-group">
                    <label for="iptTitle">视频标题</label>
                    <input name="title" type="text" class="form-control" id="iptTitle" value="{{.archive.Title}}">
                </div>
                <div class="form-group">
                    <label for="selTypeid">分类</label>
                    <select id="selTypeid" name="typeid" class="form-control">
                        <option value="0">请选择栏目...</option>
                    </select>
                </div>
                <div class="form-group">
                    <label><input id="ckIsShow" name="isshow" {{if .cIndex}} checked{{end}} value="1" type="checkbox">
                        首页推荐</label>
                    <!-- <label><input id="ckArcrank" name="arcrank"{{if eq .archive.Arcrank 10}} checked{{end}} value="10" type="checkbox"> 仅会员查看</label> -->
                </div>
                <div class="form-group">
                    <label for="iptMoney">需要金币（默认为0，免费）</label>
                    <input name="money" type="text" class="form-control" id="iptMoney" value="{{.archive.Money}}">
                </div>
                <div class="form-group">
                    <label>视频合集列表</label>
                    <div class="row fileupload-buttonbar">
                        <div class="col-lg-7">
                            <span class="btn btn-success fileinput-button">
                                <i class="glyphicon glyphicon-plus"></i>
                                <span>上传视频...</span>
                                <input type="file" name="files[]" multiple id="iptAddVideos">
                            </span>
                            <button id="btnClearAll" type="button" class="btn btn-danger delete">
                                <i class="fa fa-trash-o"></i>
                                <span>清空</span>
                            </button>
                        </div>
                        <div class="col-lg-5 fileupload-progress fade">
                            <div class="progress progress-striped active" role="progressbar" aria-valuemin="0"
                                aria-valuemax="100">
                                <div class="progress-bar progress-bar-success" style="width:0%;"></div>
                            </div>
                            <div class="progress-extended">&nbsp;</div>
                        </div>
                        <div class="col-12 py-3" id="_videoItems">

                        </div>
                    </div>
                </div><!-- end form-group -->
                <div class="form-group">
                    <label for="iptMoney">来源</label>
                    <input name="source" type="text" class="form-control" id="iptSource" value="{{.archive.Source}}">
                </div>
                <div class="form-group">
                    <label for="iptMoney">预发布时间（设置未来将要上线的时间，不设置则不预发布）</label>
                    <input name="source" type="text" class="form-control" id="iptWillPub"
                        value="{{date .archive.Sortrank "Y-m-d H:i:s"}}">
                </div>
                <button id="btnPublish" class="btn btn-danger btn-block" type="submit">保存</button>
                <button onclick="javascript:history.go(-1);" class="btn btn-outline-secondary btn-block"
                    type="button">返回</button>
            </div><!-- end container -->

        </div>
    </main>

    <canvas id="pvCanvas" style="display: none;"></canvas>

    {{ template "kas/_footer.htm" .}}

    <script id="tplVideoItem" type="text/x-jsrender">
<div class="row mb-2 border-bottom" id="imageitem-{%:id%}">
  <div class="col-lg-6">
    <div class="clearfix itempreview preview-{%:id%} mb-2">
      <video id="ii-{%:id%}" src="{%:~uploads_url(src)%}" width=400 controls/>
      <span class="float-left">
        <button class="btn btn-sm btn-warning cancel" onclick="SetThumbVideoStart('{%:id%}')">
              <span>截取缩略视频（3秒）</span>
        </button>
      </span>
      <span class="float-right"><button onclick="SetThumb('{%:id%}')" type="button" class="btn btn-sm btn-warning">设置缩略图</button></span>
    </div>
  </div>
  <div class="col-lg-6">
    <div class="row">
        <div class="col-12">
          <div class="row">
            <div class="col-6">
              {%if thumbVideo%}
                <video autoplay loop id="pvo-{%:id%}" src="{%:~uploads_url(thumbVideo)%}" style="width: 200px;"></video>
              {%else%}
                <video autoplay loop id="pvo-{%:id%}" class="border" style="width: 200px;"></video>
              {%/if%}
              <br/>
              缩略视频
            </div>
            <div class="col-6" id="pio-{%:id%}">
              {%if thumb%}
                <img src="{%:~uploads_url(thumb)%}" style="width: 133.33px; height: 100px;">
              {%else%}
                <img src="{{.global.host_img}}/assets/img/logo.png" style="width: 133.33px; height: 100px;">
              {%/if%}
              <br/>
              缩略图
            </div>
          </div>
          

        </div>
        <div class="col-12 mb-2">
          <p><b>文件名：</b>{%:name%}</p>
          <p><b>尺寸：</b>{%:size%}</p>

          <button class="btn btn-warning cancel" onclick="RemoveVideoItem('{%:id%}')">
            <i class="fa fa-times"></i>
            <span>删除</span>
          </button>
          {%if litpic%}
          <button class="btn btn-warning cancel" disabled>
            <i class="fa fa-camera"></i>
            <span>设为封面</span>
          </button>
          {%else%}
          <button class="btn btn-warning cancel" onclick="SetLitpic('{%:id%}')">
            <i class="fa fa-camera"></i>
            <span>设为封面</span>
          </button>
          {%/if%}
        </div>
    </div>
  </div>
</div>
</script>

    <script type="text/javascript">
        var gokeep_token = GetCookie(TokenName())
        if (gokeep_token == null) {
            DirectTo("/kas");
        }

        var willpub = {{.archive.Sortrank }};
        var arcrank = {{.archive.Arcrank }};

        $.views.settings.delimiters("{%", "%}"); // 设置js render标签
        $.views.helpers({
            uploads_url: function (val) {
                return val.replace("public/", "/");
            }
        })
        // 加载栏目选项
        LoadTypeidSelectOptions("#selTypeid", {{.archive.Typeid }}, 2);

        $('#iptWillPub').daterangepicker({
            timePicker: true,
            singleDatePicker: true,
            locale: {
                format: 'YYYY/MM/DD HH:mm'
            }
        });
        $('#iptWillPub').on('apply.daterangepicker', function (ev, picker) {
            willpub = picker.startDate.unix();
        });

        // 选择图片后，将图片渲染到浏览器界面，以便进行操作再进行上传
        var videoItems = JSON.parse({{.videos }});

        function ShowVideoItems() {
            var content = $("#tplVideoItem").render(videoItems);
            $("#_videoItems").html(content);
        }

        let mediaRecorder;
        let recordedBlobs; // 用来存放截取的视频流

        const thumbWidth = 400; // 缩略视频宽度
        const thumbHeight = 300; // 缩略视频高度

        // 定义一个canvas将视频转为特定尺寸
        var canvas = document.getElementById('pvCanvas');
        var context = canvas.getContext('2d');

        // 存放截取的视频流
        function handleDataAvailable(event) {
            if (event.data && event.data.size > 0) {
                recordedBlobs.push(event.data);
            }
        }

        function RemoveVideoItem(id) {
            for (var i = 0; i < videoItems.length; i++) {
                var videoItem = videoItems[i];
                if (videoItem.id == id) {
                    videoItems.splice(i, 1);
                }
            }
            ShowVideoItems();
        }

        // 设为封面缩略图
        function SetLitpic(id) {
            for (var i = 0; i < videoItems.length; i++) {
                var videoItem = videoItems[i];
                if (videoItem.id == id) {
                    videoItems[i].litpic = true;
                } else {
                    videoItems[i].litpic = false;
                }
            }
            ShowVideoItems();
        }

        // 设置截取的缩略图到imageItems中
        function SetVideoItemThumb(id, data) {
            for (var i = 0; i < videoItems.length; i++) {
                var videoItem = videoItems[i];
                if (videoItem.id == id) {
                    videoItems[i].thumb = data;
                }
            }
        }

        function SetThumb(id) {
            var footer = "<p><a href='?' class='btn btn-outline-primary' data-dismiss='modal' aria-label='Close'>确定</a></p>";
            var canvas = document.createElement("canvas");
            var video = document.getElementById('ii-' + id)
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            canvas.getContext('2d')
                .drawImage(video, 0, 0, canvas.width, canvas.height);


            var mdlID = ShowMsg('<div><div class="float-left" style="width:300px;"><img id="cropImg~modalID~" src="' + canvas.toDataURL() + '" width=200></div><div class="pv float-right" style="width:150px;height:100px;overflow:hidden;"></div></div>', {
                footer: footer,
                noClose: false,
            });

            setTimeout(function () {
                $("#cropImg" + mdlID).cropper({
                    aspectRatio: 4 / 3,
                    preview: ".pv",
                    // 拖动截取缩略图后，截取的缩略图更新到imageItems中
                    cropend: function (data) {
                        // 这里的ID要单独取出来
                        var dataUrl = $(this).cropper("getCroppedCanvas").toDataURL();
                        $("#pio-" + id).html('<img src="' + dataUrl + '" style="width: 133.33px; height: 100px;">');
                        SetVideoItemThumb(id, dataUrl);
                    }
                });
            }, 500);
        }

        // 将视频画到canvas里面
        function draw(v, c, w, h, isLandscape) {
            if (v.paused || v.ended) return false;
            if (isLandscape && h < thumbHeight) {
                c.drawImage(v, 0, (thumbHeight - h) / 2, w, h);
            } else if (!isLandscape && w < thumbWidth) {
                c.drawImage(v, (thumbWidth - w) / 2, 0, w, h);
            } else {
                c.drawImage(v, 0, 0, w, h);
            }

            setTimeout(draw, 20, v, c, w, h, isLandscape);
        }

        function SetThumbVideoStart(id) {
            for (var ii = 0; ii < videoItems.length; ii++) {
                var videoItem = videoItems[ii];
                if (videoItem.id == id) {
                    // videoItems[i].thumbVideo_start = parseInt(document.getElementById('ii-'+id).currentTime);
                    var v = document.getElementById("ii-" + id);
                    const stream = canvas.captureStream(3); // frames per second
                    var isLandscape = true; // 视频是否为横向（宽大于高）
                    var cw = 400;
                    var ch = 300;
                    vw = v.clientWidth;
                    vh = v.clientHeight;
                    if (vh > vw) {
                        isLandscape = false
                    }
                    if (isLandscape) {
                        // 如果是横向视频
                        cw = thumbWidth;
                        ch = (thumbWidth / vw) * vh;
                    } else {
                        // 如果是纵向
                        ch = thumbHeight;
                        cw = (thumbHeight / vh) * vw;
                    }

                    // 固定画布尺寸
                    canvas.width = thumbWidth;
                    canvas.height = thumbHeight;

                    v.addEventListener('play', function () {
                        draw(this, context, cw, ch, isLandscape);
                    }, false);

                    // 截取canvas中的视频
                    let options = { mimeType: 'video/webm' };
                    recordedBlobs = [];
                    mediaRecorder = new MediaRecorder(stream, options);

                    mediaRecorder.onstop = (event) => {
                        console.log('Recorder stopped: ', event);
                        const superBuffer = new Blob(recordedBlobs, { type: 'video/webm' });
                        var pv = document.getElementById('pvo-' + id);

                        var reader = new FileReader();
                        reader.onload = function () {
                            var dataUrl = reader.result;
                            // var base64 = dataUrl.split(',')[1];
                            pv.src = dataUrl;
                            // 由于是异步，所以需要判断id，而不是直接用i取索引
                            for (var i = 0; i < videoItems.length; i++) {
                                if (videoItems[i].id == id) {
                                    videoItems[i].thumbVideo = pv.src;
                                }
                            }

                        };
                        reader.readAsDataURL(superBuffer);
                    };
                    mediaRecorder.ondataavailable = handleDataAvailable;
                    mediaRecorder.start(100); // collect 100ms of data

                    v.play();

                    setTimeout(function () {
                        mediaRecorder.stop();
                        v.pause();
                    }, 3000);
                }
            }
        }

        // 清空所有视频
        $('#btnClearAll').click(function (event) {
            videoItems = [];
            ShowVideoItems();
        });

        // 添加视频
        $("#iptAddVideos").change(function (event) {

            var files = event.target.files;
            for (var i = 0, f; f = files[i]; i++) {
                Log("[#iptAddVideos.change]", f);

                if (!f.type.match('video.*')) {
                    continue;
                }
                var hash = md5(f.name + f.size);
                // 将视频渲染到浏览器
                var reader = new FileReader();
                reader.onload = (function (theFile) {
                    return function (e) {
                        var hash = md5(theFile.name + theFile.size);
                        videoItems.push({
                            id: hash,
                            name: theFile.name,
                            size: theFile.size,
                            src: e.target.result,
                            litpic: false, // 是否为缩略图
                            thumb: "", // 缩略图
                            thumbVideo: "", // 缩略视频
                        });
                        ShowVideoItems();
                    };
                })(f);
                reader.readAsDataURL(f);

            }
        });

        // 发布
        $('#btnPublish').click(function (event) {
            if ($("#iptTitle").val() == "") {
                ShowMsg("请添加标题");
                return;
            } if (parseInt($("#selTypeid").val()) == 0) {
                ShowMsg("请选择栏目");
                return;
            }
            if (videoItems.length == 0) {
                ShowMsg("请添加视频");
                return;
            }
            if (willpub > 0 && willpub <= NowUnix && arcrank == -9) {
                ShowMsg("预发布时间需要是未来时间");
                return;
            }

            var haslitpic = false;
            var nothumb = false;
            for (var i = 0; i < videoItems.length; i++) {
                if (videoItems[i].litpic == true) {
                    haslitpic = true;
                }
                if (videoItems[i].thumb == "") {
                    nothumb = true;
                }
            }
            if (!haslitpic) {
                ShowMsg("请设置封面图片");
                return;
            }
            if (nothumb) {
                ShowMsg("请确保每个图片都含有缩略图");
                return;
            }

            $('#btnPublish').addClass('disabled');
            $('#btnPublish').text('正在发布...');
            $.ajax({
                type: "POST",
                dataType: 'json',
                contentType: "application/json;",
                url: "/api/v1/auth/archive/video_edit",
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('Authorization', 'Bearer ' + gokeep_token);
                },
                data: JSON.stringify({
                    unqid: $("#iptUnqid").val(),
                    title: $("#iptTitle").val(),
                    typeid: parseInt($("#selTypeid").val()),
                    isshow: $("#ckIsShow").is(":checked") ? 1 : 0,
                    // arcrank: $("#ckArcrank").is(":checked")? 10 : 0,
                    money: parseInt($("#iptMoney").val()),
                    source: $("#iptSource").val(),
                    videos: videoItems,
                    willpub: willpub,
                }),
                timeout: 0,
                success: function (data) {
                    Log(data);
                    if (data.code == 0) {
                        var viewStr = "<p><a href='{{.global.host_www}}/view/" + data.result.UnqID + "' class='btn btn-primary' target='_blank'>查看已发布内容</a> ";
                        if (willpub > 0 && willpub > NowUnix) {
                            viewStr = "";
                        }
                        var footer = viewStr + "<a href='javascript:location.reload();' class='btn btn-primary'>继续修改</a> <a href='/kas/archive/video_add' class='btn btn-primary'>发布新内容</a></p>"
                        ShowMsg("编辑成功", {
                            footer: footer,
                            noClose: true,
                        });
                    } else {
                        ShowMsg("[错误代码:" + data.code + "]发布失败，请检查填写内容是否完整、正确");
                    }
                },
                error: function () {
                    ShowMsg("编辑失败");
                }
            }).always(function () {
                $('#btnPublish').removeClass('disabled');
                $('#btnPublish').text('发布');
            });
        });

        if (videoItems.length > 0) {
            ShowVideoItems();
        }

    </script>
</body>

</html>
{{ end }}