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];
	}
	/**
	 * 请求返回成功
	 * @param {*} data 操作成功返回的数据,有值为成功，无值为失败
	 * @param {*} okmsg 操作成功的描述
	 * @param {*} req 请求头信息
	 */
	static getResult(data, opmsg = "操作成功", req) {
		return {
			status: !data ? -1 : 0,
			msg: opmsg,
			data: data,
			bizmsg: req && req.session && req.session.bizmsg ? req.session.bizmsg : "empty"
		};
	}
	/**
	 * 请求返回成功
	 * @param {*} data 操作成功返回的数据
	 * @param {*} okmsg 操作成功的描述
	 */
	static getResultSuccess(data, okmsg = "success") {
		return {
			status: 0,
			msg: okmsg,
			data: data,
		};
	}
	/**
	 * 请求返回失败
	 * @param {*} status 操作失败状态，默认为-1
	 * @param {*} errmsg 操作失败的描述，默认为fail
	 * @param {*} data 操作失败返回的数据
	 */
	static getResultFail(status = -1, errmsg = "fail", data = null) {
		return {
			status: status,
			msg: errmsg,
			data: data,
		};
	}
	/**
	 * 请求处理异常
	 * @param {*} errmsg 操作失败的描述，默认为fail
	 * @param {*} data 操作失败返回的数据
	 */
	static getResultError(errmsg = "fail", data = null) {
		return {
			status: -200,
			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) {
			return System.objTable[objabspath];
		} else {
			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";
		}

	};
}
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;
}
/*
编码说明，
1000----1999  为请求参数验证和app权限验证
2000----2100  为请求用户信息操作验证，如：注册，登录，获取验证码，修改用户信息，修改用户密码
 */


System.objTable = {};
//访问token失效，请重新获取
System.tokenFail = 1000;
//appKey授权有误
System.appKeyError = 1100;
//应用处于待审核等待启用状态
System.waitAuditApp = 1110;
//获取访问token失败
System.getAppInfoFail = 1130;

//已经存在此用户，注册失败
System.existUserRegFail = 2000;
//用户名或密码错误
System.userLoginFail = 2010;
//用户名错误
System.userNameLoginFail = 2020;
//验证验证码错误
System.verifyVCodeFail = 2030;
//opencode存储的值已经失效
System.verifyOpencodeFail = 2040;
module.exports = System;

// rc=System.getObject("tool.restClient");
// rc.execDownload("http://gsb-public.oss-cn-beijing.aliyuncs.com/netsharp_SPEPdWCBp4xAtzrsiTcZWQ2CXK7aW8Dz.jpg","./a.jpg").then(function(result){
// 	console.log(result.stderr);
// });

  // var oss=System.getObject("tool.oss");

	// oss.upfile(key,"/usr/devws/OMC/igirl-api/r3resize.jpg").then(function(result){
	//   console.log(result);
	// }).then(function(){
	// 	oss.downfile(key).then(function(result){
	// 	  console.log(result);
	// 	});
	// });



	// eimage=System.getObject("tool.easyimage");
	// eimage.convert("/usr/devws/OMC/igirl-api/r3.jpg","/usr/devws/OMC/igirl-api/r4.pdf").then(function(r,t){
	// 	console.log(r)
	// 	console.log(t)
	// }).catch(function(e){
	// 	console.log(e);
	// });
	//var coss=System.getObject("service.convertoss");
//======================模板嵌套
// tmplTable=attrs=>`
// 	<table>
// 	${attrs.map(attr=>`
// 	    <tr><td>${attr.id}</td><td>${attr.name}</td></tr>
// 	`).join()}
// 	</table>
// `
// var data=[
// 	{id:1,name:'jy'},
// 	{id:2,name:'tom'},
// ]
// var rtnHtml=tmplTable(data)
// console.log(rtnHtml)

//========根据模板，动态生成javascript表达式，根据模板生成脚本表达式
// let template = `
// <ul>
//   <% for(let i=0; i < data.supplies.length; i++) { %>
//     <li><%= data.supplies[i] %></li>
//   <% } %>
// </ul>
// `;

// //===>通过郑则编译为
// echo('<ul>');
// for(let i=0; i < data.supplies.length; i++) {
//   echo('<li>');
//   echo(data.supplies[i]);
//   echo('</li>');
// };
// echo('</ul>');


// let evalExpr = /<%=(.+?)%>/g;
// let expr = /<%([\s\S]+?)%>/g;

// template = template
//   .replace(evalExpr, '`); \n  echo( $1 ); \n  echo(`')
//   .replace(expr, '`); \n $1 \n  echo(`');
// console.log(template)
// //生成脚本表达式
// template = 'echo(`' + template + '`);';

// //=========模板编译函数--返回渲染函数
// function compile(template){
// 	const evalExpr = /<%=(.+?)%>/g;
// 	const expr = /<%([\s\S]+?)%>/g;

// 	template = template
// 	  .replace(evalExpr, '`); \n  echo( $1 ); \n  echo(`')
// 	  .replace(expr, '`); \n $1 \n  echo(`');

// 	template = 'echo(`' + template + '`);';

// 	let script =
// 	`(function parse(data){
// 	  let output = "";

// 	  function echo(html){
// 		output += html;
// 	  }

// 	  ${ template }

// 	  return output;
// 	})`;

// 	return script;
//   }
