/**
 * 通用公共function 方法
 */
$(document).ready(function () {
    //初始化字典缓存
    if(window.sessionStorage.getItem("dict")==null){
        g_ajax("/weixin/primaryPage/dict",{},function(json){
            window.sessionStorage.setItem("dict",JSON.stringify(json));
        });
    }
    //初始化地区缓存
    if(window.sessionStorage.getItem("region")==null){
        // g_ajax("/weixin/primaryPage/region",{},function(json){
        //     var data  = {};
        //     for(var i in json){ //转换为key value的模式，就是map，key是省市区的id
        //         data[json[i].id] = json[i];
        //     }
        //     data[0] = '不限';
        //     window.sessionStorage.setItem("region",JSON.stringify(data));
        // });
    }


});

/*
* 参数说明：
* number：要格式化的数字
* decimals：保留几位小数
* dec_point：小数点符号
* thousands_sep：千分位符号
* */
function number_format(number, decimals, dec_point, thousands_sep) {
    number = (number + '').replace(/[^0-9+-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + (n * k) / k;
            // return '' + Math.ceil(n * k) / k;
        };

    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    var re = /(-?\d+)(\d{3})/;
    while (re.test(s[0])) {
        s[0] = s[0].replace(re, "$1" + sep + "$2");
    }

    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}


function g_getObjLength(obj){

    var count = 0;
    for(var i in obj){
        count++;
    }

    return count;
}

/**
 * 是否微信浏览器
 * @returns {boolean}
 */
function is_weixin(){
    var ua = navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i)=="micromessenger") {
        return true;
    } else {
        return false;
    }
}



