const system = require("../../system");
const Dao = require("../dao.base");
class UserDao extends Dao {
  constructor() {
    super(Dao.getModelName(UserDao));
    this.appDao = system.getObject("db.appDao");
    this.partnerinfoDao = system.getObject("db.partnerinfoDao");
  }
  async getAuths(userid) {
    var self = this;
    return this.model.findOne({
      where: { id: userid },
      include: [{ model: self.db.models.account, attributes: ["id", "isSuper", "referrerOnlyCode"] },
      {
        model: self.db.models.role, as: "Roles", attributes: ["id", "code"], include: [
          { model: self.db.models.product, as: "Products", attributes: ["id", "code"] }
        ]
      },
      ],
    });
  }
  async getUserByUsername(username, appkey, t) {
    var app = await this.appDao.findOne(appkey);
    var tUser = await this.model.findOne({
      where: { userName: username, app_id: app.id },
      include: [{ model: this.db.models.app, raw: true },
      // {model:this.db.models.partnerinfo,attributes:["id","user_id","app_id","userName","applyType","applyName","workPic","tagInfo","mobile","tel","applyProvince","applyCity",
      //                                               "applyArea","applyAddr","identityCardPic","identityCard","businessLicensePic","businessLicenseNum","entName","cardNo","realName"]},
      { model: this.db.models.account, attributes: ["id", "isSuper", "referrerOnlyCode"], raw: true },
      {
        model: this.db.models.role, as: "Roles", attributes: ["id", "code"], include: [
          { model: this.db.models.product, as: "Products", attributes: ["id", "code"], raw: true }
        ]
      },
      ]
    }, { transaction: t });
    // if(tUser!=null){
    //   tUser=tUser.get({plain:true});
    //   tUser.partnerinfo=await this.partnerinfoDao.model.findOne({where:{onlyCode:tUser.onlyCode},raw:true});
    // }
    return tUser;
  }
  async getUserByOpenId(popenid, appkey, t) {
    //new----fq
    var tUser = await this.model.findOne({
      where: { openId: popenid },
      attributes: ["id", "nickName", "openId", "unionId", "account_id", "app_id", "isAdmin",
        "userName", "onlyCode", "referrerOnlyCode", "mobile", "tm_company_id", "tm_copmpany_name"],
      include: [
        { model: this.db.models.app, attributes: ["id", "appid", "wxcode", "name", "homePage", "authPage", "logoUrl", "app_code"], raw: true },
        { model: this.db.models.account, attributes: ["id", "isSuper", "referrerOnlyCode"], raw: true },
        {
          model: this.db.models.role, as: "Roles", attributes: ["id", "code"], include: [
            { model: this.db.models.product, as: "Products", attributes: ["id", "code"], raw: true }
          ]
        },
      ]
    }, { transaction: t });
    return tUser;
    //old
    // var tUser = await this.model.findOne({
    //   where: { openId: popenid },
    //   include: [{ model: this.db.models.app, raw: true },
    //   { model: this.db.models.account, attributes: ["id", "isSuper", "referrerOnlyCode"], raw: true },
    //   {
    //     model: this.db.models.role, as: "Roles", attributes: ["id", "code"], include: [
    //       { model: this.db.models.product, as: "Products", attributes: ["id", "code"], raw: true }
    //     ]
    //   },
    //   ]
    // }, { transaction: t });
    // if (!tUser) {
    //   tUser = tUser.get({ plain: true });
    //   tUser.partnerinfo = await this.partnerinfoDao.model.findOne({ where: { onlyCode: tUser.onlyCode }, raw: true });
    // }
    // return tUser;
  }
  async setAccount(user, account, t) {
    var user = await user.setAccount(account, { transaction: t });
    return user;
  }
  async setApp(user, app, t) {
    //按照APPId,获取app对象
    var user = await user.setApp(app, { transaction: t });
    return user;
  }
  extraModelFilter() {
    //return {"key":"include","value":[{model:this.db.models.app,},{model:this.db.models.role,as:"Roles",attributes:["id","name"],joinTableAttributes:['created_at']}]};
    return { "key": "include", "value": [{ model: this.db.models.app, }, { model: this.db.models.role, as: "Roles", attributes: ["id", "name"] }] };
  }
  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;
      });
    }
  }

  //修改用户(user表)公司的唯一码
  async putUserCompanyOnlyCode(userId, company_only_code, result) {
    var customerObj = { companyOnlyCode: company_only_code };
    var putSqlWhere = { where: { id: userId } };
    this.updateByWhere(customerObj, putSqlWhere);
    return result;
  }

}
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);
    //   }
    //
    // })();
