var url = require("url");
var System = require("../../base/system");
var wxsvr=require("../../base/service/wxsvr");
const settings=require("../settings");
const logCtl=System.getObject("web.oplogCtl");
const xml2js = require("xml2js");
module.exports = function (app) {
	app.use("/wxop/empowerWxop/receiveEmpowerMsg", function (req, res, next) {//公众号授权回调
		try {
			// 获取XML内容
			var buf = '';
			req.setEncoding('utf8');
			req.on('data', function (chunk) {
				buf += chunk;
			});
			// 内容接收完毕
			req.on('end', async function () {
				xml2js.parseString(buf, function (err, json) {
					if (err) {
						err.status = 400;
					} else {
						req.body = json;
					}
				});
				return next();
			});
		} catch (e) {
			logCtl.error({
				optitle:"微信开放平台 公众号授权回调异常：接收xml",
				op:classPath+"/"+methodName,
				content:e.stack,
				clientIp:""
			});
			return next();
		}
	});
	app.use("/wxop/oauth",function(req, res, next){
		try {
			req.codepath=req.headers["codepath"];
			var classPath="empowerWxop";
			var methodName="oauth";
			var params=[];
	      	params.push(req.query);
			params.push(req);
			var p=null;
			var invokeObj= System.getObject("wxop."+classPath);
			if(invokeObj[methodName]){
				p=invokeObj[methodName].apply(invokeObj,params);
			}
			p.then(r=>{
				logCtl.info({
					optitle: "wxop微信开放平台 oauth认证 --hostname+res ",
					op: "/base/wxop/impl/empowerWxop.js/oauth",
					content: req.hostname +"---"+JSON.stringify(r),
					clientIp: ""
				});
				if(req.session.company){
					req.companyid = req.session.company.id;
					logCtl.info({
						optitle: "wxop微信开放平台 oauth认证 --company ",
						op: "/base/wxop/impl/empowerWxop.js/oauth",
						content: JSON.stringify(req.session.company),
						clientIp: ""
					});
				}
				if(req.session.user){
					logCtl.info({
						optitle: "wxop微信开放平台 oauth认证 user ",
						op: "/base/wxop/impl/empowerWxop.js/oauth",
						content: JSON.stringify(req.session.user),
						clientIp: ""
					});
				}
				if(req.session.wxuser){
					logCtl.info({
						optitle: "wxop微信开放平台 oauth认证 wxuser ",
						op: "/base/wxop/impl/empowerWxop.js/oauth",
						content: JSON.stringify(req.session.wxuser),
						clientIp: ""
					});
				}
				if(req.session.company && req.session.company.domainname){
					if(req.session.wxuser && req.session.wxuser.openid){
						var url = "http://" + req.session.company.domainname+"/mobile?openid="+req.session.wxuser.openid;
						if(r.stateObj){
							var stateObj = r.stateObj;
							if(stateObj){
								logCtl.info({
									optitle:"微信开放平台 oauth stateObj",
									op:"empowerWxop/oauth",
									content:JSON.stringify(stateObj),
									clientIp:""
								});
								if(stateObj.redirectPageName){//回调跳转页面
									url = "http://" + req.session.company.domainname+"/"+stateObj.redirectPageName+"?openid="+req.session.wxuser.openid;
								}
								if(stateObj.entcode){//企业渠道码
									url = url+"&entcode="+stateObj.entcode;
								}
								if(stateObj.callbackpage){//回调跳转路由
									url = url+"#/"+stateObj.callbackpage;
								}
							}
						}
						res.redirect(url);
					}else{
						var url = "http://" + req.session.company.domainname+"/mobile";
						res.redirect(url);
					}
					return;
				}
				res.redirect("http://" + req.hostname+"/mobile");
				return;
			}).then(()=>{
				params.pop();
			})
		} catch (e) {
			logCtl.error({
				optitle:"微信开放平台 oauth认证",
				op:"empowerWxop/oauth",
				content:e.stack,
				clientIp:""
			});
		}
	});
	app.use("/wxop/receiveMsgAndEvent/:appid", function (req, res, next) {
		try {
			// 获取XML内容
			var buf = '';
			req.setEncoding('utf8');
			req.on('data', function (chunk) {
				buf += chunk;
			});
			// 内容接收完毕
			req.on('end', async function () {
				xml2js.parseString(buf, function (err, json) {
					if (err) {
						err.status = 400;
					} else {
						req.body = json;
					}
				});
				req.codepath=req.headers["codepath"];
				var classPath="pushmsgWxop";
				var methodName="receiveMsgAndEvent";
				var params=[];
				var appid = req.params["appid"];
				req.body["appid"]=appid;
				params.push(req.query);
				params.push(req.body);
				var tClientIp=System.get_client_ip(req);
				req.body.clientIp=tClientIp;
				params.push(req);
				var p=null;
				var invokeObj= System.getObject("wxop."+classPath);
				if(invokeObj[methodName]){
					p=invokeObj[methodName].apply(invokeObj,params);
				}
				p.then(r=>{
					if(!r){
						res.end("");
					}else{
						res.end(r);
					}
				}).then(()=>{
					params.pop();
				})
			});
		} catch (e) {
			logCtl.error({
				optitle:"微信开放平台 公众号消息事件回调异常：接收xml",
				op:"pushmsgWxop/receiveMsgAndEvent",
				content:e.stack,
				clientIp:""
			});
		}
	})

	app.get('/wxop/:qname/:method', function(req,res){
		try {
			req.codepath=req.headers["codepath"];
			req.companyid = req.headers["companyid"];
			req.theme = req.headers["theme"];
	  	  	var classPath=req.params["qname"];
			var methodName=req.params["method"];
			var tClientIp=System.get_client_ip(req);
			var params=[];
	      	params.push(req.query);
			params.push(req);
			var p=null;
			var invokeObj= System.getObject("wxop."+classPath);
			if(invokeObj[methodName]){
				p=invokeObj[methodName].apply(invokeObj,params);
			}
			p.then(r=>{
				if(classPath == "empowerWxop" && methodName=="authorizedBack"){
					if(r.code && r.code==1){//授权成功
						res.redirect("http://" + req.hostname+"/mobile#/mobilewxauthoback?code=1&msg=测试");
					}else{
						res.redirect("http://" + req.hostname+"/mobile#/mobilewxauthoback?code=-1&msg="+r.msg);//授权失败
					}

					return;
				}else{
					res.end(JSON.stringify(r));
				}

			});
		} catch (e) {
			logCtl.error({
				optitle:"微信开放平台 get接口调用异常error:",
				op:classPath+"/"+methodName,
				content:e.stack,
				clientIp:tClientIp,
				agent:req.headers["user-agent"],
			});
		}

	});
	app.post('/wxop/:qname/:method', function(req,res){
		req.codepath=req.headers["codepath"];
		var classPath=req.params["qname"];
	    var methodName=req.params["method"];
		var params=[];
      	params.push(req.query);
		params.push(req.body);
		var tClientIp=System.get_client_ip(req);
		req.body.clientIp=tClientIp;
		var db=System.getObject("db.connection").getCon();
		var cacheManager=System.getObject("db.cacheManager");
		var key=req.query.key;
		if(key){
			var userInfo = cacheManager["wxopUserinfoCache"].get(key);
			if(userInfo){
				req["userinfo"]=JSON.parse(userInfo);
			}
		}
		params.push(req);
		var p=null;
		var invokeObj= System.getObject("wxop."+classPath);
		if(invokeObj[methodName]){
			p=invokeObj[methodName].apply(invokeObj,params);
		}
		p.then(r=>{
			if(classPath=="empowerWxop" && methodName=="receiveEmpowerMsg"){
				res.end(r);
			}else{
				res.end(JSON.stringify(r));
			}
		}).then(()=>{
			params.pop();
		}).catch(e=>{
			logCtl.error({
				optitle:"微信开放平台 post接口调用异常error:",
				op:classPath+"/"+methodName,
				content:e.stack,
				clientIp:tClientIp,
				agent:req.headers["user-agent"],
			});
		});
	});
};
