<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <base th:href="${#request.getContextPath() + '/'} ">
    <meta charset="utf-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="assets/fonts/font-awesome/css/font-awesome.css"/>
    <link rel="stylesheet" href="assets/layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="assets/layuiadmin/style/admin.css" media="all">
    <style>
        .layui-table-progress {height: 28px !important; line-height: 28px !important; border-radius: 0px !important;}
        .layui-table-progress-bar {height: 28px !important; line-height: 28px !important; border-radius: 0px !important;}
    </style>
</head>
<body>
<div class="layui-fluid layui-anim layui-anim-fadein">
    <div class="layui-row">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-body" id="cardBody">
                    <div class="test-table-reload-btn" style="margin-bottom: 10px;">
                        <div class="layui-inline">
                            <input type="text" id="keywords" class="layui-input search-item search-item-width-100" placeholder="输入关键字">
                        </div>
                        <div class="layui-inline">
                            <input type="text" id="startTime" class="layui-input search-item search-item-width-100" placeholder="开始时间" readonly>
                        </div>
                        <div class="layui-inline">
                            <input type="text" id="endTime" class="layui-input search-item search-item-width-100" placeholder="结束时间" readonly>
                        </div>
                        <button type="button" id="search" class="layui-btn layui-btn-sm">
                            <i class="fa fa-lg fa-search"></i> 搜索
                        </button>
                    </div>
                    <table class="layui-hide" id="dataTable" lay-filter="dataTable"></table>
                    <!-- 表头按钮组 -->
                    <script type="text/html" id="headerToolBar">
                        <div class="layui-btn-group">
                            <button type="button" class="layui-btn layui-btn-sm" lay-event="saveEvent">
                                <i class="fa fa-lg fa-plus"></i> 新增
                            </button>
                            <button type="button" class="layui-btn layui-btn-danger layui-btn-sm" lay-event="removeEvent">
                                <i class="fa fa-lg fa-trash"></i> 删除
                            </button>
                        </div>
                        <span style="margin-left: 10px;"><i class="fa fa-warning"></i> 视频在线播放只支持MP4格式，格式不符合或不能播放，请点击"转码状态"列的"开始转码"按钮进行转码</span>
                    </script>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="assets/layuiadmin/layui/layui.js"></script>
