var url = require("url");
var System = require("../../base/system");
const settings = require("../settings.js")
let channelCache = {};
module.exports = function (app) {
	app.post("*", async function (req, res, next) {
		console.log("---- 进来了- ----")
		try {
			let channel;
			// let sourceHost = req.headers["x-forwarded-host"];
			let sourceHost = req.hostname;
			if (sourceHost in channelCache) {
				channel = channelCache[sourceHost];
			} else {
				channel = await chnelapi.getChannels(sourceHost);
				channelCache[sourceHost] = channel;
			}
			if (!channel) {
				next()
			} else {
				let rtn = await chnelapi.channelHandle(channel, req.path + "/" + req.body.actionType, req.body)
				if (rtn != null) {
					res.end(JSON.stringify(rtn));
				} else {
					res.end(JSON.stringify({ status: -1, message: "fail" }));
				}
			}
		} catch (e) {
			console.log(e)
			res.end(JSON.stringify({ status: -1, message: e }));
		}
	})
	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;
		console.log("====================");
		console.log(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));
		});
	});
};
