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));
    //this.loginS=system.getObject("service.userSve");
    this.acS = system.getObject("service.auth.accountSve");
    this.companyS = system.getObject("service.common.companySve");
  }

  async initNewInstance(queryobj, req) {
    var rtn = {};
    rtn.roles = [];
    return system.getResultSuccess(rtn);
  }
  //获取验证码，发送给指定手机
  async fetchVcode(pobj, qobj, req) {
    var mobile = pobj.u;
    //生成一个验证码，发送
    // var vcode = await this.service.getUidStr(6, 10);
    // await this.smsS.sendMsg(mobile, vcode);
    return system.getResult({ vcodestr: "123" });
  }
  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,
        isSuper:req.session.user.isSuper,
        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?req.session.user.owner:null,
        tanentor_id:req.session.user?req.session.user.tanentor_id:null,
      }
      return system.getResult(tmp, "操作成功", req);
    } else {
      req.session.user = null;
      //req.session.destroy();
      return system.getResult(null, "操作失败", req);
    }
  }
  async exit(pobj, qobj, req) {
    if(req.session.app.id==settings.platformid){
      req.session.user = null;
      req.session.tocompany=null;
      req.session.destroy();
      return system.getResultSuccess({ "env": settings.env });
    }else{
      req.session.user=req.session.originalUID;
      req.session.app=req.session.originalAPP;
      return system.getResultSuccess({ "env": settings.env });
    }

  }
  /**
   * 
   * //用户重名检查--account
   * 
   * 先按照username和password检查,是否存在account,
   * 如果不存在account(第一次注册)，检查查询字符串中是否存在appkey,
   *                    如果不存在说明是平台用户注册，就从会话中取出app_id
   * 
   * 如果存在（已经注册过）
   *      检查查询字符串appkey，如果存在，那么就按照appkey和userName和password去查看是否存在用户
   *                                                           如果存在，提示已经有同名用户存在；
   *                                                           如果不存在，那么就创建app下的用户
   *                                           如果不存在，就按照会话中app_id去查看是否存在用户
   *                                                         
   */
  //重名检查,检查是否有
  async checkSameName(pobj, qobj, req) {
    var uname = pobj.uname;
    //按照appid查询出app
    var rtn = await this.service.checkSameName(uname, req.appid);
    return system.getResult(rtn);

  }
  /**
   * 查询某一个应用管理员信息
   * @param {*} pobj 
   * @param {*} qobj 
   * @param {*} req 
   */
  async findAppAdmin(pobj, qobj, req) {
    var appid = pobj.appid;
    var user = await this.service.findOne({ isAdmin: true, app_id: appid });
    return system.getResult(user);
  }
  async register(pobj, qobj, req) {
    var appid = req.session.app.id;
    var jumpUrl = req.session.app.authUrl;
    var fmuser = pobj.u;
    fmuser.app_id = req.appid;
    if (!fmuser.userName) {
      return system.getResult(null, "用户名不能为空");
    }
    if (!fmuser.mobile) {
      return system.getResult(null, "手机号不能为空");
    }
    if (!fmuser.password) {
      return system.getResult(null, "密码不能为空");
    }
    if (appid == settings.platformid){//如果是开放平台应用注册，设置所属公司
      fmuser.owner_id=settings.platformid;
    }else{//否则 todo
      if(!fmuser.owner_id && req.session.tocompany){
        fmuser.owner_id=req.tanentid;
      }
    }
    var ruser = await this.service.register(fmuser);
    if (ruser) {
      if (appid != settings.platformid) {//说明是委托注册或登录
        // this.redisClient.setWithEx(req.session.id,ruser,3600);
        await this.cacheManager["OpenCodeCache"].cache(req.session.id, ruser, 30);
        jumpUrl = jumpUrl + "?code=" + req.session.id;
      } else {
        //登录
        req.session.user = ruser;
        //设置系统默认公司
        var pcompany=await  this.companyS.findById(settings.platformcompanyid);
        req.session.company=pcompany;
      }
      return system.getResultSuccess({ user: ruser, jumpUrl: jumpUrl });
    } else {
      return system.getResult(null, "用户已存在, 请修改并重试");
    }
  }
  //管理员新增用户，设置默认密码
  async create(pobj, queryobj, req) {
    pobj.appid = req.appid;
    pobj.owner_id=req.tanentid;
    //新增用户时，获取当前用户的租户id
    pobj.tanentor_id=req.session.user.tanentor_id;
    var rtn=await this.service.createUser(pobj);
    return system.getResult(rtn);
  }
  /**
   * inuser 当前的req.session.app不是平台时，退出按钮关闭的是
   * req.session.inuser
   * @param {*} req 
   */
  async authByCode(req) {
    var opencode = req.query.code;
    var user = await this.service.authByCode(opencode);
    if (user) {
      req.session.originalUID=req.session.user;
      req.session.originalAPP=req.session.app;
      req.session.user = user;//防止覆盖租户的session
      req.session.tocompany=user.owner;//从应用中导航到平台管理,平台完成登录
    } else {
      req.session.user = null;
    }
    return user;

  }
  // async bindCompany(p,q,req){
  //    var cmpinfo=p.u;
  //    var cmp=await this.service.bindCompany(cmpinfo,req.session.user.id);
  //    req.session.company=cmp;
  //    return system.getResult(cmp);

  // }
  //非开放平台登录方法
  async goLoginForApp(p,q,req){
    var app=p;
    var appid=app.id;
    var jumpUrl = app.authUrl;
    var usercurrent=req.session.user;
    var pobj={};
    pobj.u={
      userName:usercurrent.userName,
      password:usercurrent.password,
      mobile:usercurrent.mobile,
      app_id:appid,
      isNavto:true,
      owner_id:req.session.tocompany?req.session.tocompany.id:null
    }
    var existedUser = await this.service.getUserByUserNamePwd(pobj.u);
    if (existedUser != null) {
      await this.cacheManager["OpenCodeCache"].cache(req.session.id, existedUser, 60);
      jumpUrl = jumpUrl + "?code=" + req.session.id;
      return system.getResult({ user: existedUser, jumpUrl: jumpUrl });
    }else {
      return system.getResultFail(-1, "账号或密码有误.");
    }
  }
  async login(pobj, qobj, req) {
    var appid = req.session.app.id;
    var jumpUrl = req.session.app.authUrl;
    if (req.session.toapp) {
      jumpUrl = req.session.toapp.authUrl;
      pobj.u.isNavto=true;
      //state为p_app表中appkey
    } else{
      pobj.u.isNavto=false;
    }
    pobj.u.app_id = appid;
    if(!pobj.u.owner_id){//说明不是从平台界面，利用go进入，所以是自主登录
      pobj.u.owner_id=pobj.tanentid;
    }
    var existedUser = await this.service.getUserByUserNamePwd(pobj.u);
    if (existedUser != null) {
      if (appid != settings.platformid) {//非平台应用
        await this.cacheManager["OpenCodeCache"].cache(req.session.id, existedUser, 60);
        jumpUrl = jumpUrl + "?code=" + req.session.id;
        if (req.session.toapp) {
          jumpUrl = jumpUrl + "&srcKey=" + req.session.app.appkey;
        }
      } else {
        req.session.user = existedUser;
        //查询出companys信息,缓存当前的compnay,todo 放到service
        var pcompany=await  this.companyS.findById(settings.platformcompanyid);
        req.session.company=pcompany;
        //设置平台登录后默认要去往的租户公司
        //查看用户身上是否有tanentor_id值，如果没有，说明是平台租户
        var maproleids= existedUser.Roles.map((r)=>r.id);
        var istanentorpassrole=maproleids.indexOf(settings.passroleid)>=0 || maproleids.indexOf(settings.commonroleid)>=0;
        if(istanentorpassrole && !existedUser.isAdmin && !existedUser.isSuper){
          var coms=existedUser.companies;
          if(coms && coms.length>1){//因为平台默认公司的存在
            var comfinds=coms.find((item)=>{
              return item.usercompany.isCurrent==true;
            });
            if(comfinds){
              req.session.tocompany=comfinds;
            }
          }
        }else{
          req.session.tocompany=existedUser.owner;
        }
     
      }
      if (!existedUser.isEnabled) {
        return system.getResultFail(system.waitAuditApp, "您的账户处于待审核等待启用状态.");
      }
      return system.getResult({ user: existedUser, jumpUrl: jumpUrl });
    } else {
      return system.getResultFail(-1, "账号或密码有误.");
    }
  }
}
module.exports = UserCtl;