var Gdate={
    curtime: function(){
        // return Gdate.format(new Date(), 'yyyy-MM-dd h:m:s');
        return Gdate.format(new Date(), 'yyyy-MM-dd');
    },
    getDaysDiff:
        function getTime2Time($time1, $time2) {
            var time1 = arguments[0], time2 = arguments[1];
            time1 = Date.parse(time1)/1000;
            time2 = Date.parse(time2)/1000;
            var time_ = time1 - time2;
            return (time_/(3600*24));
        },
    getDateDiff :
    /*
     * 获得时间差,时间格式为 年-月-日 小时:分钟:秒 或者 年/月/日 小时：分钟：秒
     * 其中，年月日为全格式，例如 ： 2010-10-12 01:00:00
     * 返回精度为：秒，分，小时，天
     */
        function (startTime, endTime, diffType) {
            //将xxxx-xx-xx的时间格式，转换为 xxxx/xx/xx的格式
            startTime = startTime.replace(/\-/g, "/");
            endTime = endTime.replace(/\-/g, "/");

            //将计算间隔类性字符转换为小写
            diffType = diffType.toLowerCase();
            var sTime =new Date(startTime); //开始时间
            var eTime =new Date(endTime); //结束时间
            //作为除数的数字
            var divNum =1;
            switch (diffType) {
                case"second":
                    divNum =1000;
                    break;
                case"minute":
                    divNum =1000*60;
                    break;
                case"hour":
                    divNum =1000*3600;
                    break;
                case"day":
                    divNum =1000*3600*24;
                    break;
                default:
                    break;
            }
            return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(divNum));
        },
    format:
        function(pdate,f) {

            // 获取当前时间戳(以s为单位)
//			var timestamp = Date.parse(new Date());
//			timestamp = timestamp / 1000;
            //当前时间戳为：1403149534
//			console.log("当前时间戳为：" + timestamp);

            // 获取某个时间格式的时间戳
            /*var stringTime = "2014-07-10 10:21:12";
             var timestamp2 = new Date(stringTime).getTime();
             timestamp2 = timestamp2 / 1000;
             //2014-07-10 10:21:12的时间戳为：1404958872
             console.log(stringTime + "的时间戳为：" + timestamp2);*/

            // 将当前时间换成时间格式字符串
//			var timestamp3 = 1403058804;
//			var newDate = new Date();
//			newDate.setTime(timestamp3 * 1000);
            // Wed Jun 18 2014
//			console.log(newDate.toDateString());
            // Wed, 18 Jun 2014 02:33:24 GMT
//			console.log(newDate.toGMTString());
            // 2014-06-18T02:33:24.000Z
//			console.log(newDate.toISOString());
            // 2014-06-18T02:33:24.000Z
//			console.log(newDate.toJSON());
            // 2014年6月18日
//			console.log(newDate.toLocaleDateString());
            // 2014年6月18日 上午10:33:24
//			console.log(newDate.toLocaleString());
            // 上午10:33:24
//			console.log(newDate.toLocaleTimeString());
            // Wed Jun 18 2014 10:33:24 GMT+0800 (中国标准时间)
//			console.log(newDate.toString());
            // 10:33:24 GMT+0800 (中国标准时间)
//			console.log(newDate.toTimeString());
            // Wed, 18 Jun 2014 02:33:24 GMT
//			console.log(newDate.toUTCString());

            Date.prototype.format = function(format) {
                var date = {
                    "M+": Gdate.helpZero(this.getMonth() + 1),
                    "d+": Gdate.helpZero(this.getDate()),
                    "h+": Gdate.helpZero(this.getHours()),
                    "m+": Gdate.helpZero(this.getMinutes()),
                    "s+": Gdate.helpZero(this.getSeconds()),
                    "q+": Math.floor((this.getMonth() + 3) / 3),
                    "S+": this.getMilliseconds()
                };
                if (/(y+)/i.test(format)) {
                    format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                for (var k in date) {
                    if (new RegExp("(" + k + ")").test(format)) {
                        format = format.replace(RegExp.$1, RegExp.$1.length == 1
                            ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
                    }
//		       console.log(format);
                }
                return format;
            }
//			console.log("fuck..."+pdate.format('yyyy-MM-dd h:m:s'));
            return pdate.format(f);
        },
    helpZero:function(n){
        var str =""+n;
        switch (n){
            case 0: str="00"; break;
            case 1: str="01"; break;
            case 2: str="02"; break;
            case 3: str="03"; break;
            case 4: str="04"; break;
            case 5: str="05"; break;
            case 6: str="06"; break;
            case 7: str="07"; break;
            case 8: str="08"; break;
            case 9: str="09"; break;
            default: break;
        }
        return str;
    },
    stringToDate : function(fDate){
        var d = fDate.split(" ");
        var nyr = d[0].split("-");
        var sfm = d[1].split(":");
        //gprint(d);
        return new Date(nyr[0], nyr[1]-1, nyr[2], sfm[0], sfm[1], 0);
    },
    stringToDate2 : function(fDate){ //输入yyyy-mm-dd
        var nyr = fDate.split("-");
        //gprint(d);
        return new Date(nyr[0], nyr[1]-1, nyr[2]);
    },
    calcDiff:function(ctime, etime){ // t为秒
        console.log(ctime.innerText+"  "+etime.innerText);
        var ctimes = Gdate.stringToDate(ctime.innerText).getTime()/1000;
        var etimes = Gdate.stringToDate(etime.innerText).getTime()/1000;
        var curDate = new Date().getTime()/1000;
        t = etimes - ctimes;
        var day  = parseInt( t / (24*60*60) );
        var hour = parseInt( (t - day*(24*60*60)) / (60*60) );
        var min  = parseInt( (t - day*(24*60*60) - hour*(60*60)) / 60 );
        //console.log(day+"天 "+hour+"小时"+min+"分钟")


        f = ctimes- curDate ;
        var day2  = parseInt( f / (24*60*60) );
        var hour2 = parseInt( (f - day2*(24*60*60)) / (60*60) );

        var str1 = (day2<=0?"":day2+"天")+(hour2<=0?"":hour2+"时");
        str1 = f==0?"从现在开始 ":str1+"后 ";

        var str2= (day<=0?"":day+"天")+(hour<=0?"":hour+"时")+(min<=0?"":min+"分");
        str2 = str2==""?"":"持续"+str2;

        //console.log(f+" "+t)
        console.log("开始差"+f+"  持续差"+t);
        if(f<0 || t<=0) return "";

        return str1+str2;
    },
    addDateBySeconds:function(dateString, seconds){
        var ori = Gdate.stringToDate(dateString+" 00:00:00").getTime()/1000;
        var target = new Date();
        target.setTime((ori+seconds) * 1000);
        // var str = Gdate.format(target,'yyyy-MM-dd h:m');
        return target;
    },
    addDateTypeBySeconds:function(ori,seconds){
        var ori = ori.getTime()/1000;
        var target = new Date();
        target.setTime((ori+seconds) * 1000);
        // var str = Gdate.format(target,'yyyy-MM-dd h:m');
        return target;
    }
}

/**
 * 全局正则表达式
 * @type {{ckPhone: g_reg.ckPhone, ckEmail: g_reg.ckEmail}}
 */
var g_reg = {
    ckNull:function(val){
      if(val==undefined || $.trim(val)=="")  return false;
      return true;
    },
    ckPhone: function(val){
        var reg=/^(\d{11})$/;
        return reg.test(val);
    },
    ckEmail: function(val){
        var reg = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/;
        return reg.test(val);
    },
    ckNum:function(val,len){
        var reg=/^[0-9]*$/;
        if(!reg.test(val)) return false;
        if(val.toString().length > len) return false;
        return true;
    }
}

/**
 * 根据 type 和value 获得label值
 * @param type
 * @param value
 */
function g_getDict(type, value){
    if(window.sessionStorage.getItem("dict")==null) return "";
    var dict = JSON.parse(window.sessionStorage.getItem("dict"));
    for(var i in dict){
        if(dict[i].type==type && dict[i].value==value){
            return dict[i].label;
        }
    }
}

function clone(obj){
    var o;
    switch(typeof obj){
        case 'undefined': break;
        case 'string'   : o = obj + '';break;
        case 'number'   : o = obj - 0;break;
        case 'boolean'  : o = obj;break;
        case 'object'   :
            if(obj === null){
                o = null;
            }else{
                if(obj instanceof Array){
                    o = [];
                    for(var i = 0, len = obj.length; i < len; i++){
                        o.push(clone(obj[i]));
                    }
                }else{
                    o = {};
                    for(var k in obj){
                        o[k] = clone(obj[k]);
                    }
                }
            }
            break;
        default:
            o = obj;break;
    }
    return o;
}
/**
 * 翻译code为地区的名字
 * @param id
 */
function g_getRegion(id){
    var rev=  "";
    g_ajax("/weixin/primaryPage/region",{id:id},function(json){
        rev = json;
    },false);
   //  if(window.sessionStorage.getItem("region")==null) return "";
   // var region =  JSON.parse(window.sessionStorage.getItem("region"));
   // return region[id];
    return rev;
}

$.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 g_getTabTitle(t){
    if(t.length>18){
        return "<span title='"+t+"'>"+t.substr(0,18) +"...</span>"
    }else{
        return t;
    }
}

//得到当前日期
g_formatterDate = function(date) {
    var day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
    var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0"
        + (date.getMonth() + 1);
    return date.getFullYear() + '-' + month + '-' + day;
};

function g_comm_back(json,refresh,close){//回调函数
    if (json.success == true) {
        if(refresh) parent.refresh();
        layer.msg(json.msg, {icon: 1, time: 2000});
        if(close) layer_close();
    } else {
        layer.alert(json.msg, {icon: 2});
    }
}
function g_comm_back2(json,refresh){//回调函数
    if (json.success == true) {
        if(refresh) refresh();
        layer.msg(json.msg, {icon: 1, time: 2000});
    } else {
        layer.alert(json.msg, {icon: 2});
    }
}


function g_ajax(url,p,callback,async){
    if(async) async=true;
    $.ajax({async:async, type: 'post', dataType: 'json', url:url, data:p,success: function (json) {callback(json) }});
}

function g_timer(time, btnId, btnTextId, display) {
    var btn = $("#"+btnId);
    var btnText = $("#"+btnTextId);
    btn.attr("disabled", true);  //按钮禁止点击
    btnText.html(time <= 0 ? display : (display + (time) + ""));
    var hander = setInterval(function() {
        if (time <= 0) {
            clearInterval(hander); //清除倒计时
            btnText.html(display);
            btn.attr("disabled", false);
            return false;
        }else {
            btnText.html(display + (time--) );
        }
    }, 1000);
}

/**
 * 加载div
 */
function g_fromDiv(id,obj){
    $("#"+id).find("div").each(function(){
        var key = $(this).attr("name");
        $(this).html(obj[key]);
    })
}
/**
 * 序列化表单 serializeObject
 * @param form
 * @returns {___anonymous78_79}
 */
function g_sobj(form) { /*将form 表单元素的值序列化*/
    var obj = {};
    $.each(form.serializeArray(), function (index) {
        if (obj[this['name']]) {
            obj[this['name']] = obj[this['name']] + "," + this['value'];
        } else {
            obj[this['name']] = this['value'];
        }
    });
    return obj;
}
/**
 * 本地递归算法
 * @param old_obj
 * @param new_obj
 * @returns {Boolean}
 */
function g_getRealTree(json){
    var result=[], temp = g_getTree(json,json[0].id);//获得根节点下的所有节点
    obj = g_getNode(json[0]); //构造根节点
    if (temp.length > 0)  obj.children = temp;
    result.push(obj);
    return result;
}
function g_getNode(data){
    return {
        id: data.id,
        text: data.text,
        //iconCls: data[i].iconCls,
        checked: (data.checked==="true"?true:false),   // true or false
        state: data.state, //The node state, 'open' or 'closed'.
        attributes: data
    };
}
/**
 * 得到树结构数据
 */
function g_getTree(data, pId) {
    var result = [], temp;
    for (var i = 0; i < data.length; i++) {
        if (data[i].pId == pId) { //找到所有子节点，并构造挂载
            var obj = g_getNode(data[i]); //构造节点
            temp = g_getTree(data, data[i].id); //递归获得子节点
            if (temp.length > 0)  obj.children = temp; //添加子节点
            result.push(obj);
        }
    }
    return result;
}
function arrToObj(data){
    //把数组变成对象
    var dobj = {};
    for(var i in data){
        dobj[data[i].codes] = data[i];
    }
    return dobj;
}
/**
 * 得到树结构数据
 * 传入对象
 */
function g_getTreeArea(data,pId) {
    var result = [], temp;
    for (var i = 0; i < data.length; i++) {
        if (data[i].parent_id == pId) { //找到所有子节点，并构造挂载
            var obj = g_getNode(data[i]); //构造节点
            temp = g_getTreeArea(data, data[i].id); //递归获得子节点
            if (temp.length > 0)  obj.children = temp; //添加子节点
            result.push(obj);
        }
    }
    return result;
}
function g_getRealTreeArea(data) {
    var result=[], temp = g_getTreeArea(data,"100000");//获得根节点下的所有节点
    obj = g_getNode(data[0]); //构造根节点
    if (temp.length > 0)  obj.children = temp;
    result.push(obj);
    return result;
}

/**
 * 查看
 *
 */
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;  jquery-3.1.1.min.js
     }  */
    var index0 = layer.load(0, {shade: false});
    console.log(obj);
    $(obj).parents('form').ajaxSubmit(function(result) {
        if (result.success == true) {
            layer.msg(result.msg, {
                shade : 0.3,
                time : 1000
            }, function() {
                window.parent.location.reload(); // 刷新父页面
            });
        } else {
            layer.msg(result.msg, {
                icon : 2,
                time : 1000
            });
        }
        layer.close(index0);
        return false;
    });
}


