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) {
    try {
      console.log(req.body)
      let appkey = req.body.appkey.trim()
      if (!appkey) {
        let rd = System.getResult(null, "没有资质宝appkey,请联系资质宝服务提供方")
        res.end(JSON.stringify(rd))
        return
      }
      let companykey = req.body.companykey.trim()
      if (!companykey) {
        let rd = System.getResult(null, "没有公司宝的租户companykey,请联系资质宝服务提供方")
        res.end(JSON.stringify(rd))
        return
      }
      //let cooktoken = req.cookies["accessToken"]
      let cooktoken = req.body.accesskey
      console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>........................................")
      console.log(cooktoken)
      let tv = cooktoken
      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) {
        let rd = System.getResult(null, "当前登录人没有资质宝访问权限")
        res.end(JSON.stringify(rd))
        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: { [roleS.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,
          isAllocated: true,
          skilltags: 'icp,edi'
        }
        uf = await userS.registerByTantent(reguser)
      }
      let rtnobj = await userS.loginApp(appkey, userName)
      let rtntmp = System.getResult({ openurl: rtnobj.homePage + "?code=" + rtnobj.code })
      let rtn = JSON.stringify(rtntmp)
      res.end(rtn)
    } catch (e) {
      res.end(JSON.stringify(System.getResult(null, e.message)))
    }
  })
  app.post("/entService/*", async function (req, res, next) {
    try {
      let channel;
      const appcode = req.headers && req.headers.appcode;
      let sourceHost = appcode || "aliCloud";
      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);

        System.execLogs(
          `启服通推送`,
          {
            url: req.path + "/" + req.body.actionType,
            data: req.body,
            headers: req.headers
          },
          '交付请求',
          rtn,
          null
        ).catch(err => {
          console.log(`日志写入错误 ${url}`)
        });

        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));
    });
  });
};
