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

    var H5Upload = function (el) {
        this.uploadStatus = 0; // 上传状态 0:等待上传  1:上传成功  2:上传中
        this.uploadLimitSize = 1024 * 1024 * 2; // 上传限制字节
        this.uploadList = []; // 上传列表
    };
    H5Upload.prototype = {
        uploadList: [],
        upload_file: function (fileStart, index) {
            // 开始上传
            if (fileStart == undefined && this.uploadList.length == 0) {
                fileStart = 0, index = 0;
            }
            // 结束上传
            if (this.fileList.length === index) {
                return false;
            }
        }
    };


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

        if (this === window) {
            return new FileStorage(options);
        }
        this.init(options);
        return this;
    };
    FileStorage.prototype = {
        $elem: $(window),
        isAll: false,
        multiple: false,
        type: 'other',
        watermark: true,
        url: window._global.root + '/Index/storage?type=other',
        uploadInst: null,
        platform: 'local',//存储类型
        uploadUrl: window._global.root + '/Upload/index?type=other',
        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;
            this.isAll = options.isAll || false;

            if (!options.type) {
                $.msg('参数错误！');
                return;
            }
            this.type = options.type;
            this.setUrl(this.type);

            if (options.elem) this.$elem = $(options.elem);
            var $elem = this.$elem;
            this.callback = options.callback || $elem.data('callback') || this.callback;
            this.openWindow();
        },
        setUrl: function (type) {
            type = type || this.type;
            this.uploadUrl = window._global.root + '/Upload/index?type=' + type;
            this.url = window._global.root + '/Index/storage?type=' + type;
        },
        openWindow: function () {
            var url = this.url + (this.multiple ? '&multiple=1' : '');
            if (this.watermark === false) {
                url += '&watermark=false';
            }
            if (this.isAll) {
                url += '&is_all=1';
            }

            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);
                    that.isAll && that.bindType(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)
            });
        },
        bindType: function ($view) {
            var that = this;
            $('.file-storage-type a', $view).on('click', function () {
                var url = $(this).attr('href'), type = $(this).data('type');
                $.openpage(url, {}, function (res) {
                    $('.file-storage', $view).hide().before(res).remove();
                    that.type = type;
                    that.multiple = type == 'images' ? true : false;
                    that.setUrl(that.type);
                    that.bindEvents($view);
                });
                $(this).addClass('hover').siblings().removeClass('hover');
                return false;
            });
        },
        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');

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

                //===网络图片事件处理--开始
                $('.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');
                });
                //==网络图片事件处理--结束
            } else {
                //===网络地址处理--开始
                $('.type-network .js-webpath', $view).on('change blur', function () {
                    var url = $.trim($(this).val()), $p = $(this).closest('.layui-tab-item');
                    if (/^(http|\/\/)/i.test(url)) {
                        var slist = [url];
                        $(this).closest('.layui-tab-item').trigger('change', [slist]);
                    } else {
                        url && $.msg('请填写正确的地址！');
                        $(this).val('');
                    }
                });

                $('.type-network .js-btn-ylimg', $view).on('click', function () {
                    var url = $('.type-network .js-webpath', $view).val();
                    window.open(url, '_blank');
                });
            }


            //页签切换事件
            $('.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']();
            });

            $('.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 || []);
            }).on('lazyload', function () {
                That.type == 'images' && $('.file-list .item img', this).lazyload({
                    data_attribute: 'src',
                    container: $('.file-list', this),
                });
            });

            //文件夹切换事件
            $view.off('click.dir-path').on('click.dir-path', '.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');
                    $('.file-list', $p).html(list);
                    $p.trigger('change').trigger('lazyload');
                    return false;
                }
                var _url = $p.data('url') || url;
                $.loading.show();
                $.post(_url, { name: name }, function (rs) {
                    $.loading.hide();
                    $this.data('list', rs);
                    $('.file-list', $p).html(rs);
                    $p.trigger('change').trigger('lazyload');
                    $this.addClass('dir-select').siblings().removeClass('dir-select');
                });
            });

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

            //选择事件
            $view.off('click.list-item').on('click.list-item', '.file-list>.item', function (e) {
                if ($(e.target).is('a')) return;
                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.FileStorage = FileStorage;
    window.ImgSpace = function (callback, multiple) {
        var options = $.isPlainObject(callback) ? callback : {};
        if ($.isFunction(callback)) {
            options.callback = callback;
            options.multiple = multiple || false;
        }
        options.type = 'images';
        return new FileStorage(options);
    };


    $('body').on('click', '.fileStorage [lay-up]', function () {
        var $p = $(this).closest('.fileStorage'), multiple = $p.attr('multiple'),
            type = $p.attr('data-type');
        FileStorage({
            elem: $p,
            multiple: multiple,
            type: type,
        });
        return false;
    }).on('click', '.fileStorage[lay-up]', function () {
        var multiple = $(this).attr('multiple'),
            type = $(this).attr('data-type');
        FileStorage({
            elem: this,
            multiple: multiple,
            type: type,
        });
        return false;
    });

    $('body').on('click', '.imgspace [lay-up]', function () {
        var $p = $(this).closest('.imgspace'), multiple = $p.attr('multiple'),
            watermark = $p.attr('watermark'), type = $p.attr('data-type');
        FileStorage({
            elem: $p,
            multiple: multiple,
            watermark: watermark,
            type: type || 'images',
        });
        return false;
    }).on('click', '.imgspace[lay-up]', function () {
        var multiple = $(this).attr('multiple'), watermark = $(this).attr('watermark'),
            type = $(this).attr('data-type');
        FileStorage({
            elem: this,
            multiple: multiple,
            watermark: watermark,
            type:  type || 'images',
        });
        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);