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.db.models.user.findOne({where:{userName:openuser.userName,app_id:openuser.app_id,company_id:openuser.owner.id}});
        if(!existedUser){
          openuser.company_id=openuser.owner.id;
          existedUser=await this.register(openuser);
        }
        rawUser=existedUser.get({raw:true});
        rawUser.Roles=openuser.Roles;
        rawUser.owner=openuser.owner;
        rawUser.opath=openuser.opath;
        rawUser.ppath=openuser.ppath; 
        rawUser.password=openuser.password;
    }
    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;
    if(settings.companyKey){//说明是自主登录，不需要平台内go登录
      sysLoginUrl=settings.paasUrl()+"web/auth/userCtl/login?appKey="+settings.appKey+"\&toKey="+settings.paasKey+"\&companyKey="+settings.companyKey;
    }
    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);
// });
