<link rel="stylesheet" href="{{ asset('data/assets/css/jquery.toast.min.css') }}">
<div class="modal fade" id="media-dialog-modal" tabindex="-1" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="true"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">媒体库</h4>
                <div class="modal-header-form">
                    <div class="form-group pr-10">
                        {!! Form::select('type', ['' => '媒体类型'] + config('system.mediaType'), null, ['class'=>'form-control autosize']) !!}
                    </div>
                    <div class="form-group pr-10">
                        {!! Form::text('file_name', null, ['class'=>'form-control', 'placeholder'=>'请输入媒体名称']) !!}
                    </div>
                    <button class="btn btn-primary" id="search-btn">
                        <i class="iconfont icon-sousuo2"></i>
                    </button>
                    <button class="btn btn-info ml-10" id="media-upload">媒体上传</button>
                </div>
            </div>
            <div class="modal-body clearfix">
                <div class="media-wrap">
                    <div class="media-wrap-left">
                        <ul class="media-lists">
                        </ul>
                        <div class="media-list-loading"><img src="/data/assets/images/loading6.gif" alt=""></div>
                        <div class="select-box"></div>
                    </div>
                    <div class="media-wrap-right" style="width: 240px;">
                        
                        <div class="media-wrap-right-box">
                            <div class="media-preview-img"></div>
                            <ul class="media-preview-list"></ul>
                        </div>
                    </div>
                </div>
                <div id="upload-list"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary btn-modal-ok" id="submit-btn">确定</button>
                <button class="btn btn-default btn-modal-cancel btn-modal-close" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>
<!-- 预览 Modal -->
<div class="modal fade" id="media-preview-modal" tabindex="-1" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="true"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title"></h4>
            </div>
            <div class="modal-body clearfix">

            </div>
        </div>
    </div>
</div>
<!-- 图片属性 -->
<div class="modal fade" id="media-attr-modal" tabindex="-1" role="dialog">
  <div class="modal-dialog" style="width: 520px !important;">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="true"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">图片属性</h4>
      </div>
      <div class="modal-body clearfix">
        <div class="form-group form-horizontal clearfix">
          <label class="col-sm-2 control-label">地址：</label>
          <div class="col-sm-10">
            {!! Form::text('url', null, ['class'=>'form-control', 'readonly'=>'readonly', 'id'=>'imageUrl']) !!}
          </div>
        </div>
        <div class="form-group form-horizontal">
          <label class="col-sm-2 control-label">描述：</label>
          <div class="col-sm-10">
            {!! Form::text('alt', null, ['class'=>'form-control', 'id'=>'imageAlt']) !!}
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary attr-ok">确定</button>
        <button class="btn btn-default btn-modal-cancel btn-modal-close" data-dismiss="modal">取消</button>
      </div>
    </div>
  </div>
