var url = require("url");
var system = require("../../base/system");
var userSve = system.getObject("service.auth.userSve");
module.exports = function (app) {
	app.get("/auth", async function (req, res) {
		if (!req.query.opencode) {
			return system.getResult(null, "opencode参数不能为空");
		}
		return await userSve.authByCode(opencode);
	});
	app.get('/api/:gname/:qname/:method', function (req, res) {
		var classPath = req.params["qname"];
		var methodName = req.params["method"];
		var gname = req.params["gname"];

		classPath = gname + "." + classPath;
		var tClientIp = system.get_client_ip(req);
		req.clientIp = tClientIp;
		req.uagent = req.headers["user-agent"];
		req.classname = classPath;

		var params = [];
		params.push(gname);
		params.push(methodName);
		params.push(req.body);
		params.push(req.query);
		params.push(req);
		var p = null;
		var invokeObj = system.getObject("api." + classPath);
		if (invokeObj["doexec"]) {
			p = invokeObj["doexec"].apply(invokeObj, params);
		}
		p.then(r => {
			res.end(JSON.stringify(r));
		});
	});
	app.post('/api/:gname/:qname/:method', function (req, res) {
		var classPath = req.params["qname"];
		var methodName = req.params["method"];
		var gname = req.params["gname"];
		var params = [];
		classPath = gname + "." + classPath;
		var tClientIp = system.get_client_ip(req);

		req.clientIp = tClientIp;
		req.uagent = req.headers["user-agent"];
		req.classname = classPath;

		params.push(gname);
		params.push(methodName);
		params.push(req.body);
		params.push(req.query);
		params.push(req);
		let keys = Object.keys(params[2].action_body)
		for (let i of keys) {
			// 小数处理
			let regdigu = /^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$/
			let regdig = /^-[1-9]\d*\.\d*|-0\.\d*[1-9]\d*$/
			// 整数处理
			let regint = /^-?[0-9]\d*$/
			// 空key处理
			if (params[2].action_body[i] == null || params[2].action_body[i] == "" || params[2].action_body[i] == []) {
				delete params[2].action_body[i]
			} else if (Array.isArray(params[2].action_body[i])) {
				// list
				for (let j = 0; j < params[2].action_body[i]; ++j) {
					if (regdig.test(`${params[2].action_body[i][j]}`) || regdigu.test(`${params[2].action_body[i][j]}`)) {
						params[2].action_body[i][j] = Number(params[2].action_body[i][j])
					} else if (regint.test(`${params[2].action_body[i][j]}`)) {
						params[2].action_body[i][j] = Number(params[2].action_body[i][j])
					}
				}
			} else if (regdig.test(`${params[2].action_body[i]}`) || regdigu.test(`${params[2].action_body[i]}`)) {
				// 小数
				params[2].action_body[i] = Number(params[2].action_body[i])
			} else if (regint.test(`${params[2].action_body[i]}`)) {
				// 整数
				params[2].action_body[i] = Number(params[2].action_body[i])
			}
		}
		
		var p = null;
		var invokeObj = system.getObject("api." + classPath);
		if (invokeObj["doexec"]) {
			p = invokeObj["doexec"].apply(invokeObj, params);
		}
		p.then(r => {
			res.end(JSON.stringify(r));
		});
	});
};