function toAjaxFaildSubmit(obj){
    var index0 = layer.load(0, {shade: false});
    $(obj).parents('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: false});
    $(obj).parents('form').ajaxSubmit(function(result) {
        if (result.success == true) {
            location.href=address+result.data; // 刷新父页面
        } else {
        }
        layer.close(index0);
        return false;
    });
}

/*通用查询参数*/
function queryParams(params) {
    return {
        size: params.limit,  //页面大小
        index: params.offset, //页码
        sortName:this.sortName,
        sortOrder:this.sortOrder
    };
}

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: false});
            $(form).ajaxSubmit(function(result) {
                if (result.success == true) {
                    layer.msg(result.message, {
                        shade : 0.3,
                        time : 1000
                    }, function() {
                        window.parent.location.reload(); // 刷新父页面
                    });
                } else {
                    layer.msg(result.message, {
                        icon : 2,
                        time : 1000
                    });
                }
                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;
}

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

/**
 * 强制选中
 * @param formid，表单ID
 */

function g_forceSelect(formid){
    var globe_old_value;
    var globe_old_id;
    $("#"+formid+" .textbox-text.validatebox-text").focusin(function(){
        globe_old_value =  $(this).val();
        globe_old_id = $(this).nextAll("input").eq(0).val();
        // console.log("in:"+globe_old_value+"  "+globe_old_id)
    }).focusout(function(){
        $(this).val(globe_old_value);
        $(this).nextAll("input").eq(0).val(globe_old_id);
        // console.log("out:"+globe_old_value+"  "+globe_old_id)
    });
}
//jquery全局事件
var g_layer;
$(document).ajaxStart(g_onStart)
    .ajaxComplete(g_onComplete)
    .ajaxSuccess(g_onSuccess)
    .ajaxError(g_onError);

function g_onStart(event) {
    //加载层-默认风格
    //g_layer = layer.load(1); //layer.load();
    //判断服务器session是否存在
    // layer.open({type:2,shadeClose:false});
    // var h = document.body.clientHeight;
    // $("<div class=\"datagrid-mask\"></div>").css({display:"block",width:"100%",height:h}).appendTo("body");
    // layer.load();//1 2
//	layer.msg('加载中...', {icon: 16});
//     $("<div class=\"datagrid-mask-msg\"></div>").html("<font style='font-size: 13px;'>服务器正在努力的处理，请稍候...</font>").appendTo("body").css({display:"block",
//         left:($(document.body).outerWidth(true) - 190) / 2, top:(h - 45) / 2,"background-color":"#fff","color":"#000","border":"0px","border-radius":"8px"});
}
function g_onComplete(event, xhr, settings) {
    // layer.closeAll();
    // $('.datagrid-mask-msg').remove();
//     $('.datagrid-mask').remove();
    //此处演示关闭
//	layer.close(g_layer);
    /*setTimeout(function(){

     }, 88);*/
}
function g_onSuccess(event, xhr, settings) {
    /*try {
     var json = $.parseJSON(xhr.responseText);
     if(true==json.isSessionTimeOut){
     window.location.href="login.do";
     $.messager.alert("提示", "登录超时，请重新登录", "info", function () {});
     }
     } catch (e) {
     }*/
}
function g_onError(event, jqXHR, options, errorMsg){
    if(jqXHR.status=="200") return;

    console.log(errorMsg);
    console.log(event);
    console.log(jqXHR.status);
    console.log(options);
}
$.ajaxSetup({
    contentType : "application/x-www-form-urlencoded;charset=utf-8",
    complete : function(xhr, textStatus) {
        // $.ts.hideLoading();
        //session timeout
        // if (xhr.status == 404) {
        //     top.location.href="login.do";
        //     return;
        // }
    }/*,
     error: function(jqXHR, textStatus, errorThrown){
     if(jqXHR.status==404){
     $.messager.alert("提示", "连接服务器错误，错误代码："+jqXHR.status, "info", function () {});
     }
     } */
});

