var url = require("url");
var system = require("../../base/system");
var settings = require("../settings");
var userSve = system.getObject("service.auth.userSve");
module.exports = function (app) {
	app.get("/auth", async function (req, res) {
		var opencode = req.query.opencode || "";
		if (!opencode) {
			return system.getResult(null, "opencode参数不能为空");
		}
		var user = await userSve.authByCode(opencode);
		req.session.user = user;

		console.log(req.session.id);
		res.redirect(settings.indexPage());
	});
	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);
		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));
		});
	});
};
