layui.use(['jquery', 'upload'], function () {
    let $ = layui.jquery;
    let upload = layui.upload;

    // 失去焦点刷新
    $('.upload-file-value').blur(function () {
        initPreviewList();
    });

    $('body').on('click', '.upload-choose-btn', function () {
        $('.upload-choose-btn').removeClass('choose-open');
        $(this).addClass('choose-open');
        let type = $(this).data('type') ? $(this).data('type') : 'all';
        let multiple = $(this).data('multiple') ? $(this).data('multiple') : false;
        let url = $(this).data('url') ? $(this).data('url') : '/manager/attachment/file';
        url += '?selected=true&type=' + type + '&multiple=' + multiple;
        openLayer(url, '素材列表', '80%', '80%');
    })

    // 多个上传组件 多个实例
    $('.upload-btn').each(function (index, item) {
        let that = $(this);
        let idx = 'upload-btn-' + index;
        that.addClass(idx);

        let url = that.data('url') ? that.data('url') : '/manager/upload/image';
        let field = that.data('field') ? that.data('field') : 'image_image';
        let multiple = that.data('multiple') ? that.data('multiple') : false;
        let accept = that.data('accept') ? that.data('accept') : 'images'; //images(图片)、file(所有文件)、video(视频)、audio(音频)
        let acceptMime = that.data('mimetype') ? that.data('mimetype') : 'images/*';
        let exts = that.data('exts') ? that.data('exts') : 'jpg|png|gif|bmp|jpeg';
        let maxSize = that.data('size') ? that.data('size') : 50 * 1204; //KB
        let size = maxSize; //size KB
        let number = that.data('number') ? that.data('number') : 0;
        let param = [];
        if (that.data('path') && that.data('path') !== undefined) {
            param['path'] = that.data('path')
        }

        upload.render({
            elem: '.upload-btn-' + index
            , url: url
            , auto: true
            , field: field
            , accept: accept
            , acceptMime: acceptMime
            , exts: exts
            , size: size
            , number: number
            , multiple: multiple
            , data: param
            , before: function (obj) {
                layer.load(2);
            }
            , done: function (res, index, upload) { //每个文件提交一次触发一次。详见“请求成功的回调”
                layer.closeAll('loading'); //关闭loading
                let item = this.item;
                let div = item.parents('.upload-file-div');
                let existsNotice = item.data('notice-exists');//已存在文件是否提示 默认不提示
                let callback = item.data('callback');//上传成功执行函数
                if (callback) {
                    eval(callback);
                }

                // 200=已存在文件 0=新上传成功
                if (res.code === 0 || res.code === 200) {
                    let inputValue = '';
                    // 如果是多文件上传  则追加 否则 替换
                    if (multiple) {
                        inputValue = $(div).find('.upload-file-value').val();
                        if (inputValue.length > 0) {
                            inputValue += ',';
                        }
                    }
                    inputValue += res.data.src;

                    $(div).find('.upload-file-value').val(inputValue);
                    initPreviewList();
                    if (existsNotice && res.code === 200) {
                        layer.alert(res.msg);
                    }
                } else {
                    layer.msg(res.msg);
                }
            }
        });
    })

    // 图片上传 删除
    $('body').on('click', '.del-preview-img', function () {
        $(this).parent('li').remove();
        refreshInputByUl();
    })
})

// 根据预览图片列表 刷新input值
function refreshInputByUl() {
    layui.use(['jquery'], function () {
        let $ = layui.jquery;

        $('.upload-file-div .preview-list').each(function () {
            let currentLiList = '';
            let liList = $(this).find('li');
            let len = liList.length;
            liList.each(function (index, item) {
                currentLiList += $(this).find('img').data('img');
                if (index !== (len - 1) || index !== 0) {
                    currentLiList += ',';
                }
            })
            //去除首尾逗号
            currentLiList = currentLiList.replace(/(^\,*)|(\,*$)/g, "");
            $(this).parents('.upload-file-div').find('.upload-file-value').val(currentLiList);
        })
    })
}

// 根据input 刷新预览图片列表
function initPreviewList() {
    layui.use(['jquery'], function () {
        let $ = layui.jquery;
        let input = $('.upload-file-value');
        if (input.length > 0) {
            input.each(function () {
                let that = $(this);
                let fileList = that.val();
                let fileArr = [];
                let html = '';

                if (fileList) {
                    fileArr = fileList.split(',');
                }
                if (fileArr.length > 0) {
                    $.each(fileArr, function (index, item) {
                        let ext = item.split('.');
                        let src = getFileRequestUrl(item);
                        let aLink = getFileRequestUrl(item);
                        ext = ext[ext.length - 1];

                        // let prefix = src.substr(0, 4)

                        // if (prefix !== 'http') {
                            if (ext !== 'jpg' && ext !== 'jpeg' && ext !== 'png' && ext !== 'gif' && ext !== 'bmp') {
                                src = '/static/manager/image/file.png';
                            }

                            if (ext === 'mp4' || ext === 'ogv' || ext === 'webm') {
                                src = '/static/manager/image/video.png';
                            }
                        // }

                        html += `<li class="layui-col-xs12 layui-col-md2 preview-li">
                                        <a href="${aLink}" target="_blank" class="preview-li-img">
                                            <img src="${src}" data-img="${item}">
                                        </a>
                                        <a href="javascript:;" class="layui-btn layui-btn-xs layui-btn-danger del-preview-img">
                                            <i class="fa fa-trash-o"></i> 删除
                                        </a>
                                    </li>`;
                    })
                }
                that.parents('.upload-file-div').find('.preview-list').html(html);
            })
        }
    })
}

initPreviewList();

/**
 * 动态加载元素触发绑定上传事件
 * @param eid 必须为控件ID
 */
function renderUpload(eid) {
    layui.use(['jquery', 'upload'], function () {
        let $ = layui.jquery, upload = layui.upload;
        let url = '/manager/upload/image';
        let field = 'image_image';
        let multiple = false;
        let accept = 'images';
        let acceptMime = 'images/*';
        let exts = 'jpg|png|gif|bmp|jpeg';
        let size = 10 * 1024; //size KB

        let that = $(eid);

        if (that.data('url')) {
            url = that.data('url');
        }
        if (that.data('field')) {
            field = that.data('field');
        }
        if (that.data('multiple')) {
            multiple = that.data('multiple');
        }
        if (that.data('accept')) {
            accept = that.data('accept');
        }
        if (that.data('mimetype')) {
            acceptMime = that.data('mimetype');
        }
        if (that.data('exts')) {
            exts = that.data('exts');
        }
        if (that.data('number')) {
            number = that.data('number');
        }


        upload.render({
            elem: eid
            , url: url
            , auto: true
            , field: field
            , accept: accept
            , acceptMime: acceptMime
            , exts: exts
            , size: size
            , number: 0
            , multiple: multiple
            , before: function (obj) {
                layer.load(2);
            }
            , done: function (res, index, upload) {
                layer.closeAll('loading');
                let item = this.item;
                let div = item.parents('.upload-file-div');
                if (res.code === 0) {
                    let inputValue = '';
                    // 如果是多文件上传  则追加 否则 替换
                    if (multiple) {
                        inputValue = $(div).find('.upload-file-value').val();
                        if (inputValue.length > 0) {
                            inputValue += ',';
                        }
                    }
                    inputValue += res.data.src;

                    $(div).find('.upload-file-value').val(inputValue);
                    initPreviewList();
                } else {
                    layer.msg(res.msg);
                }
            }
        });
    });
}