const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")
class UserService extends ServiceBase {
  constructor() {
    super("auth", ServiceBase.getDaoName(UserService));
    this.accountDao = system.getObject("db.auth.accountDao");
    //  this.pConfigDao=system.getObject("db.pconfigDao");
    //  this.pTradeDao=system.getObject("db.tradeDao");
    this.appDao = system.getObject("db.common.appDao");
    this.roleDao = system.getObject("db.auth.roleDao");
    this.compDao=system.getObject("db.common.companyDao");
  }
  async modiPasswordByMobile(appid,mobile,newpwd){
    var self=this;
    var newp=await super.getEncryptStr(newpwd);
    return this.db.transaction(async function (t) {
      var mu=await self.db.models.user.findOne({
        where:{app_id:appid,mobile:mobile},
        include:[
         {model:self.db.models.account},
        ],
        transaction:t
      });
      mu.account.password=newp;
      await mu.account.save({transaction:t});
      //按照accountid去批量修改密码
      await self.db.models.user.update({password:newp},{where:{account_id:mu.account_id},transaction:t});
      return mu;
    });
  }
  async modiPasswordByUserName(appid,uname,newpwd,oldpwd){
    var self=this;
    var newp=await super.getEncryptStr(newpwd);
    var oldp=oldpwd?await super.getEncryptStr(oldpwd):null;
     return this.db.transaction(async function (t) {
       var mu=null;
       if(oldp){
         mu=  await self.db.models.user.findOne({
          where:{app_id:appid,userName:uname,password:oldp},
          include:[
           {model:self.db.models.account},
          ],
          transaction:t
        });
       }else{
        mu=  await self.db.models.user.findOne({
          where:{app_id:appid,userName:uname},
          include:[
           {model:self.db.models.account},
          ],
          transaction:t
        });
       }
       if(mu){
          mu.account.password=newp;
          await mu.account.save({transaction:t});
        //按照accountid去批量修改密码
          await self.db.models.user.update({password:newp},{where:{account_id:mu.account_id},transaction:t});
       }
       return mu;
     });
  }
  async bindCompany(cmpinfo,uid){
     var self=this;
     return this.db.transaction(async function (t) {
       //先按照公司名称查询，是否存在
      var comp=await  self.compDao.model.findOne({where:{name:cmpinfo.name}});
      if(!comp){
         comp=await  self.compDao.model.create(cmpinfo,{transaction:t});
         //设置登录用户的公司ID
         await self.dao.model.update({company_id:comp.id},{where:{id:uid},transaction:t});
      }else{
        await comp.update(cmpinfo,{transaction:t});
      }
      return comp;
     });
  }
  async authByCode(opencode) {
    var openuser = await this.cacheManager["OpenCodeCache"].cache(opencode);
    return openuser;
  }
  async checkSameName(uname, appid, t) {
    var ac = await this.dao.model.findOne({ where: { userName: uname, app_id: appid }, transaction: t });
    var rtn = { isExist: false };
    if (ac) {
      rtn.isExist = true;
    }
    return rtn;
  }
  //具体某个应用内检查同名，添加公司信息的校验,具体针对具体某个应用用户
  //具体某个非平台应用的用户具有owner_id的公司信息
  //每个在平台登录的用户，先查询出，查看身份是否是租户，如果是
  //如果是pass,那么就查询出
  async checkSameNameWithCompany(uname, appid,compid, t) {
    var ac = await this.dao.model.findOne({ where: { userName: uname, app_id: appid,owner_id:compid}, transaction: t });
    var rtn = { isExist: false };
    if (ac) {
      rtn.isExist = true;
    }
    return rtn;
  }
  //为租户创建具体某个应用的管理员
  async createAdminUser(pobj) {
    var u = { userName: pobj.userName, password: pobj.password, app_id: pobj.app_id, mobile: pobj.mobile,owner_id:pobj.owner_id,tanentor_id:pobj.tanentor_id};
    var rtn = await this.registerAppAdmin(u);
    return rtn;
  }
//为租户创建具体某个应用的管理员,不需要加密码
  async registerAppAdmin(fmuser) {
    var self = this;
    fmuser.isAdmin = true;
    return this.db.transaction(async function (t) {
      var sameNameData = await self.checkSameNameWithCompany(fmuser.userName, fmuser.app_id,fmuser.owner_id, t);
      if (!sameNameData.isExist) {
        if (!fmuser.nickName || fmuser.nickName == "") {
          fmuser.nickName = fmuser.userName;
        }
        //管理员的默认路径设置为/
        fmuser.opath="/";
        fmuser.ppath="/";
        var cruser = await self.dao.create(fmuser, t);
        //按照手机号去查询account,如果没有就创建
        var ac = await self.accountDao.findOne({ mobile: cruser.mobile });
        if (!ac) {
          var acnew = await self.accountDao.create(fmuser, t);
          await cruser.setAccount(acnew, { transaction: t });
        } else {
          await cruser.setAccount(ac, { transaction: t });
        }
        return cruser;
      } else {
        return null;
      }
    });
  }

