var fs = require("fs");
var objsettings = require("../config/objsettings");
var settings = require("../config/settings");
class System {
	static declare(ns) {
		var ar = ns.split('.');
		var root = System;
		for (var i = 0, len = ar.length; i < len; ++i) {
			var n = ar[i];
			if (!root[n]) {
				root[n] = {};
				root = root[n];
			} else {
				root = root[n];
			}
		}
	}
	static register(key, ClassObj) {
		if (System.objTable[key] != null) {
			throw new Error("相同key的对象已经存在");
		} else {
			let obj = new ClassObj();
			System.objTable[key] = obj;
		}

		return System.objTable[key];
	}
	static getResult(data, opmsg = "操作成功", req) {
		return {
			status: !data ? -1 : 0,
			msg: opmsg,
			data: data || null,
			bizmsg: req && req.session && req.session.bizmsg ? req.session.bizmsg : "empty"
		};
	}
	static getErrResult2(errmsg) {
		return this.getResult2(null, null, null, errmsg);
	}
	static getResult2(data, req, okmsg = "操作成功", errmsg = "操作失败") {
		var result = {
			status: 0,
			msg: okmsg,
			data: data,
		};
		if (req && req.session && req.session.bizmsg) {
			result.bizmsg = req.session.bizmsg;
			req.session.bizmsg = null;
		} else {
			result.bizmsg = "empty";
		}
		if (!data) {
			result.status = -1;
			result.msg = errmsg;
		}
		return result;
	}
	static getResult3(data, req, okmsg = "操作成功", errmsg = "操作失败") {
		var total = data.total;
		data = data.hits;
		var sources = [];
		data.forEach(function (d) {
			sources.push(d._source);
		})
		var result = {
			status: 0,
			msg: okmsg,
			total: total,
			data: sources,

		};
		if (req && req.session && req.session.bizmsg) {
			result.bizmsg = req.session.bizmsg;
			req.session.bizmsg = null;
		} else {
			result.bizmsg = "empty";
		}
		if (!data) {
			result.status = -1;
			result.msg = errmsg;
		}
		return result;
	}
	static getResult4(j, req, okmsg = "操作成功", errmsg = "操作失败") {

		var aggs = j.aggregations;
		var codes_count = aggs.ncl_one_codes_count;
		var bucketlist = codes_count.buckets;
		var bucklist = [];
		bucketlist.forEach(function (d) {
			bucklist.push(d);
		})
		var data = j.hits;
		var total = data.total;
		var hit = data.hits;
		var sources = [];
		hit.forEach(function (d) {
			sources.push(d._source);
		})
		var result = {
			status: 0,
			msg: okmsg,
			total: total,
			data: sources,
			buckets: bucklist,
		};
		if (req && req.session && req.session.bizmsg) {
			result.bizmsg = req.session.bizmsg;
			req.session.bizmsg = null;
		} else {
			result.bizmsg = "empty";
		}
		if (!hit) {
			result.status = -1;
			result.msg = errmsg;
		}
		return result;
	}
	static getResultjuhe4(j, req, okmsg = "操作成功", errmsg = "操作失败") {

		var aggs = j.aggregations;
		var codes_count = aggs.ncl_one_codes_count;
		var bucketlist = codes_count.buckets;
		var bucklist = [];
		bucketlist.forEach(function (d) {
			bucklist.push(d);
		})
		var result = {
			status: 0,
			msg: okmsg,
			buckets: bucklist,
		};
		if (!bucklist) {
			result.status = -1;
			result.msg = errmsg;
		}
		return result;
	}
	static getResultjuhetwo(j, req, okmsg = "操作成功", errmsg = "操作失败") {
		var aggs = j.aggregations;
		var notice_count = aggs.notice_count;
		var bucketlist = notice_count.buckets;
		var bucklist = [];
		bucketlist.forEach(function (d) {
			var notice_issue = d.key;
			var date = d.date_max.value;
			var data = {
				notice_issue: notice_issue,
				date: date
			}
			bucklist.push(data);
		})
		var result = {
			status: 0,
			msg: okmsg,
			buckets: bucklist,
		};
		if (!bucklist) {
			result.status = -1;
			result.msg = errmsg;
		}
		return result;
	}
	/**
	 * 请求返回成功
	 * @param {*} data 操作成功返回的数据
	 * @param {*} okmsg 操作成功的描述
	 */
	static getResultSuccess(data, okmsg = "success") {
		return {
			status: 0,
			msg: okmsg,
			data: data || null,
		};
	}

