@extends('admin.master')
@section('style')
    <link rel="stylesheet" href="{{ asset('data/assets/css/jquery.toast.min.css') }}">
@endsection

@section('top')
    <div class="top-breadcrumb">
        <h5>媒体库</h5>
    </div>
@endsection

@section('ordersearch')
    <div class="order-search mb-10">
        <div class="clearfix">
            <div class="pull-left">
                {!! Form::model($where, ['method'=>'get', 'class'=>'form-inline', 'id' => 'form-select']) !!}
                <div class="form-group pr-10">
                    {!! Form::select('type', ['' => '媒体类型'] + config('system.mediaType'), null, ['id'=>'flag', 'class'=>'form-control autosize']) !!}
                </div>
                <div class="form-group pr-10">
                    {!! Form::text('file_name', null, ['class'=>'form-control len wd-search', 'id'=>'kw', 'placeholder'=>'请输入媒体名称']) !!}
                </div>
                @if(auth()->user()->isMaster())
                <div class="form-group">
                  <div class="pretty p-default">
                    {!! Form::checkbox('delete', 1, null) !!}
                    <div class="state p-success"><label>已删除</label></div>
                  </div>
                </div>
                @endif
                <button type="submit" class="btn btn-primary">
                    <i class="iconfont icon-sousuo2"></i>
                </button>
                {!! Form::close() !!}
                <button class="btn btn-info" id="media-upload">媒体上传</button>
            </div>
            <div class="pull-right">
                <div class="space-use">
                    <p>已使用：</p>
                    @if(!$data['sizes']->isEmpty())
                    @foreach($data['sizes'] as $key=>$size)
                        <p>{{config('system.mediaType')[$key]}} <span data-size="{{$size}}"></span></p>
                    @endforeach
                    @else
                    <p><span>0KB</span></p>
                    @endif
                </div>
            </div>
        </div>
    </div>
@endsection

@section('content')
    <div class="media-wrap">
        <div class="media-wrap-left">
            @if(!$data['data']->isEmpty())
            <ul class="media-lists">
                @foreach($data['data'] as $item)
                    <li class="media-item" data-json="{{$item}}">
                        <div class="media-item-img">
                            @if($item->type == 'image')
                            <img src="{{$item->url}}" alt="{{$item->file_name}}">
                            @elseif($item->type == 'video')
                            <video src="{{$item->url}}" poster="{{$item->url}}?x-oss-process=video/snapshot,t_1000,f_jpg,w_400,m_fast,ar_auto">
                                您的浏览器不支持 video 标签。
                            </video>
                            <i class="iconfont icon-a-sanjiaoxing1"></i>
                            @else
                                <img src="/data/assets/images/file_l.png" alt="">
                            @endif
                            <div class="actions">
                              @if($item->deleted_at > 0)
                                @if(auth()->user()->isMaster())
                                <a href="javascript:void(0)" class="recover" style="color: #fff;width: 100%;text-align: center" data-id="{{$item->id}}">恢复</a>
                                @endif
                              @else
                                <i class="iconfont icon-fangda"></i>
                                <i data-id="{{$item->id}}" class="iconfont icon-pinhetuxing1"></i>
                              @endif
                            </div>
                        </div>
                        <p>{{$item->file_name}}</p>
                    </li>
                @endforeach
            </ul>
            <div class="media-paginate">
                <div class="pagination-info">共有{{ $data['data']->total() }}条</div>
                {!! $data['data']->appends($where)->render() !!}
            </div>
            @else
            <div class="text-center">
                暂无数据
            </div>
            @endif
        </div>
        <div class="media-wrap-right">
            <div class="media-wrap-right-box">
                <div class="media-preview-img"></div>
                <ul class="media-preview-list">
                    <li>文件类型<span class="media-preview-type"></span></li>
                    <li>名称<span class="media-preview-name"></span></li>
                    <li class="media-preview-specs">尺寸<span></span></li>
                    <li>大小<span class="media-preview-size"></span></li>
                    <li>URL<span class="media-preview-url">复制</span></li>
                </ul>
            </div>
        </div>
    </div>
    <div id="upload-list"></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>
@endsection

@section('foot')
<script src="{{ asset('data/assets/js/clipboard.min.js') }}"></script>
<script src="{{ asset('data/assets/js/jquery.toast.min.js') }}"></script>
<script>
    $(function (){
        var HOME_URL  = '{{ url('/') }}';
        var url_upload = "{{ url('admin/upload') }}";
        var mediaTypeObj = <?php echo json_encode(config('system.media')); ?>;
        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];
        }

        // 计算已使用空间单位换算
        $(".space-use span[data-size]").each(function () {
            var size = $(this).attr('data-size')
            var formatSize = bytesToSize(size)
            $(this).text(formatSize)
        })

        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 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)
                    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){
                        value.fullBlob = value.getNative()
                        let file_name = value.name;
                        let file_size = bytesToSize(parseInt(value.size));
                        var suffix = file_name.substr(file_name.lastIndexOf('.')+1)
                        if (mediaTypeArr().indexOf(suffix) === -1) {
                            swal(file_name + '格式不正确！');
                            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>');
                        console.log(num, up.files.length)
                    } else {
                        $('#upload-list').html("");
                        swal(response.message);
                    }
                },
                UploadComplete: function () {
                    window.location.reload()
                }
            }
        })
        uploader.init();
        $("#upload-list").on('click', '.close', function(){
            $("#upload-list").html("");
        })

        // 右侧描述
        $(".media-item").click(function (){
            var obj = JSON.parse($(this).attr('data-json'));
            if (!obj) return
            $(this).addClass('on').siblings().removeClass('on')

            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>')
            }
            $(".media-preview-type").text(obj.type)
            $(".media-preview-name").text(obj.file_name)
            if (obj.type === 'image') {
                var specs = obj.meta.width+' x '+obj.meta.height+'px'
                $(".media-preview-specs").show().find('span').text(specs)
            } else {
                $(".media-preview-specs").hide()
            }
            $(".media-preview-size").text(bytesToSize(obj.size))
            $(".media-preview-url").attr('data-clipboard-text',obj.url)
            $(".media-wrap-right-box").css('opacity', 1)
        })
        var clipboard = new ClipboardJS(".media-preview-url");
        clipboard.on('success', function(e) {
            $.toast({
                text: "路径复制成功！",
                icon: 'success',
                hideAfter: 1500,
                position: 'top-center',
                loader: false,
            });
            e.clearSelection();
        })

        $(".icon-pinhetuxing1").click(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,
                        });
                        setTimeout(function(){
                            window.location.reload()
                        }, 1000)
                    }
                }
            })
        })

        $(".icon-fangda").click(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('')
        })

        $(".recover").click(function (e) {
            e.stopPropagation();
            if (!confirm('确定要恢复吗？')) return
            var id = $(this).attr('data-id');
            $.ajax({
                url: '{{url("admin/media/recover")}}/'+id,
                type: 'post',
                success: function (res) {
                    if (res.status == 'success') {
                        $.toast({
                            text: "恢复成功！",
                            icon: 'success',
                            hideAfter: 1000,
                            position: 'top-center',
                            loader: false,
                        });
                        setTimeout(function(){
                            window.location.reload()
                        }, 1000)
                    }
                }
            })
        })
    })
</script>
@endsection
