var url = require("url");
var system = require("../../base/system");
var metaCtl = system.getObject("web.common.metaCtl");
var tmqueryCtl = system.getObject("web.trademark.tmqueryCtl");
var logClient = system.getObject("util.logClient");

const jwt = require('jsonwebtoken');
const secret = '3rZ3aNfGAyQAB4sE';   //自定义
module.exports = function (app) {
	app.get("/admin", async function (req, res) {
		console.log("jd==================================admin==============================================================================================");
		res.redirect("https://oauth2.jdcloud.com/authorize?response_type=token&redirect_uri=https://tm.plus.jdcloud.com/jdtm/getUser&state=OAjdlist&client_id=9491577327154697");
		return;

	});
	app.get("/jdtm/getUser", async function (req, res) {
		try {
			var params = req.query;
			if (!params.state) {
				res.redirect("/#/jd/jdtrademark");
				return;
			}
			var getUserparams = {
				actionProcess: "jd",
				authUrl: "https://oauth2.jdcloud.com/userinfo",
				authToken: params.token_type + " " + params.access_token
			};
			var userItemResult = await tmqueryCtl.getJdUserInfo(getUserparams, req.query, req);
			logClient.info("jd", {
				optitle: "###获取京东用户结果...getJdUserInfo",
				op: "/jdtm/getUser",
				content: "参数=" + JSON.stringify(getUserparams) + "，result=" + JSON.stringify(userItemResult),
				clientIp: ""
			});
			if (userItemResult.status != 0) {
				res.redirect("/#/jd/jdtrademark");
				return;
			}
			if (!userItemResult.data.encryptChannelUserId || userItemResult.data.encryptChannelUserId == "undefined") {
				userItemResult = await tmqueryCtl.getUserIdEncryptStr(getUserparams, req.query, req);
				if (userItemResult.status != 0) {
					res.redirect("/#/jd/jdtrademark");
					return;
				}
			}
			var skipUrl = "/#/jd/" + params.state + "?channelUserId=" + encodeURIComponent(userItemResult.data.encryptChannelUserId);
			res.redirect(skipUrl);
		} catch (error) {
			logClient.error("jd", {
				optitle: "###获取京东用户异常...getJdUserInfo",
				op: "/jdtm/getUser",
				content: error.stack,
				clientIp: ""
			});
		}
	});
	app.get("/jd/orderNotify", async function (req, res) {
		logClient.payLog("jd", {
			optitle: "###操作订单结果参数...orderNotify",
			op: "/jd/orderNotify",
			content: "req.query=" + JSON.stringify(req.query) + "，req.body=" + JSON.stringify(req.body),
			clientIp: ""
		});
		req.query.actionProcess = "jd";
		var result = await tmqueryCtl.pushJdPayOrder(req.query, req);
		logClient.payLog("jd", {
			optitle: "###操作订单结果...orderNotify",
			op: "/jd/orderNotify",
			content: "result=" + JSON.stringify(result),
			clientIp: ""
		});
		if (result.status != 0) {
			res.end(JSON.stringify(result));
			return;
		}
		var params =
		{
			instanceId: req.query.orderBizId,
			appInfo: {
				authUrl: "https://tm.plus.jdcloud.com/jd/skipPage?channelUserId=" + req.query.jdPin,
				adminUrl: "https://tm.plus.jdcloud.com"
			}
		};
		res.end(JSON.stringify(params));
		return;
	});
	app.get("/jd/skipPage", async function (req, res) {
		logClient.payLog("jd", {
			optitle: "###操作订单结果后跳转参数...skipPage",
			op: "/jd/skipPage",
			content: "req.query=" + JSON.stringify(req.query) + "，req.body=" + JSON.stringify(req.body),
			clientIp: ""
		});
		var channelUserId = req.query.channelUserId;
		if (channelUserId && channelUserId.indexOf('?') >= 0) {
			channelUserId = channelUserId.split("?")[0];
		}
		var getUserparams = {
			actionProcess: "jd",
			channelUserId: channelUserId
		};
		var userItemResult = await tmqueryCtl.getUserIdEncryptStr(getUserparams, req.query, req);
		if (userItemResult.status != 0) {
			logClient.payLog("jd", {
				optitle: "###操作订单结果...orderNotify...加密用户错误",
				op: "/jd/orderNotify",
				content: "result=" + JSON.stringify(userItemResult),
				clientIp: ""
			});
			res.redirect("/#/jd/jdtrademark");
			return;
		}
		res.redirect("/#/jd/jdindentlist?channelUserId=" + encodeURIComponent(userItemResult.data.encryptChannelUserId));
		return;
	});

	app.get("/1688/selfRegister", async function (req, res) {
		var getUserparams = {
			actionProcess: "1688",
			channelUserId: req.query.channelUserId
		};
		var userItemResult = await tmqueryCtl.getUserIdEncryptStr(getUserparams, req.query, req);
		if (userItemResult.status != 0) {
			res.end({ user: "user is null" });
			return;
		}
		var params = {
			actionProcess: "1688",
			requrl: "/action/tmOrder/springBoard",
			actionType: "op1688ChannelPushOrder",
			actionBody: req.query
		};
		params.actionBody.channelItemCode = "1406046";
		var result = await tmqueryCtl.doPost(params, null, req);
		if (result.status != 0) {
			console.log(result, "result.........");
			res.end(JSON.stringify(result));
			return;
		}
		var skipUrl = "/#/1688/jdindentlist?channelUserId=" + encodeURIComponent(userItemResult.data.encryptChannelUserId);
		res.redirect(skipUrl);
	});
	app.get("/1688/auxRegister", async function (req, res) {
		var getUserparams = {
			actionProcess: "1688",
			channelUserId: req.query.channelUserId
		};
		var userItemResult = await tmqueryCtl.getUserIdEncryptStr(getUserparams, req.query, req);
		if (userItemResult.status != 0) {
			res.end({ user: "user is null" });
			return;
		}
		var params = {
			actionProcess: "1688",
			requrl: "/action/tmOrder/springBoard",
			actionType: "op1688ChannelPushOrder",
			actionBody: req.query
		};
		params.actionBody.channelItemCode = "3492659";
		var result = await tmqueryCtl.doPost(params, null, req);
		if (result.status != 0) {
			console.log(result, "result.........");
			res.end(JSON.stringify(result));
			return;
		}
		var skipUrl = "/#/1688/jdindentlist?channelUserId=" + encodeURIComponent(userItemResult.data.encryptChannelUserId);
		res.redirect(skipUrl);
	});

	app.get("/gsbhome", async function (req, res) {
		var skipUrl = "/#/gsbhome/selftmreg?channelUserId=";
		var params = req.query;
		if (!params.state) {
			res.redirect(skipUrl);
			return;
		}
		var token = req.cookies.ic_token;
		if (!token) {
			res.redirect(skipUrl);
			return;
		}
		var userInfo = jwt.verify(token, secret, function (err, decoded) {
			if (err) {
				return system.getResult(null, "验证token失败");
			}
			else {
				return system.getResultSuccess(decoded);
			}
		});
		if (userInfo.status != 0) {
			res.redirect(skipUrl);
			return;
		}
		var getUserparams = {
			actionProcess: "gsbhome",
			channelUserId: userInfo.data.phone + "_" + userInfo.data.id,
			channelUserMoblie: userInfo.data.phone
		};
		var userItemResult = await tmqueryCtl.getUserIdEncryptStr(getUserparams, req.query, req);
		if (userItemResult.status != 0) {
			res.redirect(skipUrl);
			return;
		}
		skipUrl = "/#/gsbhome/" + params.state + "?channelUserId=" + encodeURIComponent(userItemResult.data.encryptChannelUserId);
		res.redirect(skipUrl);
	});
	app.get("/gsbhome/orderNotify", async function (req, res) {
		req.query.actionProcess = "gsbhome";
		var result = await tmqueryCtl.pushGsbPayOrder(req.query, req);
		if (result.status != 0) {
			res.end(JSON.stringify(result));
			return;
		}
		var params =
		{
			order_no: req.query.order_no,
			success: true,
			auth_url: "https://zcchannelweb.gongsibao.com/gsbhome?state=jdindentlist"
		};
		res.end(JSON.stringify(params));
		return;
	});
	app.get("/", async function (req, res) {
		try {
			var appinfo = await metaCtl.getAppInfo(req);
			if (!appinfo) {
				res.render("index", { appinfo: null, app: null });
			} else {
				res.render("index", appinfo);
			}
		} catch (error) {
			console.log(error.stack, "get/admin，error.............");
		}
	});
	app.get("/admin", async function (req, res) {
		try {
			var appinfo = await metaCtl.getAppInfo(req);
			res.render("admin", appinfo);
		} catch (error) {
			console.log(error.stack, "get/admin，error.............");
		}

	});
	app.get('/web/:gname/:qname/:method', function (req, res) {
		try {
			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));
			});
		} catch (error) {
			console.log(error.stack, "get/web/:gname/:qname/:method，error.............");
		}
	});
	app.post('/web/:gname/:qname/:method', function (req, res) {
		try {
			console.log(req.params, "post req.params ..............");
			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));
			});
		} catch (error) {
			console.log(error.stack, "post/web/:gname/:qname/:method，error.............");
		}
	});
};
