var url = require("url");
var System = require("../../base/system");
const chnelapi = System.getObject("api.common.channels")
const userS = System.getObject("service.auth.userSve")
const roleS = System.getObject("service.auth.roleSve")
const companyS = System.getObject("service.common.companySve")
const settings = require("../settings.js")
let channelCache = {};
module.exports = function (app) {
	app.post("/autologin", async function (req, res, next) {
		console.log(req.body)
		let appkey = req.body.appkey.trim()
		if (!appkey) {
			res.end("没有资质宝appkey,请联系资质宝服务提供方")
			return
		}
		let companykey = req.body.companykey.trim()
		if (!companykey) {
			res.end("没有公司宝的租户companykey,请联系资质宝服务提供方")
			return
		}
		let cooktoken = req.cookies["accessToken"]
		let tv = cooktoken
		try {


			let sourceUser = System.verify(tv, settings.publickey())
			let openid = sourceUser.employee
			let userName = openid
			let nickName = sourceUser.name
			let unid = sourceUser.unionid
			let fixedcodes = ["资质宝交付员", '资质宝业务员']
			let rolecodes = sourceUser.roles ? sourceUser.roles : []
			let rcs = rolecodes.filter(rc => {
				if (fixedcodes.indexOf(rc) >= 0) {
					return true
				} else {
					return false
				}
			})
			if (rcs.length == 0) {
				res.end("当前登录人没有资质宝访问权限")
				return
			}
			//先按照openid去查看是否已经存在
			let uf = await userS.dao.model.findOne({ where: { openid: openid } })
			if (!uf) {
				//按照公司companykey查询出要注册公司的所在公司，取公司id
				let company = await companyS.dao.model.findOne({ where: { companykey: companykey } })
				//构造注册用户对象,需要设置默认角色，默认角色需要按照rolecode查询出角色
				let rolesfind = await roleS.dao.model.findAll({ where: { code: { [self.db.Op.in]: rcs }, company_id: company.id } })
				//根据rolecode--,设置组织路径
				let opath = ''
				let isSalesman = false
				let isDelivery = false
				if (rcs[0] == "资质宝业务员") {
					opath = "root10/bizgroup01/g1members/" + userName
					isSalesman = true
				} else {
					opath = "root10/dlivergroup/dgroupmembers/" + userName
					isDelivery = true
				}
				//调用pmregister
				let reguser = {
					company_id: company.id,
					userName: userName,
					nickName: nickName,
					roles: rolesfind.map(r => r.id),
					opath: opath,
					openid: openid,
					isSalesman: isSalesman,
					isDelivery: isDelivery
				}
				uf = await userS.registerByTantent(reguser)
			}
			let rtnobj = await userS.loginApp(appkey, userName)
			let rtn = JSON.stringify({ openurl: rtnobj.homePage + "?code=" + rtnobj.code })
			res.end(rtn)
		} catch (e) {
			res.end(e.message)
		}
	})
	app.post("*", async function (req, res, next) {
		try {
			let channel;
			let sourceHost = req.headers["x-forwarded-host"];
			if (sourceHost in channelCache) {
				channel = channelCache[sourceHost];
			} else {
				channel = await chnelapi.getChannels(sourceHost);
				channelCache[sourceHost] = channel;
			}
			if (!channel) {
				next()
			} else {
				let rtn = await chnelapi.channelHandle(channel, req.path + "/" + req.body.actionType, req.body)
				if (rtn != null) {
					res.end(JSON.stringify(rtn));
				} else {
					res.end(JSON.stringify({ status: -1, message: "fail" }));
				}
			}
		} catch (e) {
			console.log(e)
			res.end(JSON.stringify({ status: -1, message: e }));
		}
	})
	app.get('/api/:gname/:qname/:method', function (req, res) {
		// var classPath = req.params["qname"];
		var methodName = req.params["method"];
		var gname = req.params["gname"];
		classPath = gname + "." + classPath;
		var tClientIp = System.get_client_ip(req);
		req.clientIp = tClientIp;
		req.uagent = req.headers["user-agent"];
		// req.classname=classPath;

		var params = [];
		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["doexec"]) {
			p = invokeObj["doexec"].apply(invokeObj, params);
		}
		p.then(r => {
			res.end(JSON.stringify(r));
		});
	});
	app.post('/api/: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;
		console.log("====================");
		console.log(classPath);
		var tClientIp = System.get_client_ip(req);
		req.clientIp = tClientIp;
		req.uagent = req.headers["user-agent"];
		// req.classname=classPath;

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