const system=require("../../../system");
const ServiceBase=require("../../sve.base")
const settings=require("../../../../config/settings")
class UserService extends ServiceBase{
  constructor(){
     super("auth",ServiceBase.getDaoName(UserService));
  }
  async authByCode(code){
    var existedUser=null;
    var rawUser=null;
    var openuser=await this.apiCallWithAk(settings.paasUrl()+"api/auth/accessAuth/authByCode",{opencode:code});
    if(openuser){
        //先查看是否已经存在当前用户
        existedUser=await this.dao.findOne({userName:openuser.userName,app_id:openuser.app_id});
        if(!existedUser){
          existedUser=await this.register(openuser);
        }
        rawUser=existedUser.get({raw:true});
        rawUser.Roles=openuser.Roles;
        rawUser.owner=openuser.owner;
    }
    return rawUser;
  }
  async register(fmuser){
    var self=this;
    return this.db.transaction(async function (t){
        var cruser=await self.dao.create(fmuser,t);
         return cruser;
      
    });
  }
  //在平台进行登录，返回目标认证地址
  //由于是从某个具体应用导航回平台，那么需要带着这个应用所属的公司信息
  //todo
  async navSysSetting(user){
    var sysLoginUrl=settings.paasUrl()+"web/auth/userCtl/login?appKey="+settings.appKey+"\&toKey="+settings.paasKey;
    var x={userName:user.userName,password:user.password,mobile:user.mobile,owner_id:user.owner.id};
    var restResult=await this.restS.execPost({u:x},sysLoginUrl);
    if(restResult){
      var rtnres=JSON.parse(restResult.stdout);
      if(rtnres.status==0){
        return rtnres.data;
      }else{

      }
    }
    return null;
  }
  async getUserByUserNamePwd(u){
    var user= await this.dao.model.findOne({
      where:{userName:u.userName,password:u.password,app_id:u.app_id},
      include:[
        { model: this.db.models.role, as: "Roles", attributes: ["id", "code"] },
        ]
    });
    return user;
  }
  async checkSameName(uname,appid){
    var ac= await this.dao.model.findOne({where:{userName:uname,app_id:appid}});
    var rtn={isExist:false};
    if(ac){
      rtn.isExist=true;
    }
    return rtn;
  }
}
module.exports=UserService;
// var task=new UserService();
// task.getUserStatisticGroupByApp().then(function(result){
//   console.log((result));
// }).catch(function(e){
//   console.log(e);
// });
