var url = require("url");
var system = require("../../base/system");
var metaCtl = system.getObject("web.common.metaCtl");
const redisClient = system.getObject("util.redisClient");

module.exports = function (app) {
	app.all("/web/*", async function (req, res, next) {

		var xggadminsid = req.headers["xggadminsid"] || "";
		var jsonUser = await redisClient.get(xggadminsid);

		if (req.url.indexOf("auth/userCtl/login") > 0 ||
			req.url.indexOf("auth/userCtl/captcha") > 0 ||
			req.url.indexOf("auth/userCtl/smsCode") > 0 ||
			req.url.indexOf("common/metaCtl/getApiDoc") > 0 ||

			req.url.indexOf("getRsConfig") > 0) {
			if (jsonUser) {
				req.loginUser = JSON.parse(jsonUser);
			} else {
				req.loginUser = null;
			}
			return next();
		}

		if (!jsonUser) {
			res.end(JSON.stringify({ status: -99, msg: "no login" }));
			return;
		} else {
			redisClient.setWithEx(xggadminsid, jsonUser, 60 * 60 * 12);
		}
		req.loginUser = JSON.parse(jsonUser);
		next();
	});

	app.get("/", async function (req, res) {
		res.render("index", { appinfo: null, app: null });

		// console.log(req.hostname);
		// var appinfo=await metaCtl.getAppInfo(req);
		// if(!appinfo){
		// 	res.render("index",{appinfo:null,app:null});
		// }else{
		// 	res.render("index",appinfo);
		// }
	});
	app.get('/web/: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 params = [];
		params.push(methodName);
		params.push(req.body);
		params.push(req.query);
		params.push(req);
		params.push(res);
		var p = null;
		var invokeObj = system.getObject("web." + classPath);
		if (invokeObj["doexec"]) {
			p = invokeObj["doexec"].apply(invokeObj, params);
		}
		p.then(r => {
			console.log(req.url, "req.url...................");
			console.log(r, "req###############################");
			res.end(JSON.stringify(r));
		});
	});
	app.post('/web/: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.body.clientIp = tClientIp;
		req.body.agent = req.headers["user-agent"];
		req.body.classname = classPath;
		params.push(methodName);
		params.push(req.body);
		params.push(req.query);
		params.push(req);
		params.push(res);
		var p = null;
		var invokeObj = system.getObject("web." + classPath);
		if (invokeObj["doexec"]) {
			p = invokeObj["doexec"].apply(invokeObj, params);
		}
		p.then(r => {
			res.end(JSON.stringify(r));
		});
	});
};
