var url = require("url");
var System = require("../../base/system");
const settings = require("../settings");
module.exports = function (app) {
  app.all("/applet/*", function (req, res, next) {
    let openid = req.body.openid || req.query.openid;
    if (System.endWith(req.url, "applet/merchantApplet/login") ||
      System.endWith(req.url, "applet/merchantApplet/uploadConfig")) {
      if (openid) {
        req.openid = openid;
      } else {
        req.openid = null;
      }
      return next();
    }
    if (!openid) {
      res.end(JSON.stringify({ code: 403, msg: "no login" }));
      return;
    }
    return next();
  });

  app.get('/applet/:qname/:method', async function (req, res) {
    console.log("get");
    try {
      req.codepath = req.headers["codepath"];
      var classPath = req.params["qname"];
      var methodName = req.params["method"];
      var tClientIp = System.get_client_ip(req);
      var params = [];

      req.openid = req.query.openid;
      req.merchant_id = req.query.merchant_id;
      req.query.saas_merchant_id = req.query.merchant_id;
      params.push(req.query);
      params.push(req);
      var p = null;
      var invokeObj = System.getObject("applet." + classPath);
      if (invokeObj[methodName]) {
        p = invokeObj[methodName].apply(invokeObj, params);
      }
      p.then(r => {
        res.end(JSON.stringify(r));
      });
    } catch (e) {
      console.log(e);
    }

  });

  app.post('/applet/:qname/:method', async function (req, res) {
    console.log("post");
    req.codepath = req.headers["codepath"];
    var classPath = req.params["qname"];
    var methodName = req.params["method"];
    var params = [];
    req.openid = req.body.openid;
    req.merchant_id = req.body.merchant_id;
    req.body.saas_merchant_id = req.body.merchant_id; // 为历史买单，为要的急买单

    params.push(req.query);
    params.push(req.body);
    var tClientIp = System.get_client_ip(req);
    req.body.clientIp = tClientIp;
    params.push(req);
    var p = null;
    var invokeObj = System.getObject("applet." + classPath);
    if (invokeObj[methodName]) {
      p = invokeObj[methodName].apply(invokeObj, params);
    }
    p.then(r => {
      res.end(JSON.stringify(r));
    }).then(() => {
      params.pop();
      if (params && params[1] && params[1].file) {
      } else {
      }
    }).catch(e => {
      console.log(e);
    });
  });
};