/**
 * 使用百度图片选择上传器
 * 注意：
 *    需要页面中引用
 *    <script type="text/javascript" charset="utf-8" src="plugins/ueditor-min-1.4.3/ueditor.config.js"></script>
 *    <script type="text/javascript" charset="utf-8" src="plugins/ueditor-min-1.4.3/ueditor.all.js"></script>
 *    这2个js
 */
var uePicPicker = (function () {
    'use strict';
    var UEPicPicker = function (params) {
        var p = this;

        p.protocol = window.location.protocol;
        p.host = window.location.host;

        //参数定义
        /**
         * tarId: 需要创建一个类似 <script id="upload_ue" type="text/plain"></script>，放在form中
         *        tarId = upload_ue
         * selector: 调用的选择Id或者class，用$()已经封装过
         * max: 最多可选择几个
         * datas: 原始数据（如果已有数据，则需要传递）
         * success: 回调方法
         * @type {{tarId: string, selector: string, success: function() {} }}
         */
        p.params = {
            tarId: '',
            title: '图片',
            sizeDes: '',
            max: 1,
            datas: null,
            success: null
        };

        for (var param in params) {
            p.params[param] = params[param];

        }

        p.selectedLength = 0;

        //编辑器
        p.editor = null;

        p.init = function () {
            p.uploadId = getUniqueID('ue');
            //根据tarId，建立script
            initScript();
            initContainer();


            //初始化，如果有数据，则可选数量改动
            if (p.params.datas && p.params.datas.length > 0) {
                loadInitDatas();

            }

            p.editor  = UE.getEditor(p.uploadId, {
                toolbars: [[
                    'insertimage']]});
            p.editor.addListener("ready", function () {
                //隐藏编辑器，因为不会用到这个编辑器实例，所以要隐藏
                p.editor.hide();
            });
            initEvents();

        };

        var loadInitDatas = function () {
            for (var i = 0, j = p.params.datas.length; i < j; i++) {
                var obj = {
                    src: p.params.datas[i]
                }
                if (p.selectedLength == p.params.max) {
                    hideImgSelector();
                } else {
                    buildImg(obj);
                    if (p.selectedLength == p.params.max) {
                        hideImgSelector();
                    }
                }
            }
        };

        p.getValues = function () {
            var selectedImgs = [];
            $('#img-'+p.uploadId + ' .sortableThumbnail').each(function () {
                var obj = $(this);
                var imgSrc = obj.attr('data-v');
                selectedImgs.push(imgSrc);
            });
            return selectedImgs;
        };

        p.getStringValues = function () {
            var selectedImgs = '';
            $('#img-'+p.uploadId + ' .sortableThumbnail').each(function () {
                var obj = $(this);
                var imgSrc = obj.attr('data-v');
                selectedImgs += imgSrc+ ',';
            });
            return selectedImgs;
        };

        var initContainer = function () {
            var htmlStr = '<label style="width: 100%">'+p.params.title;
            if (p.params.sizeDes !== '') {
                htmlStr += '<font style="font-size: 12px;" color="red">（尺寸：'+p.params.sizeDes+'）</font></label>';
            }

            $('#'+p.params.tarId).append(htmlStr);

            initImgsContainer();
            initImgSelector();

        };

        var initImgsContainer = function () {
            var htmlStr = '<div class="form-group form-md-line-input" id="img-'+p.uploadId+'" style="margin-bottom: 0px"></div>';
            $('#'+p.params.tarId).append(htmlStr);
        };

        var initImgSelector = function () {
            var htmlStr =
                '<div class="parentThumbnail addParentThumbnail" id="upImg-'+p.uploadId+'">\n' +
                '<div class="fileupload-preview thumbnail" style="color: #ccc;text-align: center;">\n' +
                '  <i class="fa fa-picture-o" style="font-size: 50px;margin: 41px auto 0 auto;width: 100%;float:left;"></i>\n' +
                '  <span>最多可选择'+p.params.max+'张</span>\n' +
                '  </div>\n' +
                '</div>';
            $('#'+p.params.tarId).append(htmlStr);
        };

        //创建script标签
        var initScript = function () {

            var htmlStr = '<script id="'+p.uploadId+'" type="text/plain"></script>';
            $('#'+p.params.tarId).append(htmlStr);
        };


        var initEvents = function () {
            //侦听图片上传
            p.editor.addListener('beforeInsertImage', function (t, arg) {
               if (arg && arg.length > 0) {

                   for (var i = 0, j = arg.length; i <j ; i++) {
                       if (p.selectedLength == p.params.max) {
                           hideImgSelector();
                       } else {
                           buildImg(arg[i]);
                           if (p.selectedLength == p.params.max) {
                               hideImgSelector();
                           }
                       }
                   }
               }
            });
            $('#upImg-'+p.uploadId).on('click', function () {
                var myImage = p.editor.getDialog("insertimage");
                myImage.render();
                myImage.open();
            });

            //悬停事件
            $('#img-'+p.uploadId).on('mouseenter mouseleave','.sortableThumbnail',function(event){
                if(event.type == "mouseenter"){
                    //鼠标悬浮
                    $(this).find(".delRemove").slideDown();
                }else if(event.type == "mouseleave"){
                    //鼠标离开
                    $(this).find(".delRemove").slideUp();
                }
            });

            $('#img-'+p.uploadId).on("click", ".delRemove", function () {
                var obj = $(this);
                //var img = obj.parent().find('img');
                p.selectedLength = p.selectedLength -1;
                obj.parent().parent().remove();
                showImgSelector();

            });
            var list = document.getElementById('img-'+p.uploadId);
            Sortable.create(list, {
                animation : 150,
                handle : ".sortableThumbnail"
            });

        };

        var hideImgSelector = function () {
            $('#upImg-'+p.uploadId).css('display','none');
        };

        var showImgSelector = function () {
            $('#upImg-'+p.uploadId).css('display','block');
        };

        var getUniqueID = function (prefix) {
            if (!prefix || prefix == '') prefix = 'pf';
            return prefix + '_' + Math.floor(Math.random() * (new Date()).getTime());
        };

        var buildImg = function (obj) {
            var htmlStr = "<div class='parentThumbnail sortableThumbnail' data-v='" + obj.src + "'>";
            htmlStr += "<div class='fileupload-preview thumbnail'>";
            htmlStr += "<p class='delRemove'>删除</p>";
            htmlStr += "<img src='" + obj.src + "'></div>";
            htmlStr += "</div>";
            p.selectedLength = p.selectedLength+1;
            $('#img-'+p.uploadId).append(htmlStr);
        };


    };

    return UEPicPicker;
})();