const system=require("../../system");
const Dao=require("../dao.base");
class RoleDao extends Dao{
  constructor(){
    super(Dao.getModelName(RoleDao));
  }
  async findOne(paramappid,t){
    var app=  await this.model.findOne({where:{appid:paramappid}},{transaction:t});
    return app;
  }
  extraModelFilter(){
    return {"key":"include","value":[{model:this.db.models.app,},{model:this.db.models.product,as:"Products",attributes:["id","name"],}]};
  }
  async preUpdate(u){
    if(u.products.length>0){
      var products=await this.db.models.product.findAll({where:{id:{[this.db.Op.in]:u.products}}});
      u.products=products;
    }
    return u;
  }
  async update(obj){
    var obj2=await this.preUpdate(obj);
    await this.model.update(obj2,{where:{id:obj2.id}});
    var role=await this.model.findOne({where:{id:obj2.id}});
    await role.setProducts(obj2.products);
    return role;
  }
  async preCreate(u){
    if(u.products){
      var products=await this.db.models.product.findAll({where:{id:{[this.db.Op.in]:u.products}}});
      u.products=products;
    }
    return u;
  }
  async create(u,t){
      var self=this;
      var u2= await this.preCreate(u);
      if(t){
         var role= await this.model.create(u2,{transaction: t});
         if(u2.products && u2.products.length>0){
              await role.setProducts(u2.products,{transaction: t});
         }
         return role;
      }else{
        var role= await this.model.create(u2);
        if(u2.products && u2.products.length>0){
             await role.setProducts(u2.products);
        }
        return role;
      }
  }
}
module.exports=RoleDao;
