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 rc = System.getObject("util.execClient");
const settings = require("../settings.js")
let channelCache = {};
module.exports = function (app) {
  app.post("/autologin", async function (req, res, next) {
    try {
      console.log('---- 免登 -----');
      console.log(req.body);
      let appkey = req.body.appkey.trim();
      if (!appkey) {
        res.json(System.getResult(null, "没有资质宝appkey,请联系资质宝服务提供方"));
        return
      }
      let companykey = req.body.companykey.trim();
      if (!companykey) {
        res.json(System.getResult(null, "没有公司宝的租户companykey,请联系资质宝服务提供方"));
        return
      }
      let cooktoken = req.body.accesskey
      let tv = cooktoken || 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImUxNzAzYzIwMDFkZDExZTliNTBmZDUyNWJjMmE3ZTFkIn0.eyJpZCI6IjVjOTM2Yjk1ODU4MGJjNGUwOGUwODQzZSIsIm5hbWUiOiLlvKDlm73np4AiLCJlbXBsb3llZSI6IjVjOTM2YmJhYzY4ZWIxMjMwOGQxMjEzOSIsInBob25lIjoickdGR1ZwZHFiOGNPMUNYeC9VOEVYQT09Iiwib3JnaWQiOiI1YmNmZTk1Y2IwYTAxZjAwMDkyODRiYzMiLCJyb2xlcyI6WyLlkZjlt6UiLCJpZHV0eeeuoeeQhuWRmCIsIuS-m-W6lOWVhuS6pOS7mCIsIui1hOi0qOWuneS6pOS7mOWRmCJdLCJwbGF0Zm9ybSI6ImQzOTViZGFkNmI2MGY0ODQ5MTEwNDA4OWNhYjU5OGI3IiwidW5pb25pZCI6IiIsImp0aSI6Im9vMGZHR1YwZUVaOWdxbTEiLCJleHAiOjE2MDg1OTkwMjQsImlhdCI6MTYwNzk5NDIyNH0.Q3QmHoUpcX14VucsivDNHfx3DYbAI6B59i0Ohb31Vmmfw1F-kI-IV8ZTvzBi-PKY3G-ZH7FS94BHvM2KOEVKdSnTLzhd-A-LzRI6xaWFDCYdGbjMJAYtmNqzD_xZZyx4diBPHxBJLeSyb_3uMi9doMH7Ef56DgJ05UC6Ip5J1KtIRUszMNR6--PnwwsZxLeBlObaJAGkEjKBQBZUvbVlpm1yleT5t4EKcVG9EMyibYnRq2MVK273tnqb8nb2NTeyVB9nRctzSzmFwCkChYbm-z4JvSjp8PEh50FL9eVqADbpUm3lbXahYKFxmQBfxMxm8ur6fgeU7y_vRXFzL3WNFw'
      let sourceUser = System.verify(tv, settings.publickey());
      console.log('--- 解析用户信息 -----');
      console.log(sourceUser);
      let openid = sourceUser.employee;
      let userName = openid;
      let nickName = sourceUser.name;
      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.json(System.getResult(null, "当前登录人没有资质宝访问权限"));
        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 = null;
        let isSalesman = false;
        let isDelivery = false;
        let skilltags = new Set();
        if (rcs.includes("资质宝交付员")) {
          isDelivery = true;
          opath = "root10/dlivergroup/dgroupmembers/" + userName;
          skilltags.add("icp,edi");
        }
        if (rcs.includes("工商交付员")) {
          isDelivery = true;
          opath = "root10/dlivergroup/dgroupmembers/" + userName;
          skilltags.add("公司注册");
        }
        if (rcs.includes("资质宝业务员")) {
          isSalesman = true;
          opath = "root10/bizgroup01/g1members/" + userName;
          skilltags.add("icp,edi");
        }
        if (rcs.includes("工商业务员")) {
          isSalesman = true;
          opath = "root10/bizgroup01/g1members/" + userName;
          skilltags.add("公司注册");
        }
        if (rcs.includes("资质宝分配员")) {
          opath = "root10/" + userName;
        }
        //调用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: [...skilltags].join()
        }
        if (rcs.includes("资质宝分配员")) {
          reguser.ptags = "root10";
        }
        uf = await userS.registerByTantent(reguser);
      }
      let rtnobj = await userS.loginApp(appkey, `${userName}`);
      res.json(System.getResult({ openurl: rtnobj.homePage + "?code=" + rtnobj.code }));
    } catch (e) {
      res.json(System.getResult(null, e.message));
    }
  })
  app.post("/autologinV1", async function (req, res, next) {
    try {
      console.log('---- 免登 -----');
      console.log(req.body);
      let appkey = req.body.appkey.trim();
      let sourceUser = req.body.userInfo;
      if (!sourceUser.employee || !sourceUser.name || !sourceUser.roles) {
        res.json(System.getResult(null, "参数有误,请联系技术人员"));
      }
      let companykey = req.body.companykey.trim();
      if (!companykey) {
        res.json(System.getResult(null, "没有公司宝的租户companykey,请联系资质宝服务提供方"));
        return
      }
      console.log(sourceUser);
      let openid = sourceUser.employee;
      let userName = openid;
      let nickName = sourceUser.name;
      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.json(System.getResult(null, "当前登录人没有资质宝访问权限"));
        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 = null;
        let isSalesman = false;
        let isDelivery = false;
        let skilltags = new Set();
        if (rcs.includes("资质宝交付员")) {
          isDelivery = true;
          opath = "root10/dlivergroup/dgroupmembers/" + userName;
          skilltags.add("icp,edi");
        }
        if (rcs.includes("工商交付员")) {
          isDelivery = true;
          opath = "root10/dlivergroup/dgroupmembers/" + userName;
          skilltags.add("公司注册");
        }
        if (rcs.includes("资质宝业务员")) {
          isSalesman = true;
          opath = "root10/bizgroup01/g1members/" + userName;
          skilltags.add("icp,edi");
        }
        if (rcs.includes("工商业务员")) {
          isSalesman = true;
          opath = "root10/bizgroup01/g1members/" + userName;
          skilltags.add("公司注册");
        }
        if (rcs.includes("资质宝分配员")) {
          opath = "root10/" + userName;
        }
        //调用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: [...skilltags].join()
        }
        if (rcs.includes("资质宝分配员")) {
          reguser.ptags = "root10";
        }
        uf = await userS.registerByTantent(reguser);
      }
      let rtnobj = await userS.loginApp(appkey, `${userName}`);
      res.json(System.getResult({ openurl: rtnobj.homePage + "?code=" + rtnobj.code }));
    } catch (e) {
      res.json(System.getResult(null, e.message));
    }
  })
  //
  app.post("/order/changeSalesman", async function (req, res, next) {
    let { appkey, companykey, orderNumber, userId, userName } = req.body;
    let salesman_opcode;
    if (!appkey || !companykey) {
      res.json(System.getResult(null, "没有公司宝的租户appkey,companykey,请联系资质宝服务提供方"));
      return
    }
    if (!orderNumber || !userId) {
      res.json(System.getResult(null, "订单号或转移人不能为空"));
      return
    }
    let uf = await userS.dao.model.findOne({ where: { openid: userId } });
    if (uf) {
      salesman_opcode = uf.opath;
      userName = uf.nickName;
    } else {
      salesman_opcode = `root10/bizgroup01/g1members/${userId}`
    }
    let rtn = await rc.execPost3({
      orderNumber,
      userId,
      userName,
      salesman_opcode
    }, `${settings.icpUrl()}/web/delivery/deliverCtl/changeSalesman`);
    res.json(JSON.parse(rtn.stdout));
  })
  app.post("/entService/*", async function (req, res, next) {
    try {
      let channel;
      const APPCODENUM = {
        ali: "ali",
        baidu: "baidu",
        baiduqifu: "baidu",
        zc360: "zc360",
        pannong: "pannong",
        ename: "ename"
      }
      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.json({ 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));
    });
  });
};
