var AESPWD = "La20p20tw08x18c@";
//计算天数差的函数，通用
function DateDiff(sDate1, sDate2){
   var aDate, oDate1, oDate2, iDays;
   aDate = sDate1.split("-");
   oDate1 = new Date(aDate[0], aDate[1] - 1, aDate[2]);//转换为12-18-2006格式  
   aDate = sDate2.split("-");
   oDate2 = new Date(aDate[0], aDate[1] - 1, aDate[2]);
   iDays = parseInt(Math.abs(oDate1 - oDate2)/1000/60/60/24) + 1;//把相差的毫秒数转换为天数  
   return iDays;
}

//计算天数差的函数，通用
function dateDiffVal(sDate1, sDate2){
   var aDate, oDate1, oDate2, iDays;
   aDate = sDate1.split("-");
   oDate1 = new Date(aDate[0], aDate[1] - 1, aDate[2]);//转换为12-18-2006格式  
   aDate = sDate2.split("-");
   oDate2 = new Date(aDate[0], aDate[1] - 1, aDate[2]);
   iDays = parseInt((oDate1 - oDate2)/1000/60/60/24);//把相差的毫秒数转换为天数  
   return iDays;
}

//重写获取UUID方法
function UUID(){
	var s = [], itoh = '0123456789ABCDEF'.split('');
    for (var i = 0; i < 32; i++) s[i] = Math.floor(Math.random() * 0x10);
//    s[14] = 4;
//    s[19] = (s[19] & 0x3) | 0x8;
    for (var i = 0; i < 32; i++) s[i] = itoh[s[i]];
    return s.join('');
}

//判断是PC还是移动端
function IsPC(){
    var userAgentInfo = navigator.userAgent;
    var Agents = ["Android", "iPhone",
	    "SymbianOS", "Windows Phone",
	    "iPad", "iPod"];
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    return flag;
}
//判断是PC还是移动端
function IsIphone(){
	 var browser = { 
        versions : function() { 
            var u = navigator.userAgent, app = navigator.appVersion; 
            return {//移动终端浏览器版本信息                                  
            trident : u.indexOf('Trident') > -1, //IE内核                                  
            presto : u.indexOf('Presto') > -1, //opera内核                                  
            webKit : u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核                                  
            gecko : u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核                                 
            mobile : !!u.match(/AppleWebKit.*Mobile.*/) 
                    || !!u.match(/AppleWebKit/), //是否为移动终端                                  
            ios : !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端                  
            android : u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器                                  
            iPhone : u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器                     
            iPad: u.indexOf('iPad') > -1, //是否iPad        
            webApp : u.indexOf('Safari') == -1,//是否web应该程序，没有头部与底部 
            google:u.indexOf('Chrome')>-1 
        }; 
    }(), 
    language : (navigator.browserLanguage || navigator.language).toLowerCase() 
    } 
	return browser.versions.iPhone;
}

//获取当前时间，格式YYYY-MM-DD
function getNowYYYYMMDD() {
	var date = new Date();
	var seperator1 = "-";
	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	if (month >= 1 && month <= 9) {
	    month = "0" + month;
	}
	if (strDate >= 0 && strDate <= 9) {
	    strDate = "0" + strDate;
	}
	var currentdate = year + seperator1 + month + seperator1 + strDate;
	return currentdate;
}

//获取当前时间，格式DD-MM-YYYY
function getNowDDMMYYYY() {
	var date = new Date();
	var seperator1 = "-";
	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	if (month >= 1 && month <= 9) {
	    month = "0" + month;
	}
	if (strDate >= 0 && strDate <= 9) {
	    strDate = "0" + strDate;
	}
	var currentdate = strDate + seperator1 + month + seperator1 + year ;
	return currentdate;
}

