var url = require("url");
var System = require("../../base/system");
const settings = require("../settings");
const logCtl = System.getObject("web.oplogCtl");
const wxsvr = System.getObject("service.wxSve");
const tradeCtl = System.getObject("web.tradeCtl");
const orderCtl = System.getObject("web.orderCtl");
cacheManager = System.getObject("db.cacheManager");
module.exports = function (app) {
	app.use("/wx/pay", wxsvr.wxpay.useWXCallback(async function (msg, req, res, next) {
		// 处理商户业务逻辑
		logCtl.error({
			optitle: "微信回调测试 非错误",
			op: "web.js",
			content: "msg",
			clientIp: msg.trade_type + ";" + msg.attach + ";" + msg.result_code + ";" + msg.return_code + ";" + msg.out_trade_no
		});
		if (msg.trade_type == "NATIVE" && msg.result_code == "SUCCESS" && msg.return_code == "SUCCESS") {
			try {
				var openid = msg.openid;
				var outkey = msg.out_trade_no;
				var webopenid = msg.attach;
				var amount = Number(msg.total_fee) / 100;
				//获取充值业务锁
				var locker = await cacheManager["CacheLocker"].enter(msg.out_trade_no);
				logCtl.error({
					optitle: "微信回调测试2 非错误",
					op: "web.js",
					content: "12345",
					clientIp: msg.openid + ";" + msg.out_trade_no + ";" + msg.total_fee + ";" + locker
				});
				if (locker && locker == "1") {
					if (webopenid.indexOf(";") >= 0) {
						var attachs = webopenid.split(";");
						var payUserOpenId = attachs[0];
						var orderNum = attachs[1];
						var obj = { payResult: msg, orderNum: orderNum, payUserOpenId: payUserOpenId };

						var d = await orderCtl.createOrderTrade3(obj);
						if (d) {
							return res.success();
						} else {
							return res.fail();
						}
					} else {
						var d = await tradeCtl.wxNotityFillMoney(outkey, webopenid, amount);
						if (d.status == 0) {
							return res.success();
						} else {
							return res.fail();
						}
					}
				} else {
					return res.fail();
				}
			} catch (e) {
				logCtl.error({
					optitle: "微信回调测试23 异常",
					op: "web.js",
					content: e.stack,
					clientIp: ""
				});
				return res.fail();

			} finally {
				await cacheManager["CacheLocker"].release(msg.out_trade_no);
			}

		} else if (msg.attach && msg.trade_type == "JSAPI" && msg.result_code == "SUCCESS" && msg.return_code == "SUCCESS") {
			try {
				var attachs = msg.attach.split("$$$");
				var payUserOpenId = attachs[0];
				var orderNum = attachs[1];
				var obj = { payResult: msg, orderNum: orderNum, payUserOpenId: payUserOpenId };
				//获取充值业务锁https://boss.gongsibao.com/wxappletStatisticyjs
				var locker = await cacheManager["CacheLocker"].enter(msg.out_trade_no);
				if (locker && locker == "1") {
					var d = await orderCtl.createOrderTrade3(obj);
					if (d) {
						return res.success();
					} else {
						return res.fail();
					}
				} else {
					return res.fail();
				}
			} catch (e) {
				return res.fail();
			} finally {
				await cacheManager["CacheLocker"].release(msg.out_trade_no);
			}
		} else {
			return res.success();
		}


		//{ appid: 'wx4c91e81bbb6039cd',
		// bank_type: 'CMB_DEBIT',
		// cash_fee: '1',
		// fee_type: 'CNY',
		// is_subscribe: 'Y',
		// mch_id: '1514728461',
		// nonce_str: '2CJtXsn6baxG9LOrGzm9OVov9wzi5oQZ',clientIp:System.get_client_ip(req),
		// openid: 'ozFDk0xaXbXK4CCN1F-Kl9HOQmd0',
		// out_trade_no: 'af82939c71f14297a7117f2609a74e13',
		// result_code: 'SUCCESS',
		// return_code: 'SUCCESS',
		// sign: 'B10C26929C6457C47A9AC9918F7FEA46',
		// time_end: '20181009181941',
		// total_fee: '1',
		// trade_type: 'NATIVE',
		// transaction_id: '4200000161201810097370773578',
		//scene_info}
		// res.success() 向微信返回处理成功信息，res.fail()返回失败信息。

	}));
	app.get('/zqq', function (req, res) {//自动提报(公司内部)
		res.render("iframe", {});
	});
	app.get('/autosubmitinside', function (req, res) {//自动提报(公司内部)
		res.render("autosubmitinside", {});
	});
	app.get('/autosubmitorder', function (req, res) {//自动提报
		res.render("autosubmitorder", {});
	});
	app.get('/automaticsubmit', function (req, res) {//自动提报
		res.render("automaticsubmit", {});
	});
	app.get('/automaticsubmitsw', function (req, res) {//自动提报
		res.render("automaticsubmitsw", {});
	});
	app.get('/autosubmithtml5s', function (req, res) {
		res.render("autosubmithtml5s", {});
	});
	app.get('/autosubmithtml5', function (req, res) {
		res.render("autosubmithtml5", {});
	});
	app.get('/mobile', function (req, res) {
		res.render("mobile", {});
	});
	app.get('/b', function (req, res) {
		res.render("biaoyan", {});
	});
	app.get('/m', function (req, res) {
		res.render("magic", {});
	});
	app.get('/p', function (req, res) {
		res.render("patentyc", {});
	});
	app.get('/h5', function (req, res) {
		res.render("h5", {});
	});
	app.get('/bpo', function (req, res) {
		res.render("bpo", {});
	});
	app.get('/needh5', function (req, res) {
		res.render("needh5", {});
	});
	app.get('/needhtml5', function (req, res) {
		res.render("needhtml5", {});
	});
	app.get('/PCneedhtml5', function (req, res) {
		res.render("PCneedhtml5", {});
	});
	app.get('/PCneedhtml5s', function (req, res) {
		res.render("PCneedhtml5s", {});
	});
	app.get('/distributeneed', function (req, res) {
		res.render("distributeneed", {});
	});
	app.get('/mobile2', function (req, res) {
		res.render("mobile2", {});
	});
	app.get('/wxappletStatistic', function (req, res) {
		res.render("wxappletStatistic", {});
	});
	app.get('/yydatayjs', function (req, res) {
		res.render("yydatayjs", {});
	});
	app.get('/wxappletStatisticforworker', function (req, res) {
		res.render("wxappletStatisticforworker", {});
	});
	app.get('/', function (req, res) {
		var code = req.query.code;
		if (code != null && code != "") {
			var state = req.query.state;
			if (settings.env != "dev" && code && code.indexOf("embed") < 0) {
				if (!state || state == "") {
					res.render("main", {});
					return;
				}
			}
			try {
				var loginCtl = System.getObject("web.userCtl");
				loginCtl.login(code, state, req).then(function (homeUrl) {
					if (homeUrl != null) {
						return res.redirect(homeUrl);
					}
				});
			} catch (e) {
				logCtl.error({
					optitle: "web 根接口调用登录异常error:",
					op: "userCtl/login",
					content: e.stack,
					clientIp: System.get_client_ip(req),
					agent: req.headers["user-agent"],
				});
			}
		} else {
			if (req.subdomains[0] && (req.subdomains[0].indexOf("cha") >= 0 || req.subdomains[0].indexOf("search") >= 0)) {
				res.render("biaoyan", {});
			} else if (req.subdomains[0] && req.subdomains[0].indexOf("magic") >= 0) {
				res.render("magic", {});
			} else if (req.subdomains[0] && req.subdomains[0].indexOf("patent") >= 0) {
				res.render("patentyc", {});
			} else {
				res.render("main", {});
			}

		}
	});
	app.all("/web/*", function (req, res, next) {
		//console.log(req.headers);
		if (req.url.indexOf("product") > 0 ||
			req.url.indexOf("getRouteConfig") > 0 ||
			req.url.indexOf("getDicConfig") > 0 ||
			req.url.indexOf("getOssConfig") > 0 ||
			req.url.indexOf("articledetail") > 0 ||
			req.url.indexOf("findAndCountAll") > 0 ||
			req.url.indexOf("findHomeInitData") > 0 ||
			req.url.indexOf("calculatepriceCtl/findByCodes") > 0 ||
			req.url.indexOf("calculatepriceCtl/findByOrderNum") > 0 ||
			req.url.indexOf("tradeCtl/createOrderPaid") > 0 ||
			req.url.indexOf("orderCtl/findOneByOrderNum") > 0 ||
			req.url.indexOf("tradeCtl/checkOrderPayState") > 0 ||
			req.url.indexOf("trademarkCtl/findByOrderNum") > 0 ||
			req.url.indexOf("pconfigCtl/getConfigValue") > 0 ||
			req.url.indexOf("articleCtl/findById") > 0 ||
			req.url.indexOf("wxCtl/fetchOAuthPath") > 0 ||
			req.url.indexOf("wxCtl/getJsApiConfig") > 0 ||
			req.url.indexOf("orderCtl/orderPay") > 0 ||
			req.url.indexOf("orderCtl/createOrderTrade") > 0 ||
			req.url.indexOf("businesschanceCtl/submitneed") > 0 ||
			req.url.indexOf("businesschanceCtl/getServiceItemList") > 0 ||
			req.url.indexOf("bytmqueryCtl") > 0 ||
			req.url.indexOf("servicesitemCtl/findByChannelcode") > 0 ||
			req.url.indexOf("channelCtl/getChannelItem") > 0 ||
			req.url.indexOf("loopplayCtl/findByChannelcode") > 0 ||
			req.url.indexOf("servicesitemCtl/getRecommendProducts") > 0 ||
			req.url.indexOf("servicesitemCtl/getAllProducts") > 0 ||
			req.url.indexOf("taskCtl/restartTasks") > 0 ||
			req.url.indexOf("taskCtl/restartTasks2") > 0 ||
			req.url.indexOf("taskCtl/makerpt") > 0 ||
			req.url.indexOf("userCtl/fetchVcode") > 0 ||
			req.url.indexOf("userCtl/findbymobile") > 0 ||
			req.url.indexOf("userCtl/loginByMobile") > 0 ||
			req.url.indexOf("userCtl/checkUserInfo") > 0 ||
			req.url.indexOf("metaCtl/getUiConfig") > 0 ||
			req.url.indexOf("ncloneCtl/getNcl") > 0 ||
			req.url.indexOf("orderCtl/getChannelOrderByOrderNum") > 0 ||
			req.url.indexOf("tmInfoPusherCtl/pushInfo") > 0 ||
			req.url.indexOf("customerInfoPusherCtl/pushInfo") > 0 ||
			(
				req.headers.access_source=="zqq1571212637509" && 
				(
					req.url.indexOf("metaCtl/getRouteConfig") > 0 || 
					req.url.indexOf("trademarkCtl/findAndCountAll") > 0 || 
					req.url.indexOf("metaCtl/getDicConfig") > 0 || 
					req.url.indexOf("orderCtl/getFqOrderDetailByOrderNum") > 0 ||
					req.url.indexOf("tmflowCtl/getDetail") > 0
				) 
			) || 
			req.url.indexOf("newschannel") > 0) {
			return next();
		}
		if (!req.session.user) {
			var x = {
				status: -99,
				msg: "no login"
			};
			res.end(JSON.stringify(x));
		} else {
			//console.log(req.headers);
			next();
		}
	});
	app.get('/web/:qname/:method', function (req, res) {
		console.log(req.headers);
		req.codepath = req.headers["codepath"];

		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);
		var p = null;
		var invokeObj = System.getObject("web." + classPath);
		if (invokeObj[methodName]) {
			p = invokeObj[methodName].apply(invokeObj, params);
		}
		p.then(r => {
			res.end(JSON.stringify(r));
		}).then(() => {
			// console.log("info.......req.session....................>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
			// console.log(req.session);
			// console.log("web---------app.get---------------------------******************************************");
			// console.log(classPath+"/"+methodName);
			params.pop();
			logCtl.info({
				optitle: "web get接口调用info:",
				op: classPath + "/" + methodName,
				content: params.length == 0 ? "" : "参数：" + JSON.stringify(params),
				clientIp: System.get_client_ip(req),
				agent: req.headers["user-agent"],
			});
		}).catch(e => {
			console.log(e);
			logCtl.error({
				optitle: "web get接口调用异常error:",
				op: classPath + "/" + methodName,
				content: e.stack,
				clientIp: System.get_client_ip(req),
				agent: req.headers["user-agent"],
			});
		});
	});
	app.post('/web/:qname/:method', function (req, res) {
		req.codepath = req.headers["codepath"];
		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);
		params.push(req);
		var p = null;
		var invokeObj = System.getObject("web." + classPath);
		if (invokeObj[methodName]) {
			p = invokeObj[methodName].apply(invokeObj, params);
		}
		p.then(r => {
			res.end(JSON.stringify(r));
		}).then(() => {
			params.pop();
			logCtl.info({
				optitle: "web post接口调用info:",
				op: classPath + "/" + methodName,
				content: params.length == 0 ? "" : "参数：" + JSON.stringify(params),
				clientIp: System.get_client_ip(req),
				agent: req.headers["user-agent"],
			});
		}).catch(e => {
			var s = System.getResult2(null, null, null, e.message);
			logCtl.error({
				optitle: "web post接口调用异常error:",
				op: classPath + "/" + methodName,
				content: e.stack,
				clientIp: System.get_client_ip(req),
				agent: req.headers["user-agent"],
			});
			res.end(JSON.stringify(s));
		});

	});
};
