var url = require("url");
var System = require("../../base/system");
var wxsvrFunc = require("../../base/service/wxsvr");
var wxcz=null;

module.exports = function (app) {
	//电子合同
	app.get('/ecwx',function(req,res){
		if(!wxcz){
			wxcz=wxsvrFunc("ecwx");
		}
		// 签名成功
		if (wxcz.checkSignature(req)) {
			res.status(200).send(req.query.echostr);
		} else {
			res.status(200).send('fail');
		}
	});
	app.post('/ecwx',function(req,res) {
		console.log(req, res, "-------------------------weixin app.post ecwx---------");
		if(!wxcz){
			wxcz=wxsvrFunc("ecwx");
		}
		// loop
		wxcz.loop(req, res);
	});

	app.get('/api/:qname/:method', function (req, res) {
		var classPath = req.params["qname"];
		var methodName = req.params["method"];
		var params = [];
		for (let k in req.query) {
			params.push(req.query[k]);
		}
		var p = null;
		var invokeObj = System.getObject("api." + classPath);
		if (invokeObj[methodName]) {
			p = invokeObj[methodName].apply(invokeObj, params);
		}
		p.then(r => {
			res.end(JSON.stringify(r));
		})
	});

	app.post('/api/:qname/:method', function (req, res) {
		var classPath = req.params["qname"];
		var methodName = req.params["method"];
		var params = [];
		for (let k in req.query) {
			params.push(req.query[k]);
		}
		//params.push(req.query);
		params.push(req.body);
		var p = null;
		var invokeObj = System.getObject("api." + classPath);
		if (invokeObj[methodName]) {
			p = invokeObj[methodName].apply(invokeObj, params);
		}
		p.then(r => {
			res.end(JSON.stringify(r));
		}).then(() => {
			// apitradeSvr.create({
			// 	appkey: req.body.appKey,
			// 	tradeType: "consume",
			// 	op: classPath + "/" + methodName,
			// 	params: JSON.stringify(req.body),
			// 	clientIp: System.get_client_ip(req),
			// 	agent: req.headers["user-agent"],
			// });
		});
	});
};