const system=require("../../system");
const Dao=require("../dao.base");
class UserDao extends Dao{
  constructor(){
    super(Dao.getModelName(UserDao));
  }
  async getAuths(userid){
    var self=this;
    return this.model.findOne({
      where:{id:userid},
      include:[{model:self.db.models.role,as:"Roles",attributes:["id","code"],},
      ],
    });
  }
  async getUserByOpenId(popenid,appkey,t){
       var tUser=await this.model.findOne({
         where:{openId:popenid}, include:[
           {model:this.db.models.role,as:"Roles",attributes:["id","code"],include:[], raw:true},
          ], raw:true},{transaction:t});
     return tUser;
  }
  async signleUserByOpenId(popenid, appkey){
    var tUser=await this.model.findOne({where:{openId:popenid}, include:[], raw:true});
    return tUser;
  }
  async getById(id){
    return await this.model.findOne({where:{id:id}, include:[], raw:true});
  }

  extraModelFilter(qobj){
    var rolewhere = {};

    return {"key":"include","value":[{model:this.db.models.role,as:"Roles",attributes:["id","name"], where:rolewhere}]};
  }
  extraWhere(obj,w,qc,linkAttrs){
     if(obj.codepath && obj.codepath!=""){
      //  if(obj.codepath.indexOf("userarch")>0){//说明是应用管理员的查询
      //    console.log(obj);
      //     w["app_id"]=obj.appid;
      //  }
     }

     if(linkAttrs.length>0){
       var search=obj.search;
       var lnkKey=linkAttrs[0];
       var strq="$"+lnkKey.replace("~",".")+"$";
       w[strq]= {[this.db.Op.like]:"%"+search[lnkKey]+"%"};
      
     }
     return w;
  }
  async preUpdate(u){
    if(u.roles && u.roles.length>0){
      var roles=await this.db.models.role.findAll({where:{id:{[this.db.Op.in]:u.roles}}});
      console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
      console.log(roles);
      u.roles=roles
    }
    return u;
  }
  async update(obj){
    var obj2=await this.preUpdate(obj);
    console.log("update....................");
    console.log(obj2);
    await this.model.update(obj2,{where:{id:obj2.id}});
    var user=await this.model.findOne({where:{id:obj2.id}});
    user.setRoles(obj2.roles);
    return user;
  }
  async findAndCountAll(qobj,t){
    var users=await super.findAndCountAll(qobj,t);
    return users;
  }
  async preCreate(u){
    // var roles=await this.db.models.role.findAll({where:{id:{[this.db.Op.like]:u.roles}}});
    // console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    // console.log(roles);
    // console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    // u.roles=roles
    return u;
  }
  async create(u,t){
      var self=this;
      var u2=await this.preCreate(u);
      if(t){
        return this.model.create(u2,{transaction: t}).then(user=>{
          return user;
        });
      }else{
        return this.model.create(u2).then(user=>{
          return user;
        });
      }
  }

  async findMapByIds(ids) {
    var result = [];
    if(!ids || ids.length == 0) {
      return result;
    }

    var sql = "SELECT * FROM p_user where id IN (:ids) ";
    var list = await this.customQuery(sql, {ids:ids});
    if(!list || list.length == 0) {
      return result;
    }

    for(var item of list) {
      result["id_" + item.id] = item;
    }

    return result;
  }

  async getMyIds(userId) {
    var codeSql = [];
    codeSql.push("SELECT t1.code FROM p_role t1 ");
    codeSql.push("INNER JOIN `p_userrole` t2 ON t1.`id` = t2.`role_id`");
    codeSql.push("WHERE t2.`user_id` = :userId");
    codeSql.push("GROUP BY t1.id");
    var list = await this.customQuery(codeSql.join(" "), {userId:Number(userId)});
    if(!list || list.length == 0) {
      return [];
    }

    var userids = [userId];
    var codes = [];
    var qcodes = []; // 构建查询角色参数
    for(var item of list) {
      codes.push(item.code);
    }

    // 支持
    userids = userids.concat(await this.handleUserIds(codes, "zcgl", "zczy"));
    // 大客户
    userids = userids.concat(await this.handleUserIds(codes, "dkhgl", "dkhzy"));
    // 渠道
    userids = userids.concat(await this.handleUserIds(codes, "qdgl", "qdzy"));
    // 拓展
    userids = userids.concat(await this.handleUserIds(codes, "tzgl", "tzzy"));

    if(codes.indexOf("qdgl") > -1 || codes.indexOf("qdzy") > -1) {
      userids = userids.concat(await this.getPartnerUserIds());
    }
    // // 自营
    // userids = userids.concat(await this.handleUserIds(codes, "zygl", "zyzy"));
    // 平台
    userids = userids.concat(await this.handleUserIds(codes, "ptgl", "ptzy"));
    if(codes.indexOf("ptgl") > -1 || codes.indexOf("ptzy") > -1) {
      userids = userids.concat(await this.getPartnerUserIds());
    }
    return userids;
  }

  async getPartnerUserIds() {
    var rs = [];

    var sql = "SELECT id FROM p_user WHERE isPartner = 1";
    var list = await this.customQuery(sql);
    if(!list || list.length == 0) {
      return rs;
    }

    for(var item of list) {
      rs.push(item.id);
    }
    return rs;
  }

  async handleUserIds(codes, glcode, zycode) {
    var rs = [];
    if(!glcode || !zycode) {
      return rs;
    }
    if(codes.indexOf(glcode) == -1) {
      return rs;
    }
    // 查所有专员code对应的用户id
    var sql = [];
    sql.push("SELECT t2.user_id FROM p_role t1 ");
    sql.push("INNER JOIN p_userrole t2 ON t1.id = t2.role_id");
    sql.push("WHERE t1.code = :code");
    sql.push("GROUP BY t2.user_id");

    var list = await this.customQuery(sql.join(" "), {code: zycode});
    if(!list || list.length == 0) {
      return rs;
    }

    for(var item of list) {
      rs.push(item.user_id);
    }
    return rs;
  }
}
module.exports=UserDao;
    // var u=new UserDao();
    // var roledao=system.getObject("db.roleDao");
    // (async ()=>{
    //   var users=await u.model.findAll({where:{app_id:1}});
    //   var role=await roledao.model.findOne({where:{code:"guest"}});
    //   console.log(role);
    //   for(var i=0;i<users.length;i++){
    //     await users[i].setRoles([role]);
    //     console.log(i);
    //   }
    //
    // })();
