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");

var cacheBaseComp = null;
class UserCtl extends CtlBase {
  constructor() {
    super("auth", CtlBase.getServiceName(UserCtl));
  }

  /**
   * 开放平台回调处理
   * @param {*} req 
   */
  async authByCode(req) {
    var opencode = req.query.code;
    var user = await this.service.authByCode(opencode);
    if (user) {
      req.session.user = user;
    } else {
      req.session.user = null;
    }
    //缓存opencode,方便本应用跳转到其它应用
    //  /auth?code=xxxxx,缓存没有意义，如果需要跳转到其它应用，需要调用
    //平台开放的登录方法，返回 <待跳转的目标地址>/auth?code=xxxxx
    //this.cacheManager["OpenCodeCache"].cacheOpenCode(user.id,opencode);
    return user;
  }

  async navSysSetting(pobj, qobj, req) {
    //开始远程登录，返回code
    var jumpobj = await this.service.navSysSetting(req.session.user);
    if (jumpobj) {
      if(settings.companyKey){//说明是自主登录
        jumpobj.jumpUrl=jumpobj.jumpUrl+"&companyKey="+settings.companyKey;
      }
      return system.getResultSuccess(jumpobj);
    }
    return system.getResultFail();
  }

  async loginUser(qobj, pobj, req) {
    return super.findById(req.session.user.id);
  }
  async initNewInstance(queryobj, req) {
    var rtn = {};
    rtn.roles = [];
    if (rtn) {
      return system.getResultSuccess(rtn);
    }
    return system.getResultFail();
  }

  async checkLogin(gobj, qobj, req) {
    //当前如果缓存中存在user,还是要检查当前user所在的域名，如果不和来访一致，则退出重新登录
    if (req.session.user) {
      var x = null;
      if (req.session.user.Roles) {
        x = req.session.user.Roles.map(r => { return r.code });
      }
      var tmp = {
        id: req.session.user.id,
        userName: req.session.user.userName,
        nickName: req.session.user.nickName,
        mobile: req.session.user.mobile,
        isAdmin: req.session.user.isAdmin,
        created_at: req.session.user.created_at,
        email: req.session.user.email,
        headUrl: req.session.user.headUrl,
        roles: x ? x.join(",") : "",
        owner:req.session.user.owner,
        isSelfLogin:settings.companyKey?true:false
      }
      return system.getResult(tmp, "用户登录", req);
    } else {
      req.session.user = null;
      //req.session.destroy();
      return system.getResult(null, "用户未登录", req);
    }
  }
  async exit(pobj, qobj, req) {
    req.session.user = null;
    req.session.destroy();
    return system.getResultSuccess({ "env": settings.env });
  }
}
module.exports = UserCtl;