//日期，在原有日期基础上，增加days天数，默认增加1天
function addDatePlus(date, days) {
	if ((days == undefined || days == '') && days != 0) {
		days = 1;
	}
	var date = new Date(date);
	date.setDate(date.getDate() + days);
	var month = date.getMonth() + 1;
	var day = date.getDate();
	return date.getFullYear() + '-' + getFormatDate(month) + '-' + getFormatDate(day);
}

//日期月份/天的显示，如果是1位数，则在前面加上'0'
function getFormatDate(arg) {
	if (arg == undefined || arg == '') {
		return '';
	}
	var re = arg + '';
	if (re.length < 2) {
		re = '0' + re;
	}
	return re;
}

/**
 * 加法
 * @param arg1
 * @param arg2
 * @returns {Number}
 */
function accAdd(arg1, arg2) {
    var r1, r2, m, c;
    try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
    try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
    c = Math.abs(r1 - r2);
    m = Math.pow(10, Math.max(r1, r2))
    if (c > 0) {
        var cm = Math.pow(10, c);
        if (r1 > r2) {
            arg1 = Number(arg1.toString().replace(".", ""));
            arg2 = Number(arg2.toString().replace(".", "")) * cm;
        }
        else {
            arg1 = Number(arg1.toString().replace(".", "")) * cm;
            arg2 = Number(arg2.toString().replace(".", ""));
        }
    }
    else {
        arg1 = Number(arg1.toString().replace(".", ""));
        arg2 = Number(arg2.toString().replace(".", ""));
    }
    return (arg1 + arg2) / m
}
/**
 * 减法
 * @param arg1
 * @param arg2
 * @returns
 */
function accSub(arg1,arg2){
	var r1,r2,m,n;
	try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
	try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
	m=Math.pow(10,Math.max(r1,r2));
	//last modify by deeka
	//动态控制精度长度
	n=(r1>=r2)?r1:r2;
	return ((arg1*m-arg2*m)/m).toFixed(n);
	}
/**
 * 乘法
 * @param arg1
 * @param arg2
 * @returns {Number}
 */
function accMul(arg1, arg2) {
    var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
    try { m += s1.split(".")[1].length } catch (e) { }
    try { m += s2.split(".")[1].length } catch (e) { }
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
}
/**
 * 除法
 * @param arg1
 * @param arg2
 * @returns {Number}
 */
function accDiv(arg1, arg2) {
    var t1 = 0, t2 = 0, r1, r2;
    try { t1 = arg1.toString().split(".")[1].length } catch (e) { }
    try { t2 = arg2.toString().split(".")[1].length } catch (e) { }
    with (Math) {
        r1 = Number(arg1.toString().replace(".", ""))
        r2 = Number(arg2.toString().replace(".", ""))
        return (r1 / r2) * pow(10, t2 - t1);
    }
}
/**
 * 将时间毫秒数显示为年月日的格式
 */
