var url = require("url");
var system = require("../../base/system");
const logCtl = system.getObject("service.common.oplogSve");
var settings = require("../../config/settings");
const axios = require('axios')

module.exports = function (app) {	
	
	app.all("/operate/*", async function (req, res, next) {
        console.log("一个请求进来了")
		var result = system.getResult(null, "req method must is post");
		if (req.method != "POST") {
			res.end(JSON.stringify(result));
			return;
		}
		if (!req.body.actionType) {
			result.msg = "actionType can not be empty";
			res.end(JSON.stringify(result));
			return;
		}

		var uappId = req.body.actionBody["uappId"] || "";
		if (!uappId) {
			result.msg = "req body uappId can not be empty";
			result.data = null;
			res.end(JSON.stringify(result));
			return;
        }
        var reqUrl = settings.centerAppUrl() + "auth/accessAuth/getAppInfo";
        var appResult = await axios.post(reqUrl,{uappId:uappId});
		if (appResult.data.status != 0) {// 验证渠道失败
            result.msg = appResult.data;
			result.data = null;
			res.end(JSON.stringify(result));
			return;
        }
        req.body.actionBody["uappId"]  = appResult.data.data.uapp_id
        req.body.appInfo = appResult.data.data;
		next();
	});
    
	app.post('/operate/: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;
        
        // 记录参数
        logCtl.info({
            optitle: (new Date()).Format("yyyy-MM-dd hh:mm:ss") + "ucommune-back",
            op: "ucommune-back/" + classPath,
            content: "参数:" + JSON.stringify(req.body),
            clientIp: tClientIp || ""
        });

		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["doexecMethod"]) {
			p = invokeObj["doexecMethod"].apply(invokeObj, params);
		}
		p.then(r => {
			res.end(JSON.stringify(r));
		});
	});
};