/**
 * 通用公共function 方法
 */
 $(document).ready(function () {
     init();
 });

 function  init() {
     //拖动
     $(".sortable-list").sortable({
         connectWith: ".connectList"
     }).disableSelection();

     //表达验证插件
     $("form.required-validate").each(function () {
         var $form = $(this);
         $form.bootstrapValidator();
         // 修复bootstrap validator重复向服务端提交bug
         $form.on('success.form.bv', function (e) {
             e.preventDefault();
         });
     });

     $('#data_5 .input-daterange').datepicker({
         keyboardNavigation: false,
         forceParse: false,
         autoclose: true,
         format: 'yyyy-MM-dd'
     });

     $('#date_month .input-daterange').datepicker({
         keyboardNavigation: false,
         forceParse: false,
         autoclose: true,
         format: 'yyyy-MM',
         startView: 2,
         maxViewMode: 2,
         minViewMode:1

     });
 }

$.fn.serializeObject = function() {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
}

/**
 * 查看

 *
 */
function member_show(title,url,id,ope,w,h){
	if(id == null|| id==''){
		layer_show(title,url,w,h);
	}else{
		layer_show(title,url+'/'+id+'/'+ope,w,h);
	}
}

/*弹出层*/
/*
	参数解释：
	title	标题
	url		请求的url
	id		需要操作的数据id
	w		弹出层宽度（缺省调默认值）
	h		弹出层高度（缺省调默认值）
*/
function layer_show(title,url,w,h){
	if (title == null || title == '') {
		title=false;
	};
	if (w == null || w == '') {
		w=800;
	};
	if (h == null || h == '') {
		h=($(window).height() - 50);
	};
    layer.open({
		type: 2,
		area: [w+'px', h +'px'],
		fix: false, //不固定
		maxmin: true,
		scrollbar: false,//屏蔽游览器滚动条
		shade:0.4,
		title: title,
		content: url
	});
}
/*关闭弹出框口*/
function layer_close(){
	var index = parent.layer.getFrameIndex(window.name);
	parent.layer.close(index);
}

/**
 * 提交数据
 * @returns
 */
function toAjaxSubmit(obj){
	/*$(obj).closest('form').data('bootstrapValidator').validate();
    if(!$(obj).closest('form').data('bootstrapValidator').isValid()){
        return false;  
    }  */
    $('.summernote').each(function() {
        $(this).text($(this).code());
    })
    var index0 = layer.load(0, {shade: 0.1});
    $(obj).closest('form').ajaxSubmit(function(result) {
        if (result.success == true) {
            layer.msg(result.message, {
                shade : 0.3,
                time : 1000
            }, function() {
                window.parent.location.reload(); // 刷新父页面
            });
        } else {
            layer.alert(result.message, {icon: 2});
        }
        layer.close(index0);
        return false;
    });
}


function toAjaxFaildSubmit(obj){
    var index0 = layer.load(0, {shade: 0.1});
	$(obj.find('form')).ajaxSubmit(function(result) {
		if (result.success == true) {
            location.reload(); // 父页面
        } else {
        }
        layer.close(index0);
        return false;
	});
}
function toAjaxTiaoZhuangSubmit(obj,address){
    var index0 = layer.load(0, {shade: 0.1});
	$(obj.find('form')).ajaxSubmit(function(result) {
		if (result.success == true) {
			location.href=address+result.data; // 刷新父页面
		} else {
		}
        layer.close(index0);
		return false; 
	});
}

/*通用查询参数*/
function queryParams(params) {
    var obj2 =  {
        size: params.limit,  //页面大小
        index: params.offset, //页码
        sortName:this.sortName,
        sortOrder:this.sortOrder
    };
    var obj1 =$("#searchForm").serializeObject();
    if(isNotNull(obj1)) {
        obj2 = $.extend(obj2, obj1);
    }
    return obj2;
}

function launchFullscreen(element) {
    if (!$("body").hasClass("full-screen")) {
        $("body").addClass("full-screen");
        if (element.requestFullscreen) {
            element.requestFullscreen();
        } else if (element.mozRequestFullScreen) {
            element.mozRequestFullScreen();
        } else if (element.webkitRequestFullscreen) {
            element.webkitRequestFullscreen();
        } else if (element.msRequestFullscreen) {
            element.msRequestFullscreen();
        }
    } else {
        $("body").removeClass("full-screen");
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        }
    }
}
/**
 * 验证提交回调参数
 * @param form
 * @param callback
 * @param confirmMsg
 * @returns {boolean}
 */
function validateCallback(form, callback, confirmMsg) {
    var $form = $(form);
    var data = $form.data('bootstrapValidator');
    if (data) {
        data.validate();
        if (data.isValid()) {
            var index0 = layer.load(0, {shade: 0.1});
            $(form).ajaxSubmit(function(result) {
                if (result.success == true) {
                    layer.msg(result.message, {
                        shade : 0.3,
                        time : 1000
                    }, function() {
                        window.parent.location.reload(); // 刷新父页面
                    });
                } else {
                    layer.alert(result.message, {icon: 2});
                }
                layer.close(index0);
                return false;
            });
        }
    }

}

