const system = require("../system");
const settings = require("../../config/settings");
const uuidv4 = require('uuid/v4');
class CtlBase {
  constructor(gname, sname) {
    this.serviceName = sname;
    this.service = system.getObject("service." + gname + "." + sname);
    this.cacheManager = system.getObject("db.common.cacheManager");
    this.redisClient = system.getObject("util.redisClient");
    // this.md5 = require("MD5");
    this.appS = system.getObject("service.common.appSve");
    this.comS=system.getObject("service.common.companySve");
    
  }
  getUUID() {
    var uuid = uuidv4();
    var u = uuid.replace(/\-/g, "");
    return u;
  }
  async encryptPasswd(passwd) {
    if (!passwd) {
      throw new Error("请输入密码");
    }
    var rtn = await this.service.getEncryptStr(passwd);
    return rtn;
  }
  notify(req, msg) {
    if (req.session) {
      req.session.bizmsg = msg;
    }
  }
  async findOne(queryobj, qobj) {
    var rd = await this.service.findOne(qobj);
    return system.getResult(rd);
  }
  async findAndCountAll(obj, queryobj, req) {
    obj.codepath = req.codepath;
    obj.appid = req.appid;
    if (req.session.user) {
      obj.uid = req.session.user.id;
      obj.appid = req.session.user.app_id;
      obj.account_id = req.session.user.account_id;
    }
    var apps = await this.service.findAndCountAll(obj);
    return system.getResult(apps);
  }
  async refQuery(qobj,queryobj,req) {
    if(qobj.refwhere){
      qobj.refwhere.app_id=req.appid;
      qobj.refwhere.company_id=req.tocompanyid;
    }else{
      qobj.refwhere = { app_id: req.appid,company_id:req.tocompanyid};
    }
 
    var rd = await this.service.refQuery(qobj);
    return system.getResult(rd);
  }
  async bulkDelete(queryobj, ids) {
    var rd = await this.service.bulkDelete(ids);
    return system.getResult(rd);
  }
  async delete(qobj, queryobj) {
    var rd = await this.service.delete(qobj);
    return system.getResult(rd);
  }
  async create(qobj, queryobj, req) {
    if (req && req.session && req.session.app) {
      qobj.app_id = req.appid;
      if (req.codepath) {
        qobj.codepath = req.codepath;
      }
      if (qobj.app_id == settings.platformid) {
        qobj.company_id = settings.platformcompanyid;
      }

    }
    if (req && req.tocompanyid) {//设置默认的公司id
      qobj.company_id = req.tocompanyid;
      // qobj.owner_id=req.tanentid;
    }
    var rd = await this.service.create(qobj,queryobj,req);
    return system.getResult(rd);
  }
  async update(qobj, queryobj, req) {
    if (req && req.session && req.session.user) {
      qobj.onlyCode = req.session.user.unionId;
    }
    if (req.codepath) {
      qobj.codepath = req.codepath;
    }
    var rd = await this.service.update(qobj);
    return system.getResult(rd);
  }
  static getServiceName(ClassObj) {

    return ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Ctl")).toLowerCase() + "Sve";
  }
  async initNewInstance(queryobj, req) {
    return system.getResult({});
  }
  async findById(oid) {
    var rd = await this.service.findById(oid);
    return system.getResult(rd);
  }
  async timestampConvertDate(time) {
    if (time == null) {
      return "";
    }
    var date = new Date(Number(time * 1000));
    var y = 1900 + date.getYear();
    var m = "0" + (date.getMonth() + 1);
    var d = "0" + date.getDate();
    return y + "-" + m.substring(m.length - 2, m.length) + "-" + d.substring(d.length - 2, d.length);
  }
  async universalTimeConvertLongDate(time) {
    if (time == null) {
      return "";
    }
    var d = new Date(time);
    return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
  }
  async universalTimeConvertShortDate(time) {
    if (time == null) {
      return "";
    }
    var d = new Date(time);
    return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
  }
  async setContextParams(pobj, qobj, req) {
    req.appid = req.session.app ? req.session.app.id : null;
    req.appkey = req.session.app ? req.session.app.appkey : null;
    pobj.userid = req.session.user ? req.session.user.id : null;
    var tocompany = req.session.tocompany;

    if (!req.session.app || qobj.toKey) {
      var appkey = qobj.appKey;
      var tokey = qobj.toKey;
      if (appkey) {
        var app = await this.appS.getApp(appkey);
        var toapp = await this.appS.getApp(tokey);
        req.session.app = app;
        req.session.toapp = toapp;
        req.appid = app.id;
        req.appkey = app.appkey;
      }else{//如果空，并且没有参数appkey
        var app = await this.appS.getApp(settings.appKey);
        req.session.app = app;
        req.appid = app.id;
        req.appkey = app.appkey;
      }
    }
    if(!tocompany && qobj.companyKey){
      //说明是自主登录后，跳转到目标平台进行管理操作
      tocompany=await this.comS.findOne({companykey:qobj.companyKey});
      req.session.tocompany=tocompany;
    }
  
    //只要当前APP支持saas,并且非平台那么就设置
    if (req.session.app && req.session.app.id != settings.platformid) {
      if (req.session.app.isSaas && tocompany) {
        req.tocompanyid = tocompany.id;
        pobj.tocompanyid = tocompany.id;
      } else {
        req.tocompanyid = null;
        pobj.tocompanyid = null;
      }
    } else {
      req.tocompanyid = settings.platformcompanyid;
      pobj.tocompanyid = settings.platformcompanyid;
    }
  }

  async doexec(methodname, pobj, query, req) {
    try {
      await this.setContextParams(pobj, query, req);
      // //检查appkey
      // let key = await this.cacheManager["InitAppKeyCache"].getAppKeyVal(pobj.appKey);
      // if(key==null){
      //   return system.getResultFail(system.tokenFail,"appKey授权有误");
      // }
      var rtn = await this[methodname](pobj, query, req);
      //     await this. apitradeSvr .create({
      //     appkey: pobj.appKey,
      //     tradeType: "consume",
      //     op: pobj.classname + "/" + methodname,
      //     params: JSON.stringify(pobj),
      //     clientIp: pobj.clientIp,
      //     agent: pobj.agent,
      //   });
      return rtn;
    } catch (e) {
      console.log(e.stack, "出现异常，请联系管理员.......");
      // this.logCtl.error({
      //   optitle: "api调用出错",
      //   op: pobj.classname + "/" + methodname,
      //   content: e.stack,
      //   clientIp:  pobj.clientIp
      // });
      return system.getResultFail(-200, "出现异常，请联系管理员");
    }
  }
}
module.exports = CtlBase;
