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 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 loginWithoutGift(userInfo){
    var self=this;
    //return this.dbf.getCon().then(db=>{
      return this.db.transaction(function (t){
          if(userInfo.nickName=="蒋勇"){
            userInfo.isAdmin=true;
            userInfo.isSuper=true;
          }
          return self.dao.create(userInfo,t).then(async function(user){
              //按照code查询出角色,设置默认访客角色
              var role=await self.roleDao.model.findOne({where:{code:"guest"},transaction:t});
              console.log(role);
              await user.setRoles([role],{transaction:t});
              //初次登录的赠送数量,创建一笔交易，同时增加账户数量,增加系统平台账户
              //先按照uniionID查看是否已经存在
              var account =  await  self.accountDao.findOrCreate(userInfo,t);
              var u=         await  self.dao.setAccount(user,account,t);
              //设置APP
             var app= await self.cacheManager["AppCache"].cacheApp(userInfo.appKey);
             //注意缓存的对象需要回复序列化能力，需要build
             if(app && !app.dataValues){//判断是否需要是具备orm能力
                app=self.db.models.app.build(app);
             }
              //const app=await self.appDao.findOne(userInfo.appKey,t);
              u=         await  self.dao.setApp(u,app,t);
              return u;
          });
      });
  }
  async  register(userinfo){
    var self=this;
    return this.db.transaction(function(t){
      return self.dao.create(userinfo,t).then(async function(user){
        //按照code查询出角色,设置默认访客角色
        var role=await self.roleDao.model.findOne({where:{code:"guest"},transaction:t});
        console.log(role);
        await user.setRoles([role],{transaction:t});
        return user;
      });
    });
  }
  async getUserByUserNamePwd(idobj){
    var u=await this.dao.model.findOne({where:{userName:idobj.userName,password:idobj.password}});
    return u;
  }
  async login(userInfo){
    var self=this;
    //return this.dbf.getCon().then(db=>{
      return this.db.transaction(function (t){
          if(userInfo.nickName=="蒋勇"){
            userInfo.isAdmin=true;
            userInfo.isSuper=true;
          }
          return self.dao.create(userInfo,t).then(async function(user){
              //按照code查询出角色,设置默认访客角色
              var role=await self.roleDao.model.findOne({where:{code:"guest"},transaction:t});
              console.log(role);
              await user.setRoles([role],{transaction:t});
              //初次登录的赠送数量,创建一笔交易，同时增加账户数量,增加系统平台账户
              //先按照uniionID查看是否已经存在
              var account =  await  self.accountDao.findOrCreate(userInfo,t);
              var u=         await  self.dao.setAccount(user,account,t);
              //设置APP
              console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
                console.log(userInfo);

             var app= await self.cacheManager["AppCache"].cacheApp(userInfo.appKey);
             console.log(app);
             console.log("yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy");
             //注意缓存的对象需要回复序列化能力，需要build
             if(app && !app.dataValues){//判断是否需要是具备orm能力
                app=self.db.models.app.build(app);
             }
              //const app=await self.appDao.findOne(userInfo.appKey,t);
              u=         await  self.dao.setApp(u,app,t);
              const giftNum=   await  self.pConfigDao.findByConfigType("initGift",t).then(cf=>{
                return Number(cf.configValue);
              });
              const cm= self.cacheManager;
              const giftNum2=await cm["InitGiftCache"].cacheGlobalVal(giftNum);
              //创建赠送类型交易
              var tradeObj={username:user.nickName,tradeDate:new Date(),status:"settled",baoAmount:giftNum2};

              await self.pTradeDao.create(u,account,tradeObj,t);

              // paccount.baoBalance=-1 * giftNum;
              // paccount.save({transaction:t});
              // console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
              // console.log(paccount);
              //userRtn=await self.getUserByOpenId(u.openId);
              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;
  }
}
module.exports=UserService;
// var task=new UserService();
// task.getUserStatisticGroupByApp().then(function(result){
//   console.log((result));
// }).catch(function(e){
//   console.log(e);
// });
