var url = require("url");
var System = require("../../base/system");
const settings = require("../settings");
const wxSve = System.getObject("service.wxSve");
const utilscloudSve = System.getObject("service.utilscloudSve");
const logCtl = System.getObject("web.oplogCtl");
const userCtl = System.getObject("web.userCtl");
const empowerWxop = System.getObject("wxop.empowerWxop");
cacheManager = System.getObject("db.cacheManager");

module.exports = function (app) {

	app.get('/', async function (req, res) {
		//转到首页,获取当前域名,按照域名
		if (req.hostname == "undefined" || !req.hostname) {
			res.render("test", {});
			return;
		}
		var deviceAgent = req.headers["user-agent"].toLowerCase();
		var agentID = deviceAgent.match(/(iphone|ipod|ipad|android)/);
		if (agentID) {
			console.log("手机访问");
			res.redirect("http://" + req.hostname + "/mobile");
			return;
			// var result = await empowerWxop.getOauthLink({},req);
			// if(result && result.code==1 && result.data){
			// 	res.redirect(result.data);
			// 	return;
			// }
		}
		if (settings.env != "dev") {
			if (req.hostname && req.hostname.split(".").length == 2) {
				var s = "www." + req.hostname;
				res.redirect("http://" + s);
				return;
			}
		}
		//获取基础组件
		var x = await userCtl.preReadyData(req);
		res.render("main", x);
	});
	app.get('/test', function (req, res) {
		//转到首页,获取当前域名,按照域名
		userCtl.preFetchComanyAndFooterAndBankaccount(req).then(function (x) {
			console.log(x);
			res.render("test", { "hello": encodeURIComponent(JSON.stringify(x)) });
		});


	});
	app.get('/mobile', function (req, res) {
		//转到首页,获取当前域名,按照域名
		res.render("mobile", {});
	});
	//商标交易
	app.get('/mobiletrade', function (req, res) {
		//转到首页,获取当前域名,按照域名
		res.render("mobiletrade", {});
	});
	app.get('/mobilereportsta', function (req, res) {
		console.log("cccccc------");
		//转到首页,获取当前域名,按照域名
		res.render("mobilereportsta", {});
	});
	// 商标检索
	app.get('/mobiletmsearch', function (req, res) {
		console.log("gggggggggggggggggggggggggg------");
		//转到首页,获取当前域名,按照域名
		res.render("mobilecopy", {});
	});
	// 商标报告
	app.get('/mobilereport', function (req, res) {
		console.log("cccccc------");
		//转到首页,获取当前域名,按照域名
		res.render("mobilereport", {});
	});
	// 专利报告
	app.get('/mobilepatent', function (req, res) {
		console.log("cccccc------");
		//转到首页,获取当前域名,按照域名
		res.render("mobilepatent", {});
	});
	app.use("/wx/pay", wxSve.wxpay.useWXCallback(async function (msg, req, res, next) {
		logCtl.info({
			optitle: "微信回调信息---info",
			op: "web.js",
			content: "msg=" + msg ? JSON.stringify(msg) : msg,
			clientIp: System.get_client_ip(req)
		});
		if (!msg || !msg.out_trade_no || !msg.attach || msg.result_code != "SUCCESS" || msg.return_code != "SUCCESS") {
			logCtl.error({
				optitle: "微信回调错误---error",
				op: "web.js",
				content: "msg=" + msg ? JSON.stringify(msg) : msg,
				clientIp: System.get_client_ip(req)
			});
			return res.fail();
		}
		try {
			//获取充值业务锁
			var locker = await cacheManager["CacheLocker"].enter(msg.out_trade_no);
			if (locker && locker == "1") {
				let attachList = [];
				if (msg.attach.indexOf(";") >= 0) {
					attachList = msg.attach.split(";");
				}
				else {
					attachList.push(msg.attach);
				}
				let param = {
					order_num: attachList.length > 0 ? attachList[0] : "",
					user_id: attachList.length > 1 ? attachList[1] : "",
					out_trade_no: msg.out_trade_no,
					amount: Number(msg.total_fee) / 100
				}
				if (msg.trade_type == "NATIVE" || msg.trade_type == "JSAPI") {
					await utilscloudSve.wxPayNotify(param);
					return res.success();
				}
				else {
					return res.fail();
				}
			}
			else {
				logCtl.info({
					optitle: "微信回调操作频繁---太频繁了，太频繁了",
					op: "web.js",
					content: "msg=" + msg ? JSON.stringify(msg) : msg,
					clientIp: System.get_client_ip(req)
				});
				return res.fail();
			}
		} catch (e) {
			logCtl.error({
				optitle: "微信回调业务处理---error异常",
				op: "web.js",
				content: "error：" + e.stack + "，微信msg=" + msg ? JSON.stringify(msg) : msg,
				clientIp: System.get_client_ip(req)
			});
			return res.fail();
		} finally {
			await cacheManager["CacheLocker"].release(msg.out_trade_no);
		}

	}));
	app.get('/wts', function (req, res) {//生成商标委托书
		res.render("wts", {});
	});
	app.get('/orderpay/orderpay', function (req, res) {//生成商标委托书
		res.render("orderpay", {});
	});
	app.all("/web/*", function (req, res, next) {
		if (req.url.indexOf("getRouteConfigWithoutProduct") > 0 ||
			req.url.indexOf("patentycCtl/") > 0 ||
			req.url.indexOf("restartTasks2") > 0 ||
			req.url.indexOf("createMonitoringReportH5") > 0 ||
			req.url.indexOf("trademarktransactionCtl/findAllRecommendTm") > 0 ||
			req.url.indexOf("getRsConfig") > 0 ||
			req.url.indexOf("getDicConfig") > 0 ||
			req.url.indexOf("fetchVcode") > 0 ||
			req.url.indexOf("register") > 0 ||
			req.url.indexOf("login") > 0 ||
			req.url.indexOf("loopplay") > 0 ||
			req.url.indexOf("newschannel") > 0 ||
			req.url.indexOf("article") > 0 ||
			req.url.indexOf("channelquery") > 0 ||
			req.url.indexOf("metaCtl") > 0 ||
			req.url.indexOf("siteapply") > 0 ||
			req.url.indexOf("checkLogin") > 0 ||
			req.url.indexOf("preFetchComany") > 0 ||
			req.url.indexOf("needCtl") > 0 ||
			req.url.indexOf("footerinfoCtl") > 0 ||
			req.url.indexOf("userCtl") > 0 ||
			req.url.indexOf("filedownloadCtl/download") > 0 ||
			req.url.indexOf("filedownloadCtl/bycode") > 0 ||
			req.url.indexOf("serviceitemCtl/getRecommendProducts") > 0 ||
			req.url.indexOf("serviceitemCtl/getAllProducts") > 0 ||
			req.url.indexOf("needCtl/submitneed") > 0 ||
			req.url.indexOf("bytmqueryCtl") > 0 ||
			req.url.indexOf("bytmmonitCtl") > 0 ||
			// req.url.indexOf("toolCtl/getCropperPic") > 0 ||
			req.url.indexOf("toolCtl") > 0 ||
			req.url.indexOf("wxCtl") > 0 ||
			req.url.indexOf("orderCtl/getTmOrderDetail") > 0 ||
			req.url.indexOf("serviceitemCtl/findOneByCode") > 0 ||
			req.url.indexOf("serviceitemCtl/findOneById") > 0 ||
			req.url.indexOf("companyCtl/findById") > 0 ||
			req.url.indexOf("orderCtl/aiadive") > 0 ||
			req.url.indexOf("customerinfoCtl/findOneByCustomerName") > 0 ||
			req.url.indexOf("trademarktransactionCtl/tmTransactionSearch") > 0 ||
			req.url.indexOf("trademarktransactionCtl/tmTransactionDetail") > 0 ||
			req.url.indexOf("trademarktransactionneedCtl/submitNeed") > 0 ||
			req.url.indexOf("switchUser") > 0 ||
			req.url.indexOf("switchLogin") > 0 ||
			req.url.indexOf("systemregistCtl") > 0 ||
			req.url.indexOf("trademarktransactionCtl/findByTmType") > 0 ||
			req.url.indexOf("transactionspecialperformanceCtl/getSpecialPerformanceBySiteTheme") > 0 ||
			req.url.indexOf("producttypeCtl/getProductTypeList") > 0 ||
			req.url.indexOf("producttypeCtl/getProductList") > 0 ||
			req.url.indexOf("loopplayCtl/getLooppayList") > 0 ||
			req.url.indexOf("serviceitemCtl/findByCompany") > 0 ||
			req.url.indexOf("companyportraitCtl/phonequery") > 0 ||
			req.url.indexOf("companyportraitCtl/companynamequery") > 0 ||
			req.url.indexOf("ichemingCtl/ichemingApi") > 0 ||
			req.url.indexOf("producttypeCtl/getAllProducts") > 0 ||
			req.url.indexOf("getOssConfig") > 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"];
		req.companyid = req.headers["companyid"];
		req.theme = req.headers["theme"];
		var classPath = req.params["qname"];
		var methodName = req.params["method"];
		var params = [];
		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(() => {
			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"];
		req.companyid = req.headers["companyid"];
		req.theme = req.headers["theme"];
		req.clientIp = System.get_client_ip(req);
		var classPath = req.params["qname"];
		var methodName = req.params["method"];
		var params = [];
		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));
		});

	});
};
