const system = require("../../system");
const ServiceBase = require("../sve.base")
const settings = require("../../../config/settings")
const uiconfig = system.getUiConfig2(settings.wxconfig.appId);
class UserService extends ServiceBase {
  constructor() {
    super(ServiceBase.getDaoName(UserService));
    this.pConfigDao = system.getObject("db.pconfigDao");
    this.roleDao = system.getObject("db.roleDao");
  }
  async aftercreate(result, u, t) {
    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);
      if (roles && roles.length > 0) {
        await result.setRoles(roles, { transaction: t });
      } else {
        var role = await this.roleDao.model.findOne({ where: { code: "guest", company_id: result.company_id }, transaction: t });
        var themename=u.themename;
        if(themename && themename=="policy"){
          role = await self.roleDao.model.findOne({ where: { code: "policy" }, transaction: t });
        }
        if (role) {
          await result.setRoles([role], { transaction: t });
        }
      }
    } 
    return result;
  }
  async create(qobj) {
    var self = this;
    return this.db.transaction(async function (t) {
      var result = await self.dao.create(qobj, t);
      await self.aftercreate(result, qobj, t);
      return result;
    });
  }
  async getUserByOpenId(popenid, appkey) {
    var self = this;
    return this.db.transaction(function (t) {
      return self.dao.getUserByOpenId(popenid, appkey, t);
    });
  }
  async getUidStr(len, radix) {
    var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
    var uuid = [], i;
    radix = radix || chars.length;
    if (len) {
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
      var r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }
    return uuid.join('');
  }

  //根据擅长查询user
  async getMsgsUsersList(obj) {
    var nickName = null;
    var tagInfo = null;
    if (obj.search != null) {
      nickName = obj.search.nickName == null ? "" : obj.search.nickName;
      tagInfo = obj.search.tagInfo == null ? "" : obj.search.tagInfo;
    }
    var pageSize = Number(obj.pageInfo.pageSize);
    var from = obj.pageInfo.pageNo == 1 ? 0 : Number((obj.pageInfo.pageNo - 1) * pageSize);
    var nickNamewhere = "and user.nickName like '%" + nickName + "%'";
    var tagInfowhere = "and partnerInfo.tagInfo like '%" + tagInfo + "%'";
    var sql = "SELECT user.id,user.app_id,user.nickName,user.headUrl"
      + " FROM `p_user` AS user left join `h_partner_info` AS partnerInfo"
      + " on user.id=partnerInfo.user_id WHERE 1=1 ";
    if (nickName != '' && nickName != null) {
      sql += nickNamewhere;
    }
    if (tagInfo != '' && tagInfo != null) {
      sql += tagInfowhere;
    }
    sql += " LIMIT " + pageSize + " OFFSET " + from;
    var tmpResult = await this.dao.customQuery(sql);
    var tmpi = tmpResult.length;
    return { rows: tmpResult, total: tmpi };
  }

  //获取角色，角色产品ids
  async getAuths(userid) {
    return this.dao.getAuths(userid);
  }

  async  register(userinfo,theme) {
    var self = this;
    return this.db.transaction(function (t) {
      return self.dao.create(userinfo, t).then(async function (user) {
        //按照code查询出角色,设置默认访客角色
        if(user.company_id!=1){
          var role = await self.roleDao.model.findOne({ where: { code: "guest" }, transaction: t });
          if(theme && theme=="policy"){
            role = await self.roleDao.model.findOne({ where: { code: "policy" }, transaction: t });
          }
          console.log(role);
          await user.setRoles([role], { transaction: t });
        }
        return user;
      });
    });
  }

  async getComanyAdminUser(companyid){
    var u = await this.dao.model.findOne({
      where: { isAdmin: true, company_id: companyid },
      include: [
        { model: this.db.models.role, as: "Roles", attributes: ["id", "code"] },
        {
          model: this.db.models.company, as: "company",
          attributes: ["id", "domainname", "companyType", "siteTheme", "onlyCode"]
        }
      ],
    });
    return u;
  }
  async getComanyUserById(userid,companyid){
    var u = await this.dao.model.findOne({
      where: { id: userid, company_id: companyid },
      include: [
        { model: this.db.models.role, as: "Roles", attributes: ["id", "code"] },
        {
          model: this.db.models.company, as: "company",
          attributes: ["id", "domainname", "companyType", "siteTheme", "onlyCode"]
        }
      ],
    });
    return u;
  }

  async getUserByMobile(obj) {
    var u = await this.dao.model.findOne({
      where: { mobile: obj.mobile, isEnabled: true, company_id: obj.cid },
      include: [
        { model: this.db.models.role, as: "Roles", attributes: ["id", "code"] },
        {
          model: this.db.models.company, as: "company",
          attributes: ["id", "domainname", "companyType", "siteTheme", "onlyCode"]
        }
      ],
    });
    return u;
  }
  async getUserByUserMobilePwd(idobj) {
    var u = await this.dao.model.findOne({
      where: { mobile: idobj.mobile, password: idobj.password, isEnabled: true, company_id: idobj.cid },
      include: [
        { model: this.db.models.role, as: "Roles", attributes: ["id", "code"] },
        {
          model: this.db.models.company, as: "company",
          attributes: ["id", "domainname", "companyType", "siteTheme", "onlyCode"]
        }
      ],
    }
    );
    return u;
  }
  async getUserByUserNamePwd(idobj) {
    var u = await this.dao.model.findOne({
      where: { userName: idobj.userName, password: idobj.password, isEnabled: true, company_id: idobj.cid },
      include: [
        { model: this.db.models.role, as: "Roles", attributes: ["id", "code"] },
        {
          model: this.db.models.company, as: "company",
          attributes: ["id", "domainname", "companyType", "siteTheme", "onlyCode"]
        }
      ],
    }
    );
    return u;
  }

  async getUserStatisticGroupByApp() {
    var sql = "SELECT count(`user`.id) value,`user`.app_id appid,app.NAME name FROM `p_user` AS USER "
      + "LEFT JOIN p_app AS app ON app.id = `user`.app_id "
      + "WHERE `user`.app_id NOT IN(11,13,15) "
      + "GROUP BY `user`.app_id, app.`name`";
    console.log(sql);
    var result = await this.dao.customQuery(sql);
    return result;
  }

  async checkUserLogin(){//验证用户是否登录
    

  }

  /**
   * 修改用户基本信息
   * @param nickName 昵称, headUrl 头像, sex 性别,  email 邮箱
   */
  async editUserBaseInfo(obj){
    var user = obj.user;
    if(!user || !user.id){
      return {code:-100,msg:"用户未登录"};
    }
    var updateObj = {id:user.id};
    if(obj.nickName){
      updateObj["nickName"] = obj.nickName;
    }
    if(obj.headUrl){
      updateObj["headUrl"] = obj.headUrl;
    }
    if(obj.sex){
      updateObj["sex"] = obj.sex;
    }
    if(obj.email){
      updateObj["email"] = obj.email;
    }
    if(!obj.nickName && !obj.headUrl && !obj.sex && !obj.email){
      return {code:-101,msg:"不存在修改项"};
    }
    await this.dao.update(updateObj);
    var user = await this.dao.model.findOne({
      where:{id:user.id},
      attributes: ["userName", "id", "nickName", "headUrl", "mobile","company_id","bindOpenId"],
      raw:true
    });
    return {code:1,data:user};
  }
}
module.exports = UserService;
// var task=new UserService();
// task.getUserStatisticGroupByApp().then(function(result){
//   console.log((result));
// }).catch(function(e){
//   console.log(e);
// });