Date.prototype.Format = function (fmt) {
	var o = {
		"M+": this.getMonth() + 1, //月份
		"d+": this.getDate(), //日
		"h+": this.getHours(), //小时
		"m+": this.getMinutes(), //分
		"s+": this.getSeconds(), //秒
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度
		"S": this.getMilliseconds() //毫秒
	};
	if(/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if(new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
};
//NaN返回空字符串
function ifNaN(obj){
	if(isNaN(parseInt(obj))){//是NaN
		return "";
	}else{
		return obj;
	}
}
//把属性具有父子关系的json文件转变成json树
function toTree(data) { // 删除所有 children,以防止多次调用 
	data.forEach(function(item) {
		delete item.children;
	}); // 将数据存储为 以 id 为 KEY 的 map 索引数据列
	var map = {};
	data.forEach(function(item) {
		map[item.id] = item;
	}); //        console.log(map); 
	var val = [];
	data.forEach(function(item) { // 以当前遍历项，的pid,去map对象中找到索引的id 
		var parent = map[item.parentId]; // 好绕啊，如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
		if(parent) {
			(parent.children || (parent.children = [])).push(item);
		} else { //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级 
			val.push(item);
		}
	});
	return val;
}
//AES加密
function AES_ECB_encrypt(message, key) {
	// 如果加密后没有转成base64,那么先要转成base64再传入
	//let encryptedHexStr = CryptoJS.enc.Hex.parse(word);   // 从二进制文本转成二进制
	//messageBase64 = CryptoJS.enc.Base64.stringify(encryptedHexStr);    // 转成base64
	var messageHex = CryptoJS.enc.Utf8.parse(message);
	var keyHex = CryptoJS.enc.Utf8.parse(key);
	var decrypt = CryptoJS.AES.encrypt(messageHex, keyHex, {
		mode: CryptoJS.mode.ECB,
		padding: CryptoJS.pad.Pkcs7
	});
	return decrypt.toString();
}
//AES解密
function AES_ECB_decrypt(messageBase64, key) {
	// 如果加密后没有转成base64,那么先要转成base64再传入
	//let encryptedHexStr = CryptoJS.enc.Hex.parse(word);   // 从二进制文本转成二进制
	//messageBase64 = CryptoJS.enc.Base64.stringify(encryptedHexStr);    // 转成base64
	var keyHex = CryptoJS.enc.Utf8.parse(key);
	var decrypt = CryptoJS.AES.decrypt(messageBase64, keyHex, {
		mode: CryptoJS.mode.ECB,
		padding: CryptoJS.pad.Pkcs7
	});
	var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
	return decryptedStr.toString();
}

//GeoJson和Leaflet坐标互转
function XY2YX(coordinates) {
	var yx = [];
	yx.push(coordinates[1], coordinates[0]);
	return yx;
}

//读取cookies
function getCookie(name){
	var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
	if(arr=document.cookie.match(reg))
	return unescape(arr[2]);
	else
	return null;
}

//ajax封装token
function ajaxToken(async, url, dataParam, callback){
	$.ajax({
		async: async,
		url: url,
		type: "post",
		data: dataParam,
		traditional: true,//这里设置为true
		headers: {
			"Authorization": getCookie("token")
		},
		dataType: "json",
		success: function(data){
			if(data.code == 200){
				return callback(data);
			}else if(data.code == 500){
				layer.alert(data.msg, {icon: 2, closeBtn: 0}, function(index){
					layer.close(index);
					layer.closeAll("loading");
				});
			}else if(data.code == 401 || data.code == 403 || data.code == 505){
				layer.closeAll('loading');
				location.href = "/";
			}
		},
		error: function(){
			layer.alert("网络连接失败，请检查网络或联系管理员！", {icon: 2, closeBtn: 0}, function(index){
				layer.close(index);
				layer.closeAll("loading");
			});
		}
	});
}
//合并单元格
function tablespan(tb1, find) {
	//合并行
	//列
	for (var i = tb1.rows[0].childNodes.length - 1; i >= 0; i--) {
		//行
		for (var j = tb1.rows.length - 1; j > 0; j--) {
			//当前单元格与上一单元格比较
			if (tb1.rows[j].childNodes[i].innerHTML == tb1.rows[j - 1].childNodes[i].innerHTML) {
				tb1.rows[j - 1].childNodes[i].rowSpan += tb1.rows[j].childNodes[i].rowSpan;
				tb1.rows[j].removeChild(tb1.rows[j].childNodes[i]);
			}
		}
	}
	//是否合并列
	if(!find){
		return;
	}
	//行
	for (var i = tb1.rows.length - 1; i >= 0; i--) {
		//列
		for (var j = tb1.rows[i].childNodes.length - 1; j > 0; j--) {
			//当前单元格与左一单元格比较
			if (tb1.rows[i].childNodes[j].innerHTML == tb1.rows[i].childNodes[j - 1].innerHTML) {
				tb1.rows[i].childNodes[j - 1].colSpan += tb1.rows[i].childNodes[j].colSpan;
				tb1.rows[i].removeChild(tb1.rows[i].childNodes[j]);
			}
		}
	}
}