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())

      //     { id: '5f8faf05787b88000a2e178b',
      //       name: '张华',
      //       employee: '5f8faf05787b88000a2e178c',
      //       phone: 'd1htypf8Sme3fvcXP20R+w==',
      //       orgid: '5bcfe95cb0a01f0009284bc3',
      //       roles: [ '员工', '资质宝业务员', '资质宝交付员' ],
      //       platform: '8cdf558c8645c7031f164dc23a55a28f',
      //       unionid: '',
      //       jti: 'gaBQQKKO6ZLNXNfA',
      //       exp: 1605083401,
      //       iat: 1604478601 
      //      }
      /**
       * TODO:
       * 1. 建立 磐农角色
       * 2. 建立组织结构 获取 磐农组织结构路径
       * 3. 获取角色id 设置
       */
      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 APPCODENUM = {
        ali: "ali",
        baidu: "baidu",
        baiduqifu: "baidu",
        zc360: "zc360",
        pannong: "pannong"
      }
      const appcode = req.headers && req.headers.appcode;
      let sourceHost = APPCODENUM[appcode] || "ali";
      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));
    });
  });
};
