/**
 * 人人站CMS
 * ============================================================================
 * 版权所有 2015-2030 山东康程信息科技有限公司，并保留所有权利。
 * 网站地址: http://www.rrzcms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 */
(function ($) {

    var imgSpace = function (callback, multiple) {
        var options = $.isPlainObject(callback) ? callback : {};
        if ($.isFunction(callback)) {
            options.callback = callback;
            options.multiple = multiple || false;
        }

        if (this === window) {
            return new imgSpace(options);
        }
        this.init(options);
        return this;
    };
    imgSpace.prototype = {
        $elem: $(window),
        multiple: false,
        watermark: true,
        url: window._global.root + '/Index/imgspace',
        uploadInst: null,
        platform: 'local',//存储类型
        uploadUrl: window._global.root + '/Upload/index?type=images',
        callback: function (url) {
            $('[lay-upvalue]', this).val(url);
            $('[lay-uphref]', this).attr('href', url);
            $('[lay-upsrc]', this).attr('src', url);
        },
        init: function (options) {
            this.multiple = options.multiple || false;
            this.watermark = (options.watermark + '') === 'false' ? false : true;

            if (options.elem) this.$elem = $(options.elem);
            var $elem = this.$elem;
            this.callback = options.callback || $elem.data('callback') || this.callback;
            this.openWindow();
        },
        openWindow: function () {
            var url = this.url + (this.multiple ? '?multiple=1' : '');
            if (this.watermark === false) {
                url = url + (url.indexOf('?') > 0 ? '&' : '?') + 'watermark=false';
            }
            var $elem = this.$elem, callback = this.callback, that = this;
            var options = {
                type: 0,
                title: '图片空间',
                area: ['850px', '550px'],
                success: function (layero, index) {
                    window.layui && layui.render && layui.render();
                    that.bindEvents(layero);
                },
                yes: function (layero, index) {
                    var slist = layero.data('slist') || [];
                    if (!slist.length) {
                        $.msg('请先选择图片或上传图片！');
                        return false;
                    }
                    callback.call($elem, slist[0], slist);
                    $elem.trigger('change');
                }
            };
            $.loading.show();
            $.get(url, function (rs) {
                $.loading.hide();
                options.msg = rs;
                $.page(options)
            });
        },
        bindEvents: function ($view) {
            var $elem = this.$elem, callback = this.callback, multiple = this.multiple, url = this.url,
                That = this;
            //绑定上传事件
            this.uploadInst = layui.uploadRender({
                elem: $('button.btn-lay-upload', $view),
                url: That.uploadUrl,
                data: {
                    platform: function () {
                        return That.platform;
                    },
                    watermark: function () {
                        return That.watermark;
                    }
                },
                callback: function (res) {
                    res && res.msg && $.showMsg(res.code, res.msg);
                    if (res && res.url) {
                        callback.call($elem, res.url, res.data ? res.data : []);
                        $elem.trigger('change');
                        $('.layui-layer-close', $view).trigger('click');
                    }
                    return false;
                }
            });
            //多图上传处理
            multiple && $('.layui-upload-file', $view).attr('multiple', 'multiple');

            //重载水印设置
            That.watermark = $('[name="isWatermark"]', $view).prop('checked') || false;
            //水印设置事件
            layui.form.on('checkbox(imgspace-watermark)', function (data) {
                That.watermark = data.elem.checked;
            });

            //页签切换事件
            $('.layui-card-header .layui-tab-title>li', $view).on('click', function () {
                var data = $(this).data(), $content = $('.layui-tab-item.type-' + data.type, $view),
                    $this = $(this);
                if (data.url && !data.loaded) {
                    $.openpage(data.url, {}, function (res) {
                        $content.html(res).data('url', data.url);
                        $('.js-path.dir-select', $content).trigger('click');
                        $this.data('loaded', true);
                    });
                } else {
                    $('.js-path.dir-select', $content).trigger('click');
                }
                That.platform = data.type;//存储类型
                //重置选中数据
                $view.data('slist', $content.data('slist') || []);
                //网络图片隐藏上传按钮
                $('div.btn-up.layui-form', $view)[data.type == 'network' ? 'hide' : 'show']();
                // setTimeout(function () {
                //     $('.img-list .item img', $content).lazyload({
                //         data_attribute: 'src',
                //         container: $('.img-list', $content)
                //     });
                // }, 100);
            });

            $('.layui-card-header .layui-tab-title>li.layui-this', $view).trigger('click');

            //定义重置选中数据事件
            $('.layui-tab-content>.layui-tab-item', $view).on('change', function (e, list) {
                $(this).data('slist', list || []);
                $view.data('slist', list || []);
            });

            //文件夹切换事件
            $view.on('click', '.js-path', function () {
                var $this = $(this), $p = $this.closest('.layui-tab-item'), name = $this.data('path'),
                    list = $this.data('list');
                if (list) {
                    $this.addClass('dir-select').siblings().removeClass('dir-select');
                    $('.img-list', $p).html(list);
                    $p.trigger('change');
                    $('.img-list .item img', $p).lazyload({
                        data_attribute: 'src',
                        container: $('.img-list', $p),
                    });
                    return false;
                }
                var _url = $p.data('url') || url;
                $.loading.show();
                $.post(_url, { name: name }, function (rs) {
                    $.loading.hide();
                    $this.data('list', rs);
                    $('.img-list', $p).html(rs);
                    $p.trigger('change');
                    $this.addClass('dir-select').siblings().removeClass('dir-select');
                    $('.img-list .item img', $p).lazyload({
                        data_attribute: 'src',
                        container: $('.img-list', $p)
                    });
                });
            });

            $('.layui-tab-item.layui-show .js-path.dir-select', $view).trigger('click');

            //===网络图片事件处理--开始
            $('.type-network .js-webpath', $view).change(function () {
                var url = $.trim($(this).val()), $p = $(this).closest('.layui-tab-item');
                if (/^(http|\/\/)/i.test(url)) {
                    $('.js-ylwebpath', $p).attr('src', url);
                } else {
                    $.msg('请填写正确的地址！');
                    $(this).val('');
                }
            });

            $('.type-network .js-ylwebpath', $view).on('load', function () {
                var slist = [$(this).attr('src')];
                $(this).closest('.layui-tab-item').trigger('change', [slist]);
            }).on('error', function () {
                $.msg('图片地址加载失败，请检查！');
            });

            $('.type-network .js-btn-ylimg', $view).on('click', function () {
                $('.type-network .js-webpath', $view).trigger('change');
            });
            //==网络图片事件处理--结束

            //图片选择事件
            $view.on('click', '.img-list>.item', function () {
                var $p = $(this).closest('.layui-tab-item'),
                    slist = $p.data('slist') || [], url = $(this).data('url');
                if ($(this).is('.selected')) {
                    var idx = $.inArray(url, slist);
                    idx > -1 && slist.splice(idx, 1);
                    $(this).removeClass('selected');
                } else {
                    $(this).addClass('selected');
                    if (multiple <= 0) {
                        slist = [url];
                        $(this).siblings().removeClass('selected');
                    } else {
                        slist.push(url);
                    }
                }
                $p.trigger('change', [slist]);
                return false;
            });
        }
    };

    window.ImgSpace = imgSpace;

    $('body').on('click', '.imgspace [lay-up]', function () {
        var $p = $(this).closest('.imgspace'), multiple = $p.attr('multiple'),
            watermark = $p.attr('watermark');
        ImgSpace({
            elem: $p,
            multiple: multiple,
            watermark: watermark,
        });
        return false;
    }).on('click', '.imgspace[lay-up]', function () {
        var multiple = $(this).attr('multiple'),
            watermark = $(this).attr('watermark');
        ImgSpace({
            elem: this,
            multiple: multiple,
            watermark: watermark,
        });
        return false;
    }).on('change', '.imgspace input[type="text"]', function () {
        var $p = $(this).closest('.imgspace'), url = $(this).val();
        $('[lay-uphref]', $p).attr('href', url);
        $('[lay-upsrc]', $p).attr('src', url);
    });


})(window.jQuery);