const system = require("../../system")
const querystring = require('querystring');
const settings = require("../../../config/settings");
const AppletBase = require("../applet.base");
const logCtl = system.getObject("web.oplogCtl");
const uuidv4 = require('uuid/v4');

class LDApplet extends AppletBase {
  constructor() {
    super();
    this.ldpartnerSve = system.getObject("service.ldpartnerSve");
    this.lduserSve = system.getObject("service.lduserSve");
    this.lduserbankSve = system.getObject("service.lduserbankSve");
    this.ldusertradeSve = system.getObject("service.ldusertradeSve");
    this.esettleSve = system.getObject("service.esettleSve");

    this.redisClient = system.getObject("util.redisClient");
  }

  //************************************************************公共参数处理********************开始***************************************
  //验证公共参数信息
  async getLoginUser(req) {
    let sid = req.headers["ldh5sid"] || "";
    try {
      let user = JSON.parse(await this.redisClient.get(sid + "_user"));
      let mcht = JSON.parse(this.redisClient.get(sid + "_mcht"));
      if (user && user.id) {
        await this.addLoginCache("LD_H5_LOGIN_" + user.id, sid, user, mcht);
      }
      return {user: user, mcht: mcht};
    } catch (e) {
      console.log(e)
      return null;
    }
  }

  async encrypt(obj, req) {
    let key = {
      "partner": "1",
      "user_id": "1",
      "mchtId": "1103817785420820481",
      "balance": "50"
    };

    let en = system.encryption(JSON.stringify(key));
    console.log(en);
    console.log(encodeURIComponent(en));
  }

  async removeLoginCache(uk, sid) {
    await this.redisClient.delete(uk);
    await this.redisClient.delete(sid + "_user");
    await this.redisClient.delete(sid + "_mcht");
  }

  async addLoginCache(uk, sid, mcht, user) {
    await this.redisClient.setWithEx(uk, sid, 60 * 60);
    await this.redisClient.setWithEx(sid + "_user", JSON.stringify(user), 6 * 60 * 60);
    await this.redisClient.setWithEx(sid + "_mcht", JSON.stringify(mcht), 6 * 60 * 60);
  }

  async setLogin(user, mcht) {
    let uk = "LD_H5_LOGIN_" + user.id;
    let sid = await this.redisClient.get(uk);
    if (sid) {
      await this.removeLoginCache(uk, sid);
    }
    sid = uuidv4();
    await this.addLoginCache(uk, sid, mcht, user);
    return sid;
  }

  async login(query, body, req) {
    let data = body.data;
    if (!data) {
      return system.getErrResult2("登录失败");
    }
    let loginInfo;
    try {
      loginInfo = JSON.parse(system.decryption(decodeURIComponent((data))));
    } catch (e) {
      console.log(e);
      return system.getErrResult2(`登录失败${e.stack}`);
    }

    if (!loginInfo.partner) {
      return system.getErrResult2(`登录失败，缺少合作信息`);
    }

    if (!loginInfo.user_id) {
      return system.getErrResult2(`登录失败，缺少用户标识`);
    }

    if (!loginInfo.mchtId) {
      return system.getErrResult2(`登录失败，缺少商户信息`);
    }
    try {
      let mcht = await this.esettleSve.findMchtApiInfo({mchtId: loginInfo.mchtId});
      if (!mcht) {
        return system.getErrResult2(`登录失败，商户信息不存在`);
      }

      let partner = await this.ldpartnerSve.findById(loginInfo.partner);
      if (!partner) {
        return system.getErrResult2(`登录失败，未开通合作`);
      }

      let user = await this.lduserSve.loginH5({p_id: partner.id, p_user_id: loginInfo.user_id});

      let sid = await this.setLogin(user, partner, mcht);
      return system.getResult2({
        sid: sid,
        user: user
      });
    } catch (e) {
      console.log("登录异常:error*****************************************************************************");
      console.log(e.stack);
    }
  }

}

module.exports = LDApplet;