  async queryUsersByAppId(appid){
      var userlist=await this.dao.model.findAll({where:{app_id:appid},attributes:{exclude: ['password']}});
      return userlist;
  }
  async createUser(pobj) {
    var u = { 
      userName: pobj.userName, 
      password: settings.defaultpwd, 
      app_id: pobj.appid, 
      mobile: pobj.mobile,
      owner_id:pobj.owner_id,
      tanentor_id:pobj.tanentor_id,
      org_id:pobj.org_id
    };
    var rtn = await this.registerCommon(u);
    return rtn;
  }
  //租户公司管理员创建普通用户
  async registerCommon(fmuser) {
    var self = this;
    fmuser.password = await super.getEncryptStr(fmuser.password);
    return this.db.transaction(async function (t) {
        //按照org_id,查询出角色，给当前用户设置角色,查询出是否是主岗
        var orgcurrent=await self.db.models.org.findOne({
            where:{id:fmuser.org_id},transaction:t,
            include:[
              {model:self.db.models.role,as:"roles",attributes:['id','code','name']},
       ]});
       if(orgcurrent.isMain){//如果是主岗
        fmuser.opath=orgcurrent.orgpath;
        var n=orgcurrent.orgpath.lastIndexOf("/");
        fmuser.ppath=orgcurrent.orgpath.substring(0,n);
       }else{
        fmuser.opath=orgcurrent.orgpath;
        fmuser.ppath= fmuser.opath;
       }

      var sameNameData = await self.checkSameName(fmuser.userName, fmuser.app_id, t);
      if (!sameNameData.isExist) {
        if (!fmuser.nickName || fmuser.nickName == "") {
          fmuser.nickName = fmuser.userName;
        }
        var cruser = await self.dao.create(fmuser, t);

        //按照手机号去查询account,如果没有就创建
        var ac = await self.accountDao.findOne({ mobile: cruser.mobile });
        if (!ac) {
          var acnew = await self.accountDao.create(fmuser, t);
          await cruser.setAccount(acnew, { transaction: t });
        } else {
          await cruser.setAccount(ac, { transaction: t });
        }
  
        await cruser.setRoles(orgcurrent.roles, { transaction: t });
        var rtnu=await self.dao.model.findOne({
          where:{id:cruser.id},transaction:t,
          include: [
            { model: self.db.models.role, as: "Roles", attributes: ["id", "code"] },
            { model: self.db.models.company,include:[self.db.models.app]},
            { model: self.db.models.company,as:"owner"},
            { model: self.db.models.user,as:"tanentor",include:[
              { model: self.db.models.company,include:[self.db.models.app]},
            ]},
          ],
        });
          //创建一个平台非租户用户，角色是pass,登录时，路过角色
          //先去检查是否已经存在，按照用户名，密码，电话,app_id=1，如果不存在
          //就创建，如果存在了
      var passuser=await self.dao.model.findOne({
        where:{
          userName:fmuser.userName,
          password:fmuser.password,
          mobile:fmuser.mobile,
          app_id:settings.platformid
        },transaction:t
      });
      if(!passuser){
        var ptpassuser={
          userName:fmuser.userName,
          nickName:fmuser.userName,
          password:fmuser.password,
          mobile:fmuser.mobile,
          account_id:rtnu.account_id,
          owner_id:settings.platformcompanyid,
          tanentor_id:rtnu.tanentor_id,
          app_id:settings.platformid
        };
         passuser=await self.dao.create(ptpassuser,t);
        //查询出路过角色,设置路过角色
        var passrole=await self.db.models.role.findById(settings.passroleid);
        await passuser.setRoles([passrole],{transaction:t});
        //查询出相关租户所关联的公司
        var cmps=rtnu.tanentor.companies;
        var comfinds=cmps.find((item)=>{
          return item.usercompany.isCurrent==true;
        });
        await passuser.addCompanies(cmps,{transaction:t});
        var up2=await self.db.models.usercompany.update({isCurrent:true},{where:{user_id:passuser.id,company_id:comfinds.id},transaction:t});
      }
      return rtnu;
      } else {
        return null;
      }
    });
  }
  async register(fmuser) {
    var self = this;
    fmuser.password = await super.getEncryptStr(fmuser.password);
    return this.db.transaction(async function (t) {
      var sameNameData = await self.checkSameName(fmuser.userName, fmuser.app_id, t);
      if (!sameNameData.isExist) {
        if (!fmuser.nickName || fmuser.nickName == "") {
          fmuser.nickName = fmuser.userName;
        }
        var cruser = await self.dao.create(fmuser, t);
        //按照手机号去查询account,如果没有就创建
        var ac = await self.accountDao.findOne({ mobile: cruser.mobile });
        if (!ac) {
          var acnew = await self.accountDao.create(fmuser, t);
          await cruser.setAccount(acnew, { transaction: t });
        } else {
          await cruser.setAccount(ac, { transaction: t });
        }
       //设置默认普通角色,由于有了租户概念,所以注册时，需要知道当前租户和应用的id 才可以设置默认角色 todo
        // var role = await self.roleDao.model.findOne({ where: { code: "common" }, transaction: t });
        // await cruser.setRoles([role], { transaction: t });
       // }

       //如果是平台应用，那么注册时需要关联蜂擎默认公司，添加默认的common角色
       if(settings.platformid==cruser.app_id){
         await self.db.models.usercompany.create({user_id:cruser.id,company_id:settings.platformcompanyid,isCurrent:true},{transaction:t});
         var role = await self.roleDao.model.findOne({ where: { code: "common",company_id: settings.platformcompanyid,app_id:settings.platformid}, transaction: t });
        await cruser.setRoles([role], { transaction: t });
        }
        var rtnu=await self.dao.model.findOne({
          where:{id:cruser.id},transaction:t,
          include: [
            { model: self.db.models.role, as: "Roles", attributes: ["id", "code"] },
            { model: self.db.models.company,include:[self.db.models.app]},
            { model: self.db.models.company,as:"owner"},
            { model: self.db.models.user,as:"tanentor"},
          ],
        });
        return rtnu;
      } else {
        return null;
      }
    });
  }
  async getUserByUserNamePwdForApi(u) {
    //勇于从别的应用中，点击页面连接，跳转到平台应用中进行管理
    u.password = await super.getEncryptStr(u.password);
    var user=null;
    if(u.app_id==settings.platformid){
      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"] },
          { model: this.db.models.company,include:[this.db.models.app]},
          { model: this.db.models.company,as:"owner"},
          { model: this.db.models.user,as:"tanentor"},
        ]
      });
    }else{
      user = await this.dao.model.findOne({
        where: {userName: u.userName, password: u.password, app_id: u.app_id},
        include: [
          { model: this.db.models.company,include:[this.db.models.app]},
        ]
      });
    }
    return user;
  }
  async getUserByUserNamePwd(u) {
    //勇于从别的应用中，点击页面连接，跳转到平台应用中进行管理
    if(!u.isNavto){
      u.password = await super.getEncryptStr(u.password);
    }
    var user=null;
    if(u.app_id==settings.platformid){
      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"] },
          { model: this.db.models.company,include:[this.db.models.app]},
          { model: this.db.models.company,as:"owner"},
          { model: this.db.models.user,as:"tanentor"},
        ]
      });
    }else{
      user = await this.dao.model.findOne({
        where: {userName: u.userName, password: u.password, app_id: u.app_id,owner_id:u.owner_id},
        include: [
          { model: this.db.models.role, as: "Roles", attributes: ["id", "code"] },
          { model: this.db.models.company,include:[this.db.models.app]},
          { model: this.db.models.company,as:"owner"},
        ]
      });
    }
    return user;
  }
  async getUserByUserMobile(u) {
    //勇于从别的应用中，点击页面连接，跳转到平台应用中进行管理
    var user = await this.dao.model.findOne({
      where: { mobile: u.mobile,app_id: u.app_id },
      include: [
        { model: this.db.models.role, as: "Roles", attributes: ["id", "code"] },
      ]
    });
    return user;
  }
}

module.exports = UserService;
// var task=new UserService();
// task.getUserStatisticGroupByApp().then(function(result){
//   console.log((result));
// }).catch(function(e){
//   console.log(e);
// });