/**
 * 四舍五入保留二位小数
 * @param x
 * @returns {Number}
 */
function toDecimal(x) {
    var f = parseFloat(x);
    if (isNaN(f)) {
        return;
    }
    f = Math.round(x*100)/100;
    return f;
}

function toDecimal2(x) {
    var f = parseFloat(x);
    if (isNaN(f)) {
        return "0.00";
    }
    var f = Math.round(x*100)/100;
    var s = f.toString();
    var rs = s.indexOf('.');
    if (rs < 0) {
        rs = s.length;
        s += '.';
    }
    while (s.length <= rs + 2) {
        s += '0';
    }
    return s;
}

/**
 * 获取选中行信息
 * @returns {*}
 */
function getContent(obj){
    var index = $("#"+obj).find("tr.danger").data("index");
    return $("#"+obj).bootstrapTable('getData')[index];
}

/**
 * 判断是否为空
 * @param v
 * @returns {boolean}
 */
function isNotNull(v) {
    if(v=='' || v == 'null' || v == undefined || v==null || v=='undefined'){
        return false;
    }else{
        return true;
    }
}
/**
 * 刷新页面
 */
function refreshdiv() {
    location.reload();
}
/**
 * 重置s
 * @param obj
 * @returns {boolean}
 */
function resetTable(){//重置，页码清零
    $("#searchForm input").val("");
    //$("#searchForm select").val("");
    doRefresh();
    return false;
}
/**
 * 通用刷新方法
 */
function doRefresh() {
    $("#table").bootstrapTable('refresh');
}

/**
 * 图片上传公共方法
 * fileId :文件上传控件ID
 * inputId:影藏inputID
 * value:初始值
 * demo
 *   <input id="file-picture" type="file" class="file-loading" >
     <input id="picture" type="text" name = "picture" class="hide" value="${productIns.picture}"/>

        initFileInput('file-picture','picture','${productIns.picture}')
 */
function initFileInput(fileId,inputId,value,url) {
    //初始化上传组件
    $("#"+fileId).fileinput({
        language:'zh',
        showPreview: true,
        showCaption: false,
        showRemove: false,
        showUpload: false,
        allowedFileExtensions : ['jpg', 'png','gif', 'jpeg'],
        maxFileSize:200,
        showCancel: false,
        uploadAsync:false,
        dropZoneEnabled:false,
        uploadUrl:url+"/upload",
        maxFileCount: 1,
        browseClass: "btn btn-default",
        resizeImage: true,
        allowedFileExtensions : ['jpg', 'png'],
        validateInitialCount:true,
        msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！"

    })



    if(isNotNull(value)){
        $("#"+fileId).fileinput('refresh', {
            initialPreview: [ //预览图片的设置
                "<img src="+value+" class='file-preview-image'>"
            ]
        });
    }
    //同步
    $("#"+fileId).on("filebatchuploadsuccess",function(event, data, previewId, index){
        $("#"+inputId).val(url+"/getImg?fileName="+data.response.data);
    })
    //異步
    $("#"+fileId).on("fileuploaded",function(event, data, previewId, index){
        $("#"+inputId).val(url+"/getImg?fileName="+data.response.data);
    })
    //選擇就上傳
    $("#"+fileId).on("filebatchselected", function(event, files) {
        $(this).fileinput("upload");
    });
}


function initFileInputAllFile(fileId,inputId,value,url) {
    //初始化上传组件
    $("#"+fileId).fileinput({
        language:'zh',
        showPreview: false,
        showCaption: true,//是否显示标题
        showRemove: false,//显示整体删除的按钮
        showUpload: false,//显示整体上传的按钮
        showBrowse: true,
        uploadLabel: "上传",//设置整体上传按钮的汉字
        removeLabel: "移除",//设置整体删除按钮的汉字
        uploadClass: "btn btn-primary",//设置上传按钮样式
        dropZoneEnabled: true,//是否显示拖拽区域
        maxFileSize : 9999,//文件大小限制
        maxFileCount: 1,//允许最大上传数，可以多个，
        enctype: 'multipart/form-data',
        allowedFileExtensions : ['jpg', 'png','gif', 'jpeg','zip','rar','doc','docx','pdf'],
        showCancel: true,//默认异步上传
        uploadAsync:true,
        uploadUrl:url+"/agreementForm/uploadAll",
        browseClass: "btn btn-default",
        resizeImage: false,
        validateInitialCount:true,
        msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
        browseOnZoneClick: true,
    })

    //同步
    // $("#"+fileId).on("filebatchuploadsuccess",function(event, data, previewId, index){
    //     $("#"+inputId).val(url+"/getFile?fileName="+data.response.data);
    // })
    // //将上传后的地址放到picture字段，存数据库
    $("#"+fileId).on("fileuploaded",function(event, data, previewId, index){
        // alert("ssssss");
        // $("#"+inputId).val(url+"/getFile?fileName="+data.response.data);
        // alert(data.response.data);
        alert(data.files[0].name+"上传成功");
        $("#"+inputId).val(data.response.data);
    })
    // //選擇就上傳
    $("#"+fileId).on("filebatchselected", function(event, files) {
        $(this).fileinput("upload");
    });

}



