/*
*	Unknown
*	v1.0
*/
'use strict';
const XYBase={
	config:{
	  VueEl:'#app',
	  system_network_error:'服务器繁忙，请稍后再试',
	  weekText:['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
	  imageMime:['image/png','image/jpg','image/jpeg','image/gif'],
	  cacheUrl:[
	  	'/updateRouteFileAjax',
	  	'/updateRoleFileAjax',
	  	'/area/updateFileAjax',
	  	'/menu/updateFileAjax',
	  	'/client/updateApiCacheAjax',
	  	'/jobs/cate/setCacheJobsCate',
	  	'/links/cacheLink',
	  	'/setting/basic',
	  	'/wechat/pushTpl?action=cache',
	  	'/template/sms?action=cache',
	  	'/template/email?action=cache',
	  	'/template/website?action=cache'
	  ],
	},
	pattern:{
	  mobile : /^1[3456789]\d{9}$/,
	  email : /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
	},
	/*本地储存操作*/
	getStorage(name){
		if(!window.localStorage) return null;
		var value=window.localStorage.getItem(name);
		if(value){
		  return value;
		}else{
		  return null;
		}
	},
	setStorage(name,value){
		if(!window.localStorage) return false;
		window.localStorage.setItem(name,value);
	    return this.getStorage(name)!=null;
	},
	delStorage(name){
		if(!window.localStorage) return false;
		window.localStorage.removeItem(name);
		return this.getStorage(name)==null;
	},
	/*本地储存操作*/

	/*消息提示*/
	msg(msg) {
		vm.$message({type: 'info', duration:2000, message: msg });
	},
	success(msg) {
		vm.$message({type: 'success', duration:2000, message: msg });
	},
	warning(msg) {
		vm.$message({type: 'warning', duration:2000, message: msg });
	},
	error(msg) {
		vm.$message({type: 'error', duration:2000, message: msg });
	},
	openloading(str) {
		return vm.$loading({
	          lock: true,
	          text: str?str:'Loading...',
	          spinner: 'el-icon-loading',
	          customClass:'xy-el-loading',
	          background: 'rgba(255,255,255,0.8)'
	        });
	},
	/*消息提示*/

	/**
	 * [outLogin 注销登录]
	 * @return {[type]} [description]
	 */
	outLogin() {
		vm.$confirm('您确定要注销登录吗？', '提示', {
	          confirmButtonText: '注销',
	          cancelButtonText: '取消',
	          type: 'warning'
	        }).then(() => {
	        	const loading=this.openloading();
				$.get('/outLogin',function(ret){
					loading.close();
					if(ret.code == 0){
						window.location.reload();
					}else{
						XYBase.error(ret.msg);
					}
				});
	        }).catch(() => {
	        	this.msg('已取消');
	        });
	},
	updateAllCache(){
		const loading=XYBase.openloading();
		XYBase.updateAllCacheAjax(loading,0);
	},
	updateAllCacheAjax(loading,index){
		var url=XYBase.config.cacheUrl[index];
		if (url) {
			index++;
			loading.setText(index+'/'+XYBase.config.cacheUrl.length);
			$.getJSON(url,function(ret) {
				setTimeout(function(){
					XYBase.updateAllCacheAjax(loading,index);
				},300);
			});
		}else{
			loading.close();
		}
	},
	number_format(number, decimals, dec_point, thousands_sep) {
	    /*
	    * 参数说明：
	    * 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 '' + 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);
	},
	PrefixZero(num, n) {
	    return (Array(n).join(0) + num).slice(-n);
	},
	Date:{
		getMStoYear(time_stamp){
			if (time_stamp) {
			    var time=new Date().getTime();
			    //去掉 js 时间戳后三位，与php 时间戳保持一致
			    time=parseInt(time-time_stamp);
			    return parseInt(time/(3600*24*365*1000));
			}else return '';
		},
		date(format,time_stamp){
		    var time=new Date().getTime();
			if (time_stamp) time=time_stamp;
			var dateObj=new Date(time);
			format=format.replace(/Y/g, dateObj.getFullYear());
			format=format.replace(/m/g, XYBase.PrefixZero(dateObj.getMonth()+1,2));
			format=format.replace(/d/g, XYBase.PrefixZero(dateObj.getDate(),2));
			format=format.replace(/H/g, XYBase.PrefixZero(dateObj.getHours(),2));
			format=format.replace(/i/g, XYBase.PrefixZero(dateObj.getMinutes(),2));
			format=format.replace(/s/g, XYBase.PrefixZero(dateObj.getSeconds(),2));
			return format
		}
	},
	/*控制页面展示*/
	view:{
		auth_menu:typeof auth_menu != "undefined"?auth_menu:[],
		active_menu:typeof active_menu != "undefined"?active_menu:[],
		nav_bg:'#343a40',
		nav_text:'#fff',
		nav_active_text:'#ffd04b',
		isCollapse:false,
		mask:true,
		messageWin:false,
		messageWinContent:false,
	},
	openMessageWin(){
		vm.view.messageWin=true;
	},
	/*监听页面数据变化*/
	viewWatch:{
		handler(val,oldVal){
			if (val.nav_bg) {
				XYBase.setStorage('nav_bg',val.nav_bg);
			}else{
				val.nav_bg='#343a40';
			}
			if (val.nav_text) {
				XYBase.setStorage('nav_text',val.nav_text);
			}else{
				val.nav_text='#ffffff';
			}
			if (val.nav_active_text) {
				XYBase.setStorage('nav_active_text',val.nav_active_text);
			}else{
				val.nav_active_text='#ffd04b';
			}
			if (val.isCollapse) {
		  		XYBase.setStorage('isCollapse',val.isCollapse);
			}else{
		  		XYBase.delStorage('isCollapse');
			}
			setTimeout(function(){
				typeof bodyResizeChange==='function'&&bodyResizeChange();
			},300)
		},
		deep:true
	},
	/*初始化页面*/
	created(_this,callback){
		_this.view.mask=false;
		var isCollapse=XYBase.getStorage("isCollapse");
		if (isCollapse) {
			_this.view.isCollapse=true;
		}else{
			_this.view.isCollapse=false;
		}
		var nav_bg=XYBase.getStorage("nav_bg");
		if (nav_bg)
			_this.view.nav_bg=nav_bg;
		var nav_text=XYBase.getStorage("nav_text");
		if (nav_text)
			_this.view.nav_text=nav_text;
		var nav_active_text=XYBase.getStorage("nav_active_text");
		if (nav_active_text)
			_this.view.nav_active_text=nav_active_text;
		if (typeof callback=='function')
			callback();
	},
	hasUserMobile:(rule, value, callback)=>{
		if (!value) {
			callback(new Error('请输入用户手机号'));
		}else if(XYBase.pattern.mobile.test(value)){
			$.ajax({
					url:'/hasUser',
					data:{
						type:'mobile',
						value:value,
					},
					type:'post',
					dataType:'json',
					success:function(ret){
				        if (ret) {
							if(ret.code == 0){
								if (ret.data.has) {
									callback(new Error(ret.msg));
								}else{
									callback();
								}
							}else{
								callback(new Error(ret.msg));
							}
				        }else{
							callback(new Error(XYBase.config.system_network_error));
				        }
					},
					error:function(err){
						callback(new Error(XYBase.config.system_network_error));
					}
				});
		}else{
			callback(new Error('手机号码格式不正确'));
		}
	},
	hasUserEmail:(rule, value, callback)=>{
		if (value) {
			if(XYBase.pattern.email.test(value)){
				$.ajax({
					url:'/hasUser',
					data:{
						type:'email',
						value:value,
					},
					type:'post',
					dataType:'json',
					success:function(ret){
				        if (ret) {
							if(ret.code == 0){
								if (ret.data.has) {
									callback(new Error(ret.msg));
								}else{
									callback();
								}
							}else{
								callback(new Error(ret.msg));
							}
				        }else{
							callback(new Error(XYBase.config.system_network_error));
				        }
					},
					error:function(err){
						callback(new Error(XYBase.config.system_network_error));
					}
				});
			}else{
				callback(new Error('邮箱格式不正确'));
			}
		}else{
			callback();
		}
	},
	strntobr(str){
		if (str) {
	        return str.replace(/\n/g, '<br/>');
		}else{
			return str;
		}
	},
	inspectSystemVersion(_this,callback){
		var loading=XYBase.openloading('检查更新中...');
		$.getJSON('/system/version/inspect',function(ret) {
			loading.close();
			if(typeof callback==='function'){
				callback(ret);
			}else{
				if(ret){
					if(ret.code===0){
						XYBase.success(ret.msg);
					}else if(ret.code===600){
						_this.$confirm('此操作将永久删除该文件, 是否继续?', '更新提示', {
				          confirmButtonText: '立即更新',
				          cancelButtonText: '取消',
				          type: 'warning'
				        }).then(() => {
				        	XYBase.updateSystemVersion();
				        }).catch(() => {
				        });
					}else{
						XYBase.msg(ret.msg);
					}
				}else{
					XYBase.error(XYBase.config.system_network_error);
				}
			}
		});
	},
	updateSystemVersion(){
		var loading=XYBase.openloading('更新中，请勿关闭当前页面...');
		$.getJSON('/system/version/update',function(ret) {
			loading.close();
			if(ret){
				if(ret.code===0){
					XYBase.success(ret.msg);
					setTimeout(function() {
						window.location.reload();
					},1500)
				}else{
					XYBase.msg(ret.msg);
				}
			}else{
				XYBase.error(XYBase.config.system_network_error);
			}
		});
	}
}