</div>
<script src="{{ asset('data/assets/js/jquery.toast.min.js') }}"></script>
<script>
    var relatedTarget;
    $('#media-dialog-modal').on('show.bs.modal',function(e){
        $relatedTarget = $(e.relatedTarget)
        window.selectArr = []
        $(".media-wrap-right-box").css('opacity', 0);
        $('.media-dialog-item').removeClass('on')
    });
    $(function() {
        var scrollStatus = false
        var HOME_URL  = '{{ url('/') }}';
        var url_upload = "{{ url('admin/upload') }}";
        var mediaTypeObj = <?php echo json_encode(config('system.media')); ?>;
        var isDown, isCtrl;

        var bytesToSize = function (bytes, is_float = true) {
            if (bytes === 0) return '0 B';
            var k = 1024,
                sizes = ['B', 'KB', 'MB', 'G', 'TB', 'PB', 'EB', 'ZB', 'YB'],
                i = Math.floor(Math.log(bytes) / Math.log(k));
            var result_size = is_float ? (bytes / Math.pow(k, i)).toPrecision(3) : parseInt(bytes / Math.pow(k, i))
            return result_size + ' ' + sizes[i];
        }

        var temp_data = [];
        var render_list = function (data) {
            var html = '';
            for (var i = 0; i < data.length; i++) {
                var obj = data[i];
                html += '<li class="media-item media-dialog-item" data-json=\''+JSON.stringify(obj)+'\'>'
                html += '<div class="media-item-img">';
                if (obj.type === 'image') {
                    html += '<img src="'+obj.url+'" alt="'+obj.file_name+'">';
                }
                if (obj.type === 'video') {
                    html += '<video src="'+obj.url+'" poster="'+obj.url+'?x-oss-process=video/snapshot,t_1000,f_jpg,w_400,m_fast,ar_auto"></video><i class="iconfont icon-a-sanjiaoxing1"></i>';
                }
                if (obj.type === 'doc') {
                    html += '<img src="/data/assets/images/file_l.png" alt="">';
                }
                html += '<div class="actions">';
                html += '<i class="iconfont icon-fangda"></i>'
                html += '<i data-id="'+obj.id+'" class="iconfont icon-pinhetuxing1"></i>'
                html += '</div>'
                html += '</div>'
                html += '<p>'+obj.file_name+'</p>'
                html += '</li>'
            }
            return html
        }
        var get_data = function (params) {
            if (isDown) return
            var data = params || {}
            $(".media-list-loading").css('display', 'flex');
            $.ajax({
                url: "{{url('/admin/media/lists')}}",
                data: data,
                success: function (res) {
                    temp_data = res
                    var renderHtml = render_list(res)
                    $(".media-lists").append(renderHtml)
                    $(".media-list-loading").css('display', 'none');
                    scrollStatus = false
                }
            })
        }
        get_data();

        window.selectArr = []
        // 右侧描述
        $(".media-lists").on('click', '.media-dialog-item', function (e){
            e.stopPropagation();
            var obj = JSON.parse($(this).attr('data-json'));
            if (!obj) return
            if (isCtrl) {
                if ($(this).hasClass('on')) {
                    $(this).removeClass('on')
                    var index = selectArr.findIndex(function (item) {
                        return item.id === obj.id
                    })
                    selectArr.splice(index, 1)
                } else {
                    $(this).addClass('on')
                    selectArr.push(obj)
                }
                if (selectArr.length > 0) {
                    $(".media-wrap-right-box").css('opacity', 1);
                    $(".media-preview-img").html('<img src="/data/assets/images/file_l.png" />')
                    $(".media-preview-list").html("<li>已选择文件数<span>"+selectArr.length+"</span></li>")
                } else {
                    $(".media-wrap-right-box").css('opacity', 0);
                }
            } else {
                $(this).addClass('on').siblings().removeClass('on')
                selectArr[0] = obj

                if (obj.type === 'image') {
                    $(".media-preview-img").html('<img src="'+obj.url+'" />')
                }
                if (obj.type === 'doc') {
                    $(".media-preview-img").html('<img src="/data/assets/images/file_l.png" />')
                }
                if (obj.type === 'video') {
                    $(".media-preview-img").html('<i class="iconfont icon-a-sanjiaoxing1"></i><video src="'+obj.url+'"></video>')
                }
               var preview_html = '<li>文件类型<span>'+obj.type+'</span></li>'
               preview_html+='<li>名称<span>'+obj.file_name+'</span></li>'
               if (obj.type === 'image') {
                    var specs = obj.meta.width+' x '+obj.meta.height+'px'
                    preview_html+='<li>尺寸<span>'+specs+'</span></li>'
                }
                preview_html+= '<li>大小<span>'+bytesToSize(obj.size)+'</span></li>'
                $(".media-preview-list").html(preview_html)
                $(".media-wrap-right-box").css('opacity', 1);
            }
        })

        $(".media-lists").on('click', '.icon-pinhetuxing1', function (e){
            e.stopPropagation();
            if (!confirm('确定要删除吗？')) return
            var id = $(this).attr('data-id');
            $.ajax({
                url: '{{url("admin/media")}}/'+id,
                type: 'delete',
                success: function (res) {
                    if (res.status == 'success') {
                        $.toast({
                            text: "删除成功！",
                            icon: 'success',
                            hideAfter: 1000,
                            position: 'top-center',
                            loader: false,
                        });
                        $(".media-lists").html('')
                        get_data()
                    }
                }
            })
        })

        $(".media-lists").on('click', '.icon-fangda', function (e){
            e.stopPropagation();
            var obj = JSON.parse($(this).parents('li').attr('data-json'))
            $("#media-preview-modal .modal-title").text(obj.file_name)
            if (obj.type === 'image') {
                $("#media-preview-modal .modal-body").html("<img src='"+obj.url+"' />")
            }
            if (obj.type === 'video') {
                $("#media-preview-modal .modal-body").html("<video src='"+obj.url+"' controls></video>")
            }
            if (obj.type === 'doc') {
                $("#media-preview-modal .modal-body").html("<img src='/data/assets/images/file_l.png' />")
            }
            $("#media-preview-modal").modal('show')
        })
        $("#media-preview-modal").on('hide.bs.modal', function(){
            $("#media-preview-modal .modal-body").html('')
        })

        // 滚动加载
        var mediaWrapLeftDom = document.querySelector('.media-wrap-left')
        mediaWrapLeftDom.addEventListener('scroll',function (e) {
            if (scrollStatus) return
            if (e.target.scrollTop + e.target.offsetHeight + 10 >= e.target.scrollHeight) {
                scrollStatus =true
                if (!temp_data.length || temp_data.length < 30) return
                var type = $("[name='type']").val()
                var file_name = $("[name='file_name']").val()
                const last_id = temp_data.pop().id
                get_data({last_id: last_id, type: type, file_name: file_name})
            }
        })

        $("#search-btn").click(function () {
            var type = $("[name='type']").val()
            var file_name = $("[name='file_name']").val()
            $(".media-lists").html('')
            get_data({type: type, file_name: file_name})
        })

        var previewImage = function (file, callback) {
            if (file.type.indexOf('video') !== -1) {
                callback && callback(HOME_URL + '/data/assets/images/video_l.png');
            } else {
                if (!file || !/image\//.test(file.type)) {
                    callback && callback(HOME_URL + '/data/assets/images/file_l.png');
                }
            }
            if (file.type == 'image/gif') {
                var fr = new moxie.file.FileReader();
                fr.onload = function(){
                    callback(fr.result);
                    fr.destroy();
                    fr = null;
                }
                fr.readAsDataURL(file.getSource());
            } else {
                var preloader = new moxie.image.Image();
                preloader.onload = function() {
                    preloader.downsize(300, 300);
                    var imgsrc = preloader.type == 'image/jpeg' ? preloader.getAsDataURL('image/jpeg', 80) : preloader.getAsDataURL();
                    callback && callback(imgsrc);
                    preloader.destroy();
                    preloader = null;
                }
                preloader.load(file.getSource());
            }
        }
        // 允许上传的类型
        var mediaTypeArr = function () {
            var arr = []
            for (var key in mediaTypeObj) {
                if (key === 'media') continue
                arr = arr.concat(mediaTypeObj[key])
            }
            return arr
        }

        var editorMediaTypeArr = function () {
            var arr = []
            for (var key in mediaTypeObj) {
                if (key === 'doc') continue
                arr = arr.concat(mediaTypeObj[key])
            }
            return arr
        }

        // 上传文件
        var uploader = new plupload.Uploader({
            runtimes : 'html5',
            browse_button : 'media-upload',
            url : url_upload,
            multi_selection: true,
            multipart_params: {'type': 1},
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            init: {
                BeforeUpload: async function(up, files) {
                    var suffix = files.name.substr(files.name.lastIndexOf('.')+1).toLowerCase()
                    var mediaKey = ''
                    for (var key in mediaTypeObj) {
                        if (key === 'media') continue
                        if (mediaTypeObj[key].indexOf(suffix) !== -1) {
                            mediaKey = key
                            break;
                        }
                    }
                    if (mediaKey === 'image') {
                        up.settings.multipart_params.type = 1;
                    } else if (mediaKey === 'doc') {
                        up.settings.multipart_params.type = 2;
                    } else if (mediaKey === 'video') {
                        up.settings.multipart_params.type = 3;
                    }
                },
                FilesAdded: function(up, files) {
                    if (files.length > 20) {
                        $('#upload-list').html("");
                        swal('一次最多只能上传20个文件！');
                        return false;
                    }
                    $('#upload-list').html("");
                    // 显示添加进来的文件名
                    let title = '<div class="title">正在上传<strong class="num">0</strong>/<strong class="total">'+ files.length +'</strong>项目<span class="close">&times;</span></div>';
                    $(title).prependTo('#upload-list');
                    let ul = '<ul></ul>';
                    $(ul).appendTo('#upload-list');
                    $.each(files, function(key, value){
                        // 获取文件后缀
                        var suffix = value.name.substr(value.name.lastIndexOf('.')+1).toLowerCase()
                        value.fullBlob = value.getNative()
                        let file_name = value.name;
                        let file_size = bytesToSize(parseInt(value.size));
                        if (mediaTypeArr().indexOf(suffix) === -1) {
                            swal('不支持的文件格式！');
                            return
                        }
                        let html = '<li id="file-' + value.id +'"><div class="img"></div><div class="name">' + file_name + '</div><div class="size">' + file_size + '</div><div class="state"><img src="'+HOME_URL+'/data/assets/images/loading6.gif"></div></li>';
                        $(html).appendTo('#upload-list ul');
                        previewImage(value, function(imgsrc){
                            $('#file-' + value.id + ' .img').append('<img src="'+ imgsrc +'" />');
                        })
                    });
                    up.start();
                },
                FileUploaded: function(up, file, data) {
                    var response = JSON.parse(data.response)
                    if (response && response.state == "SUCCESS") {
                        let num = parseInt($("#upload-list .title").find('.num').html()) + 1;
                        $("#upload-list .title").find('.num').html(num);
                        $("#upload-list").find('#file-' + file.id + ' .state').html('<i class="iconfont icon-xiaoyan1"></i>');
                    } else {
                        $('#upload-list').html("");
                        swal(response.message);
                    }
                },
                UploadComplete: function () {
                    $(".media-lists").html('')
                    $('#upload-list').html("");
                    get_data();
                }
            }
        })
        uploader.init();
        $("#upload-list").on('click', '.close', function(){
            $("#upload-list").html("");
        })
        
        // 多选功能
        @if (isset($multi))
        if (window.mediaType !== 'video') {
            window.addEventListener('keydown', function(e) {
                if (e.keyCode === 17) isCtrl = true
            })
            window.addEventListener('keyup', function() {
                isCtrl = false
            });

            // 框选
            var startX, startY, moveX, moveY, domRect;
            var mediaWrapLeftDom = document.querySelector(".media-wrap-left")
            mediaWrapLeftDom.addEventListener('mousedown', handleMouseDown, false)
            function handleMouseDown(e) {
                e.stopPropagation();
                if (isCtrl) return
                $(".media-item").removeClass('on')
                isDown = true
                // 确定鼠标按下的坐标
                startX = e.pageX;
                startY = e.pageY;
                moveX = 0
                moveY = 0
                selectArr = []
                $(".media-wrap-right-box").css('opacity', 0);
                domRect = mediaWrapLeftDom.getBoundingClientRect()
                mediaWrapLeftDom.addEventListener('mousemove', handleMousemove);
                mediaWrapLeftDom.addEventListener('mouseup', handleMouseup);
            }
            function handleMousemove(e) {
                e.stopPropagation();
                // 确定鼠标移动的坐标
                moveX = e.pageX
                moveY = e.pageY
                // 临界值判断，会根据弹窗位置变化
                if (e.pageX > 1120) moveX = 1120
                if (e.pageY > 500) moveY = 500
                var left = Math.min(startX, moveX)
                var top = Math.min(startY, moveY)
                $(".select-box").css({
                    'left': left - domRect.x + 'px',
                    'top': top - domRect.y + 'px',
                    'width': Math.abs(moveX - startX) + 'px',
                    'height': Math.abs(moveY - startY) + 'px'
                }).show();
            }
            function handleMouseup(e) {
                e.stopPropagation();
                isDown = false
                mediaWrapLeftDom.removeEventListener('mousemove', handleMousemove);
                mediaWrapLeftDom.removeEventListener('mouseup', handleMouseup);
                if (moveX < 10 && moveY < 10) return
                $(".media-item").each(function () {
                    var itemRect = $(this)[0].getBoundingClientRect()
                    if (
                        (moveX > startX && startX < itemRect.x + itemRect.width && moveX > itemRect.x && moveY > itemRect.y)
                        || (startX > moveX && startX > itemRect.x + itemRect.width && moveY < itemRect.y + itemRect.height && startY > itemRect.y  &&  moveX < itemRect.x + itemRect.width && moveY < itemRect.y + itemRect.height)
                    ) {
                        $(this).addClass('on')
                        selectArr.push(JSON.parse($(this).attr('data-json')))
                    }
                })
                if (selectArr.length > 0) {
                    $(".media-wrap-right-box").css('opacity', 1);
                    $(".media-preview-img").html('<img src="/data/assets/images/file_l.png" />')
                    $(".media-preview-list").html("<li>已选择文件数<span>"+selectArr.length+"</span></li>")
                } else {
                    $(".media-wrap-right-box").css('opacity', 0);
                }
                $(".select-box").hide();
            }
        }
        @endif

        // 弹窗里选择文件
        $("#submit-btn").click(function () {
            if (selectArr.length == 0) {
                swal("您还未选择文件")
                return
            }
            var typeStr = "{{$type}}";
            if (window.mediaType === 'image') typeStr = 'jpg,gif,png'
            if (window.mediaType === 'video') typeStr = 'mp4,ogg,webm'
            if (window.mediaType === 'file') typeStr = 'xls/xlsx,doc/docx,ppt/pptx,pdf,zip,rar'
            var status = selectArr.every(function (item) {
                if (window.editorMyMediaClick) {
                    return editorMediaTypeArr().indexOf(item.extension.toLowerCase()) > -1
                }
                return typeStr.indexOf(item.extension.toLowerCase()) > -1
            })
            if (!status) {
                swal({
                    title: '',
                    text: '请选择'+typeStr+'类型的文件'
                })
                return
            }
            // 附件上传
            if (window.mediaType === 'video' || window.mediaType === 'file') {
                window.mediaType = null
                $("[name='filepath']").val(selectArr[0].url)
                $("[name='filesize']").val(bytesToSize(selectArr[0].size))
                $("#media-dialog-modal").modal('hide')
                return
            }
            // 富文本触发的弹窗，关闭后不在这里做处理
            if (window.editorMyMediaClick) {
                $("#imageUrl").val(selectArr[0].url)
                $("#imageAlt").val(selectArr[0].file_name)
                $("#media-dialog-modal").modal('hide')
                $("#media-attr-modal").modal('show')
                return
            }
            // 广告
            if (window.mediaType === 'ad') {
                $("#" + window.adImgId).attr('src', selectArr[0].url).next().val(selectArr[0].url)
                $("#media-dialog-modal").modal('hide')
                return
            }
           var inputName = $relatedTarget.parents(".upload-wrap").attr("data-name");
           var html = ""
           for (var i = 0; i < selectArr.length; i++) {
                var item = selectArr[i];
                html += '<li class="thumbnail thumb-imgs">'
                html+= '<input name="'+inputName+'" value="'+item.url+'" type="hidden" class="uploadfiles-input">'
                if (item.type === 'video') {
                    html += '<a class="thumbnail-img"><video src="'+item.url+'" poster="'+item.url+'?x-oss-process=video/snapshot,t_1000,f_jpg,w_400,m_fast,ar_auto" width="80" height="80"></video><i class="iconfont icon-a-sanjiaoxing1"></i></a>';
                }
                if (item.type === 'image') {
                    html+= '<a class="thumbnail-img"><img src="'+item.url+'"></a>'
                }
                html+= '<a class="thumbnail-remove" data-index="'+i+'" href="javascript:;">删除</a>'
                html+='</li>'
           }
           $relatedTarget.parents('.upload-wrap').find('.upload-wrap-lists').append(html)
           $("#media-dialog-modal").modal('hide')
           @if(!isset($multi))
           $relatedTarget.parent().addClass('display-none')
           @endif
            if (window.single_upload == 1) {
               $relatedTarget.parent().addClass('display-none')
           }
        })
        $(".attr-ok").click(function () {
            selectArr[0].file_name = $("#imageAlt").val()
            window.setEditorHtml = true
            $("#media-attr-modal").modal('hide')
        })
        // 删除图片
        $(".upload-wrap-lists").on('click', '.thumbnail-remove', function (e) {
            e.preventDefault();
            var index = $(this).attr('data-index')
            selectArr.splice(index, 1)
            $(this).parents('.thumbnail').remove()
            $(e.delegateTarget).prev().removeClass('display-none')
        })

        $('#media-dialog-modal').on('hidden.bs.modal', function () {
            $('.input-assistant').hide();
            window.editorMyMediaClick = null
            window.mediaType = null
        })
    })
</script>