<script type="text/javascript">
    layui.config({
        base: 'assets/layuiadmin/'
    }).extend({
        index: 'lib/index'
    }).use(['index', 'table', 'laydate', 'element', 'common'], function() {
        var $ = layui.$;
        var $win = $(window);
        var table = layui.table;
        var admin = layui.admin;
        var laydate = layui.laydate;
        var element = layui.element;
        var common = layui.common;
        var resizeTimeout = null;
        var tableUrl = 'api/file/media/video/listpage';

        // 初始化表格
        function initTable() {
            table.render({
                elem: '#dataTable',
                id: 'dataTable',
                url: top.restAjax.path(tableUrl, []),
                width: admin.screen() > 1 ? '100%' : '',
                height: $win.height() - 90,
                limit: 20,
                limits: [20, 40, 60, 80, 100, 200],
                toolbar: '#headerToolBar',
                request: {
                    pageName: 'page',
                    limitName: 'rows'
                },
                cols: [
                    [
                        {type:'checkbox', fixed: 'left'},
                        {field:'rowNum', width:80, title: '序号', fixed: 'left', align:'center', templet: '<span>{{d.LAY_INDEX}}</span>'},
                        {field: 'fileId', width: 140, title: '文件ID', align:'center',
                            templet: function(row) {
                                var rowData = row[this.field];
                                if(typeof(rowData) === 'undefined' || rowData == null || rowData == '') {
                                    return '-';
                                }
                                return rowData;
                            }
                        },
                        {field: 'fileName', width: 140, title: '文件名称', align:'center',
                            templet: function(row) {
                                var rowData = row[this.field];
                                if(typeof(rowData) === 'undefined' || rowData == null || rowData == '') {
                                    return '-';
                                }
                                return '<a href="javascript:void(0);" lay-event="searchFileEvent"><i class="fa fa-video-camera"></i> '+ rowData +'</a>'
                            }
                        },
                        {field: 'fileType', width: 100, title: '文件类型', align:'center',
                            templet: function(row) {
                                var rowData = row[this.field];
                                if(typeof(rowData) === 'undefined' || rowData == null || rowData == '') {
                                    return '-';
                                }
                                return rowData;
                            }
                        },
                        {field: 'fileSize', width: 120, title: '文件大小', align:'center',
                            templet: function(row) {
                                var rowData = row[this.field];
                                if(typeof(rowData) === 'undefined' || rowData == null || rowData == '') {
                                    return '-';
                                }
                                return parseInt(rowData / 1000000) +'MB';
                            }
                        },
                        {field: 'widthHeight', width: 120, title: '分辨率', align:'center',
                            templet: function(row) {
                                return row.videoWidth +' ×️ '+ row.videoHeight;
                            }
                        },
                        {field: 'videoBitRate', width: 100, title: '比特率', align:'center',
                            templet: function(row) {
                                var rowData = row[this.field];
                                if(typeof(rowData) === 'undefined' || rowData == null || rowData == '') {
                                    return '-';
                                }
                                return rowData;
                            }
                        },
                        {field: 'videoDuration', width: 100, title: '时长', align:'center',
                            templet: function(row) {
                                var rowData = row[this.field];
                                if(typeof(rowData) === 'undefined' || rowData == null || rowData == '') {
                                    return '-';
                                }
                                var hour = parseInt(rowData / 3600000);
                                hour = hour < 10 ? '0'+ hour : hour;
                                var minute = parseInt(rowData % 3600000 / 60000);
                                minute = minute < 10 ? '0'+ minute : minute;
                                var second = parseInt(rowData % 3600000 % 60000 / 1000);
                                second = second < 10 ? '0'+ second : second;
                                return hour +':'+ minute +':'+ second;
                            }
                        },
                        {field: 'videoEncoder', width: 80, title: '编码', align:'center',
                            templet: function(row) {
                                var rowData = row[this.field];
                                if(typeof(rowData) === 'undefined' || rowData == null || rowData == '') {
                                    return '-';
                                }
                                return rowData;
                            }
                        },
                        {field: 'videoFrameRate', width: 80, title: '帧率', align:'center',
                            templet: function(row) {
                                var rowData = row[this.field];
                                if(typeof(rowData) === 'undefined' || rowData == null || rowData == '') {
                                    return '-';
                                }
                                return rowData;
                            }
                        },
                        {field: 'convertProgress', width: 120, title: '转换进度', align:'center', fixed: 'right',
                            templet: function(row) {
                                if(row.convertStatus === 'UN_CONVERTED') {
                                    return '0%';
                                }
                                if(row.convertStatus === 'CONVERTED') {
                                    return '100%';
                                }
                                return '<div class="layui-progress layui-progress-big layui-table-progress" lay-showPercent="true" lay-filter="progress_'+ row.fileId +'">\n' +
                                    '  <div class="layui-progress-bar layui-table-progress-bar layui-bg-blue">' +
                                    '    <span class="layui-progress-text">0%</span>' +
                                    '  </div>\n' +
                                    '</div>';
                            }
                        },
                        {field: 'convertStatus', width: 120, title: '转码状态', align:'center', fixed: 'right',
                            templet: function(row) {
                                var rowData = row[this.field];
                                if(typeof(rowData) === 'undefined' || rowData == null || rowData == '') {
                                    return '-';
                                }
                                if(rowData === 'UN_CONVERTED') {
                                    return '<button type="button" class="layui-btn layui-btn-xs" lay-event="convertEvent">开始转码</button>';
                                }
                                if(rowData === 'CONVERTING') {
                                    return '排队转码中...';
                                }
                                if(rowData === 'CONVERTED') {
                                    return '转码完成';
                                }
                                return rowData;
                            }
                        },
                    ]
                ],
                page: true,
                parseData: function(data) {
                    return {
                        'code': 0,
                        'msg': '',
                        'count': data.total,
                        'data': data.rows
                    };
                }
            });
        }
        // 重载表格
        function reloadTable(currentPage) {
            table.reload('dataTable', {
                url: top.restAjax.path(tableUrl, []),
                where: {
                    keywords: $('#keywords').val(),
                    startTime: $('#startTime').val(),
                    endTime: $('#endTime').val()
                },
                page: {
                    curr: currentPage
                },
                height: $win.height() - 90,
            });
        }
        // 初始化日期
        function initDate() {
            // 日期选择
            laydate.render({
                elem: '#startTime',
                format: 'yyyy-MM-dd'
            });
            laydate.render({
                elem: '#endTime',
                format: 'yyyy-MM-dd'
            });
        }
        // 删除
        function removeData(ids) {
            top.dialog.confirm('确定删除（同时删除源文件）吗？', function(index) {
                top.dialog.close(index);
                var layIndex;
                top.restAjax.delete(top.restAjax.path('api/file/media/video/delete/{ids}', [ids]), {}, null, function (code, data) {
                    top.dialog.msg(top.dataMessage.deleteSuccess, {time: 1000});
                    reloadTable();
                }, function (code, data) {
                    top.dialog.msg(data.msg);
                }, function () {
                    layIndex = top.dialog.msg(top.dataMessage.deleting, {icon: 16, time: 0, shade: 0.3});
                }, function () {
                    top.dialog.close(layIndex);
                });
            });
        }
        function sseConvertProgress() {
            var source = new EventSource(top.restAjax.path('api/file/media/video/get-convert-progress', []));
            source.addEventListener('message', function(e) {
                var data = JSON.parse(e.data);
                var fileId = data.fileId;
                var percent = data.percent;
                element.progress('progress_'+ fileId, percent +'%');
                if(percent >= 100) {
                    setTimeout(function() {
                        reloadTable();
                    }, 5000);
                }
            });
            source.addEventListener('open', function(e) {}, false);
            // 响应finish事件，主动关闭EventSource
            source.addEventListener('finish', function(e) {
                source.close();
            }, false);
            // 异常
            source.addEventListener('error', function(e) {
                if (e.readyState == EventSource.CLOSED) {
                    console.log("连接关闭");
                }
            }, false);
        }
        initTable();
        initDate();
        sseConvertProgress();

        // 事件 - 页面变化
        $win.on('resize', function() {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(function() {
                reloadTable();
            }, 500);
        });
        // 事件 - 搜索
        $(document).on('click', '#search', function() {
            reloadTable(1);
        });
        // 事件 - 增删改
        table.on('toolbar(dataTable)', function(obj) {
            var layEvent = obj.event;
            var checkStatus = table.checkStatus('dataTable');
            var checkDatas = checkStatus.data;
            if(layEvent === 'saveEvent') {
                top.dialog.open({
                    url: top.restAjax.path('route/file/media/video/upload', []),
                    title: '上传视频',
                    width: '500px',
                    height: '380px',
                    onClose: function() {
                        reloadTable();
                    }
                });
            } else if(layEvent === 'removeEvent') {
                if(checkDatas.length === 0) {
                    top.dialog.msg(top.dataMessage.table.selectDelete);
                } else {
                    var ids = '';
                    for(var i = 0, item; item = checkDatas[i++];) {
                        if(i > 1) {
                            ids += '_';
                        }
                        ids += item['fileId'];
                    }
                    removeData(ids);
                }
            }
        });
        table.on('tool(dataTable)', function(obj) {
            var data = obj.data;
            var event = obj.event;
            if(event === 'searchFileEvent') {
                if(data.fileType != 'mp4') {
                    top.dialog.msg('在线播放只支持MP4格式，请转码');
                    return;
                }
                var maxWidth = parseInt($win.width() * 0.8);
                var maxHeight = parseInt($win.height() * 0.8);
                var videoWidth = data.videoWidth;
                var videoHeight = data.videoHeight;
                var widthHeightProportion = videoWidth / videoHeight;

                var openWidth = videoWidth;
                var openHeight = videoHeight;
                if(videoWidth > videoHeight) {
                    if(videoWidth > maxWidth) {
                        openWidth = maxWidth;
                        openHeight = maxWidth / widthHeightProportion;
                    }
                    if(videoHeight > maxHeight) {
                        openHeight = maxHeight;
                        openWidth = widthHeightProportion * openHeight;
                    }
                } else {
                    if(videoHeight > maxHeight) {
                        openHeight = maxHeight;
                        openWidth = widthHeightProportion * openHeight;
                    }
                    if(videoWidth > maxWidth) {
                        openWidth = maxWidth;
                        openHeight = maxWidth / widthHeightProportion;
                    }
                }
                top.dialog.open({
                    url: top.restAjax.path('route/file/media/video/preview?fileId={fileId}', [data.fileId]),
                    title: false,
                    width: parseInt(openWidth) +'px',
                    height: parseInt(openHeight) +'px',
                    onClose: function() {}
                });
            } else if(event === 'convertEvent') {
                top.dialog.confirm('转码成功后，源文件将删除，确定转码吗？', function(index) {
                    top.dialog.close(index);
                    top.restAjax.put(top.restAjax.path('api/file/media/video/convert/{fileId}', [data.fileId]), {}, null, function (code, data) {
                        top.dialog.msg('正在转码...', {time: 1000});
                        reloadTable();
                    }, function (code, data) {
                        top.dialog.msg(data.msg);
                    }, function () {
                        layIndex = top.dialog.msg('正在提交...', {icon: 16, time: 0, shade: 0.3});
                    }, function () {
                        top.dialog.close(layIndex);
                    });
                });
            }
        });
    });
</script>
</body>
</html>