var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
const md5 = require("MD5");
const uuidv4 = require('uuid/v4');
const crypto = require('crypto');

var cacheBaseComp = null;
class TuserCtl extends CtlBase {
  constructor() {
    super("tax", CtlBase.getServiceName(TuserCtl));
    this.redisClient = system.getObject("util.redisClient");
  }

  async smartLogin(pobj, pobj2, req, res) {
    let data = pobj.data || "";
    if (!data) {
      return system.getResult(-1, `参数错误`);
    }
    data = this.decryption(data);
    try {
      data = JSON.parse(data);
      if (!data.userName) {
        return system.getResult(-1, `登录名称为空`);
      }
      if (!data.companyName) {
        return system.getResult(-1, `商户名称为空`);
      }
      if (!data.mchtId) {
        return system.getResult(-1, `商户号为空`);
      }

      var loginInfo = await this.service.smartLogin(data);
      loginInfo = loginInfo.data;
      let key = await this.setLogin(loginInfo);
      return system.getResultSuccess({
        taxsid: key
      });
    } catch (error) {
      console.log(error);
      return system.getResult(-1, `${data}解析错误`);
    }
  }
  
  async setLogin(user) {
    var xggadminsid = "bt_" + uuidv4();
    if(settings.env == "dev") {
      xggadminsid = "bt_3cb49932-fa02-44f0-90db-9f06fe02e5c7";
    }
    await this.redisClient.setWithEx(xggadminsid, JSON.stringify(user), 60 * 60);
    return xggadminsid;
  }

  encryption(data) {
    if (!data) {
      return "";
    }
    let AES_conf = settings.apiconfig.AES;
    let key = AES_conf.key;
    let iv = AES_conf.iv;
    // let padding = AES_conf.padding;

    var cipherChunks = [];
    var cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
    cipher.setAutoPadding(true);
    cipherChunks.push(cipher.update(data, 'utf8', 'base64'));
    cipherChunks.push(cipher.final('base64'));
    return cipherChunks.join('');
  }

  decryption(data) {
    if (!data) {
      return "";
    }
    let AES_conf = settings.apiconfig.AES;
    let key = AES_conf.key;
    let iv = AES_conf.iv;
    // let padding = AES_conf.padding;

    var cipherChunks = [];
    var decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
    decipher.setAutoPadding(true);
    cipherChunks.push(decipher.update(data, 'base64', 'utf8'));
    cipherChunks.push(decipher.final('utf8'));
    return cipherChunks.join('');
  }

}
module.exports = TuserCtl;