	/**
	 * 请求返回成功 自定义
	 * @param {*} data 操作成功返回的数据
	 * @param {*} okmsg 操作成功的描述
	 */
	static getResultCustomSuccess(data, okmsg = "success") {
		return {
			status: 0,
			msg: okmsg,
			...data
		};
	}

	/**
	 * 请求返回失败
	 * @param {*} status 操作失败状态，默认为-1
	 * @param {*} errmsg 操作失败的描述，默认为fail
	 * @param {*} data 操作失败返回的数据
	 */
	static getResultFail(status = -1, errmsg = "fail", data = null) {
		return {
			status: status,
			msg: errmsg,
			data: data,
		};
	}
	static getObject(objpath) {
		var pathArray = objpath.split(".");
		var packageName = pathArray[0];
		var groupName = pathArray[1];
		var filename = pathArray[2];
		var classpath = "";
		if (filename) {
			classpath = objsettings[packageName] + "/" + groupName;
		} else {
			classpath = objsettings[packageName];
			filename = groupName;
		}

		var objabspath = classpath + "/" + filename + ".js";
		if (System.objTable[objabspath] != null) {
			console.log(objabspath, "get cached obj....");
			return System.objTable[objabspath];
		} else {
			console.log("no cached...");
			var ClassObj = require(objabspath);
			return System.register(objabspath, ClassObj);
		}
	}
	static getUiConfig(appid) {
		var configPath = settings.basepath + "/app/base/db/metadata/" + appid + "/index.js";
		if (settings.env == "dev") {
			delete require.cache[configPath];
		}
		var configValue = require(configPath);
		return configValue;
	}
	static getUiConfig2(appid) {
		var configPath = settings.basepath + "/app/base/db/metadata/index.js";
		// if(settings.env=="dev"){
		// 	console.log("delete "+configPath+"cache config");
		// 	delete require.cache[configPath];
		// }
		delete require.cache[configPath];
		var configValue = require(configPath);
		return configValue[appid];
	}
	static get_client_ip(req) {
		var ip = req.headers['x-forwarded-for'] ||
			req.ip ||
			req.connection.remoteAddress ||
			req.socket.remoteAddress ||
			(req.connection.socket && req.connection.socket.remoteAddress) || '';
		var x = ip.match(/(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$/);
		if (x) {
			return x[0];
		} else {
			return "localhost";
		}

	};

	static y2f(y) {
		if (!y) {
			return 0;
		}
		return (Number(y) * 100).toFixed(0);
	}

	static f2y(f) {
		if (!f) {
			return 0;
		}
		return parseFloat((Number(f) / 100).toFixed(2));
	}

	static f2y4list(list, fields, prev) {
		if (!list || list.length == 0 || !fields || fields.length == 0) {
			return;
		}
		prev = prev || "";
		for (var item of list) {
			for (var f of fields) {
				var v = item[f];
				if (v) {
					try {
						item[f + "_y"] = prev + parseFloat((Number(v) / 100).toFixed(2));
					} catch (error) {
						console.log(error);
					}
				}
			}
		}
	}
}
Date.prototype.Format = function (fmt) { //author: meizz
	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;
}
System.exTime = 4 * 3600;//缓存过期时间，4小时

System.objTable = {};

//缓存失效
System.cacheInvalidation = -88;
System.noLogin = -99;

//访问token失效，请重新获取
System.tokenFail = 1000;
//appKey授权有误
System.appKeyError = 1100;
//应用处于待审核等待启用状态
System.waitAuditApp = 1110;
//渠道应用处于待审核等待启用状态
System.waitAuditSelfApp = 1120;
//用户处于待审核等待启用状态
System.getUserInfoFail = 1140;
//访问appid失效，请重新获取
System.appidFail = 1200;
//签名验证失败，请重新获取
System.signFail = 1300;
//获取访问token失败
System.getAppInfoFail = 1130;

//已经存在信息
System.existData = 1400;

module.exports = System;