var url = require("url");
var System = require("../../base/system");
var metaCtl = System.getObject("web.common.metaCtl");
var tmqueryCtl = System.getObject("web.trademark.tmqueryCtl");
module.exports = function (app) {
	app.get("/1688/proxy", async function (req, res) {
		var params = {
			actionProcess: "1688",
			requrl: "/action/tmOrder/springBoard",
			actionType: "getChannelOrderInfo",
			actionBody: req.query
		};
		if (params.actionBody.sign) {
			params.sign = params.actionBody.sign;
			delete params.actionBody["sign"];
		}
		var result = await tmqueryCtl.doPost(params, null, req);
		if (result.status != 0) {
			res.end(JSON.stringify(result));
			return;
		}
		var skipUrl = result.skipUrl + "?itemCode=" + result.itemCode + "&channelUser=" + JSON.stringify(result.data.channelUser) + "&channelOrder=" + JSON.stringify(result.data.channelOrder) + "&channelParams=" + result.channelParams;
		res.redirect(skipUrl);
	});
	app.get("/", async function (req, res) {
		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("/admin", async function (req, res) {
		var appinfo = await metaCtl.getAppInfo(req);
		res.render("admin", 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);
		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));
		});
	});
	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);
		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));
		});
	});
};
