<?
class user extends base{
  public $type=array(1=>"新会员",2=>"学员",3=>"班主任");
  public $status=array(1=>"正常",2=>"禁用");
  public $subscribe_status=array(1=>"已关注",2=>"未关注");

/**
 * [delts 微信呢称特殊字符]
 * @Author   huangxiaojian
 * @DateTime 2022-02-15T21:17:45+0800
 * @param    [type]                   $nickName [description]
 * @return   [type]                             [description]
 */
function delSpecial($nickName){
    return preg_replace("/[\x{1F600}-\x{1F64F}\x{1F300}-\x{1F5FF}\x{1F680}-\x{1F6FF}\x{2600}-\x{26FF}\x{2700}-\x{27BF}]/u","",$nickName);
}
 function hpywy(){
        if (empty($_POST['tjr'])){
           json(1,"获取不到推荐人");
        }
        $ids=explode(",",$_REQUEST['ids']);
         foreach ($ids as $key => $value) {
             db()->update("user",array("tjr"=>$_POST['tjr']),"id=$value");
        }

        json(0,"批量修改成功");

 }
 function bdStudent(){
    $data=db()->select("user","*","token='".$this->token."'");
    if (empty($data)){
       json(1,"获取用户异常");
    }
    $realname=$_POST['realname'];
    $idnumber=$_POST['idnumber'];
    $mobile=$_POST['mobile'];
    $students=db()->select_all("student","*","(title='$realname' and idnumber='$idnumber') or (title='$realname' and mobile='$mobile')");
    if (count($student)>1){
       json(1,"同样的姓名以及身份证后四位查询到有多条记录，请联系管理员处理");
    }else if (count($students)==1){
        $student=$students[0];
        if ($student){
          $student['realname']=$student['title'];
          $student['type']=2;
          unset($student['id']);
          unset($student['sort']);
          unset($student['addtime']);
          unset($student['title']);
          unset($student['lastupdatetime']);

          db()->update("user",$student,"id=".$data['id']);
          json(0);
       }
    }else{
      $student['mobile']=$mobile;
      $student['title']=$realname;
      $student['idnumber']=$idnumber;
      db()->update("user",$student,"id=".$data['id']);
      json(1,"认证未成功,没有找到相关学员");
    }

 }
//添加会员
   function wxLogin(){
        $unionid=$_POST['unionid'];
       
        $user=db()->select("user","*","unionid='$unionid'");
        if (empty($user)){
            $data['regtime']=date("Y-m-d H:i:s",time());
            $data['ddusername']="xcx_".time();
            $data['mobile']=$mobile;
            $data['ddpassword']=md5("112233");
            $data['unionid']=$unionid;
            $data['openid']=$openid;
            $data['avatarUrl']=$_POST['avatarUrl'];
            $data['nickName']=$this->delSpecial($_POST['nickName']);
            $data['openid']=$openid;
            $data['token']=md5(time());
            $data['subscribe']=2;
            $id=db()->insert("user",$data);
            if (empty($id)){
               json(1,"添加异常");
            }
              json(0,"111",$data['token']);
        }else{
              $data['avatarUrl']=$_POST['avatarUrl'];
              $data['nickName']=$this->delSpecial($_POST['nickName']);
              db()->update("user",$data,"id=".$user['id']);

             json(0,"111",$user['token']);
        }
        
     
      $id=db()->select("user","id","openid='".$data['openid']."'");
      if ($id>0){
          db()->update("user",$data,"id=$id");
      }else{

        $id=db()->insert("user",$data);
      }
      $user=db()->get_table("user",$id);

      json(0,"",$user);
  }


function ywy($kou=0){
 
    $data= db()->select_2_field("user","id,realname as title","type=3");
    if ($kou==1){
       $data[99999]="无班主任";
    }

    return $data;
}
 function ewm(){



   $uid=$this->uid;
   $filepath="upload/ewm/$uid.jpg";
  
   if (!file_exists($filepath)){
      tgewm($uid,2);
   }
   json(0,"二维码显示成功",xcx_img($filepath));
 }
 function testadd(){
    $str='a:8:{s:7:"regtime";s:19:"2022-02-25 10:51:57";s:10:"ddusername";s:14:"gzh_1645757517";s:10:"ddpassword";s:32:"d0970714757783e6cf17b26fb8e2298f";s:7:"unionid";s:28:"oJ_4J61Hk-tdmGE3T0YKxchma2dg";s:10:"gzh_openid";s:28:"o7nBP6VQo1U3Fi-wfsIfJxaZH23M";s:5:"token";s:32:"e9a37f99ae01b0f42c136e735f5fd5d3";s:9:"subscribe";i:1;s:3:"tjr";s:2:"29";}';
    $data=unserialize($str);

    db()->insert("user",$data,1,1);
 }
  function subscribe($info=[],$param=0){
       // $str='{"subscribe":1,"openid":"o7nBP6YDMPSxcsfHCcZBu2Ji4ImI","nickname":"\u9ec4\u5c0f\u5efa","sex":0,"language":"zh_CN","city":"","province":"","country":"","headimgurl":"http:\/\/thirdwx.qlogo.cn\/mmopen\/CH8w50fycLjN42RUI7jzsffpVJA8a8nWUu7icv6vkrd6zGr8WcLJCUcVssXLdvtDNhYdDRVyH5S82WnUpRKzbH1Rmp59RDeyu\/132","subscribe_time":1637375094,"unionid":"oJ_4J624QVg_hCZy3o2QcSzkGFos","remark":"","groupid":0,"tagid_list":[],"subscribe_scene":"ADD_SCENE_QR_CODE","qr_scene":0,"qr_scene_str":""}';
       // $info=json_decode($str,true);
      //$info=json_decode($str,true);
      
       $user_id=db()->select("user","id","unionid='".$info['unionid']."'");
     
       if (empty($user_id)){
                      
            $data['regtime']=date("Y-m-d H:i:s",time());
            $data['ddusername']="gzh_".time();
            $data['ddpassword']=md5("112233");
            $data['unionid']=$info['unionid'];
            $data['gzh_openid']=$info['openid'];
            $data['token']=md5(time());
            $data['subscribe']=1;
           // $data['avatarUrl']=$info['headimgurl'];
            //$data['nickName']=$info['nickname'];
            if ($param>0){
                $data['tjr']=$param;
            }
            $id=db()->insert("user",$data);
            if (empty($id)){
                file_put_contents("error.txt", serialize($data).PHP_EOL, FILE_APPEND);
                throw new Exception("添加用户异常");
            }
        }else{
             $data['subscribe']=1;           
             $res=db()->update("user",$data,"unionid='".$info['unionid']."'");
             if ($res==false){
                  file_put_contents("error_update.txt", serialize($data).PHP_EOL, FILE_APPEND);
                  throw new Exception("更新用户异常");
             }

         }
     

  }


   function unsubscribe($openid){
        

      $user_id=db()->select("user","id","gzh_openid='".$openid."'");

      if ($user_id>0){
         
          $data['subscribe']=2;           
          db()->update("user",$data,"id=".$user_id);

      }

   }


  /**
   * [login 手机授权登录]
   * @Author   huangxiaojian
   * @DateTime 2021-11-09T19:43:11+0800
   * @param    string                   $unionid [description]
   * @param    string                   $mobile  [description]
   * @return   [type]                            [description]
   */
  function login($unionid="oJ_4J624QVg_hCZy3o2QcSzkGFos",$openid="oHyWI4gZJ9NUarsBnqsD1orUW43A",$mobile="18558752805"){
     

     file_put_contents("cc.txt", $unionid."__".$openid);
    
     $user=db()->select("user","*","unionid='$unionid'");


     $student=db()->select("student","code,school,major,learning_center,cheng,idnumber,username,pwd,level,title as realname,mobile,xl,idnumber,cheng","mobile='$mobile'");

     if (empty($user)){
       if ($student){
           $data=$student;
           $data['type']=2;
       }
           
        $data['regtime']=date("Y-m-d H:i:s",time());
        $data['ddusername']="xcx_".time();
        $data['mobile']=$mobile;
        $data['ddpassword']=md5("112233");
        $data['unionid']=$unionid;
        $data['openid']=$openid;
        $data['token']=md5(time());
        $data['subscribe']=2;
        $id=db()->insert("user",$data);
        if (empty($id)){
           json(1,"添加异常");
        }
     }else{
         
         if ($student){
             $data=$student;
             $data['type']=2;
         }else{
              $data['mobile']=$mobile;
         }
        $id=$user['id'];
        $data['unionid']=$unionid;
        $data['openid']=$openid;
   
        $res=db()->update("user",$data,"id=".$user['id']);
        if (!$res){
           json(1,"更新用户数据异常");
        }
     }
     $token=db()->get_field("user",$id,"token");
     json(0,"111",$token);
  }

  
 /**
  * [updateinfo 更改会员中心的info用户信息]
  * @Author   huangxiaojian
  * @DateTime 2021-09-18T11:57:09+0800
  * @return   [type]                   [description]
  */
 function updateinfo(){
    $_POST['nickName']=$this->delSpecial($_POST['nickName']);
    db()->update("user",$_POST,"id=".$this->uid);
    $data=db()->get_table("user",$id);
    json(0,"",$data);
 }
 /**
  * [view 个人通读录]
  * @Author   huangxiaojian
  * @DateTime 2021-09-17T17:03:16+0800
  * @return   [type]                   [description]
  */
 function view(){
    //先学员列表中获取
    $this->update_student($this->token);
    $data=db()->select("user","*","token='".$this->token."'");
    $data['typename']=$this->type[$data['type']];
    $data['realname']=$data['realname']?$data['realname']:$data['nickName'];
    json(0,"",$data);
 }

 function update_student($token){
      
      $data=db()->select("user","*","token='".$this->token."'");
  
      if ($data['type']==1 and !empty($data['mobile'])){
           $mobile=$data['mobile'];
           $student=db()->select("student","code,school,major,learning_center,cheng,idnumber,username,pwd,level,title as realname,mobile,xl,idnumber,cheng","mobile='$mobile'");

           if ($student){
               db()->update("user",$student,"id=".$data['id']);
           }

      }



 }

 function search_nickname(){

    $q=$_REQUEST['q'];
    $rows=db()->select_all("user","nickName as title","nickName like '%$q%' limit 0,10");
      $html="";
    foreach ($rows as $key => $value) {
      $html.="<p  class='scompany'>".$value['title']."</p>";
    }
    $result['html']=$html;
    echo dd_json_encode($result);exit();
 }

 function openid(){
   $data=db()->select("user","*","openid='".$_POST['openid']."'");
   $data['avatarUrl']=xcx_img($data['avatarUrl']);
   json(0,"",$data);
 }
 function realname($id){

    return db()->get_field("user",$id,"realname");
  }
  function nickname($id){

    return db()->get_field("user",$id,"nickName");
  }
 /**
  * [updatestatus 批量更改状态]
  * @Author   huangxiaojian
  * @DateTime 2021-09-15T16:19:08+0800
  * @return   [type]                   [description]
  */
 function updatestatus(){
    
      $temp=explode(",", $_POST['ids']);
      foreach ($temp as $key => $value) {
          db()->update("user",array("status"=>$_POST['status']),"id=$value");
      }
      json(0);

 }
  function updateuser(){
   
   if ($this->user['subscribe']==2){
      json(1,"请先关注公众号");
   }

    db()->update("user",$_POST,"id=".$this->uid);
    $user=db()->get_table("user",$id);
    json(0,"更新成功",$user);
  }
 function login1(){
   if (limit_ip('user_limit_ip')) {
      $result['msg']=('你的IP已经被禁用');
      echo dd_json_encode($result);exit();
    }    
   
   $username = trim($_POST['username']);
   $password = trim($_POST['password']);
   $remember = 1;
   $md5pwd = md5($password);
   $username_pass = reg_name($username, 3, 30, $shield_arr);
   if ($username_pass == -1) {
      $result['msg']=('用户名不合法');
       echo dd_json_encode($result);exit();
   } elseif ($username_pass == -2) {
      $result['msg']=('包含非法词汇');
       echo dd_json_encode($result);exit();
   } 
   $password_pass = reg_password($password);
   if ($password_pass == 0) {
      $result['msg']=('密码格式错误');
       echo dd_json_encode($result);exit();
   } 

   $dduser = db() -> select('user', '*', "(ddusername='" . $username . "' or email='" . $username . "') and ddpassword='" . $md5pwd . "' and del=0");
   $uid = $dduser['id'];
   
   if ($uid > 0) { // 如果会员存在
            $id = $dduser['id'];
            $username = $dduser['ddusername'];
            $email = $dduser['email'];
            $status = $dduser['status'];
            if ( $status ==2) {
                json(1,"你的账号已被禁用");
            } 
            if ($remember == 1) {
               $life = 3600 * 24 * 100;
            } else {
               $life = '';
            } 
            user_login($uid, $md5pwd, $life); //登陆状态
            $set_con_arr = array(array('f' => 'ddpassword', 'v' => $md5pwd), array('f' => 'lastlogintime', 'v' => SJ), array('f' => 'loginnum', 'e' => '+', 'v' => 1), array('f' => 'logip', 'e' => '=', 'v' => get_client_ip()));
            db() -> update('user', $set_con_arr, 'id="' . $uid . '"');
         
         } else {
             json(1,"账号密码错误");
         } 
       $temp=strtotime($dduser['lastlogintime']);
       $dduser['lastlogintime']=date("Y-m-d",$temp);
       $dduser['roletext']=db()->get_field("role",$dduser['role']);
       $rfield=role_field($dduser['role']);
       if (empty($rfield)){
          json(1,"角色异常");
       }
       $dduser['rfield']=$rfield;
      json(0,"登录成功",$dduser);
 }

 //获取所有区域的会员
function users2($fid=1,$did=0){

   $did=$did?$did:$this->dduser['id'];

   $ins=$this->sons($did,1);
   $users=db()->select_all("user","id,ddusername,realname,role","role in ($fid)  and status=1 and  id in ($ins)   order by id desc");
     foreach ($users as $k=>$vo){
       $rolename=$this->role->get_role($vo['role']);
       $temp[$vo['id']]=$vo['realname']."[".$rolename['title']."]";
    } 
  return $temp;
}






 /**
  * [get_role 根据ID获取角色ID]
  * @Author   huangxiaojian
  * @DateTime 2021-04-16T22:40:59+0800
  * @return   [type]                   [description]
  */
 function get_role($uid){

      return db()->get_field("user",$uid,"role");
 }

/**
 * [user_list 根据不同角色获取显示用户]
 * @Author   huangxiaojian
 * @DateTime 2021-04-03T12:13:22+0800
 * @param    [type]                   $where [搜索条件]
 * @param    [type]                   $uid   [用户ID]
 * @return   [type]                          [用户列表]
 */
  function user_list(){

      $where="";
      if ($_REQUEST['ddusername']){
         $where.=" and ddusername like '%".$_REQUEST['ddusername']."%'";
      }
      if ($_REQUEST['realname']){
         $where.=" and realname like '%".$_REQUEST['realname']."%'";
      }
    $ins=$this->sons($this->dduser['id'],0,"",0);
    $id=$this->dduser['id'];
    $users=db()->select_all("user","*","id in ($ins) $where");
     foreach ($users as $k=>$vo){
             if ($vo['pid']==$id){
               $users[$k]['pid']=0;
             }

             if (!empty($where))
                 $users[$k]['pid']=0;
           $role11=$this->role->get_role($vo['role']);
           $users[$k]['rolename']=$role11['title'];
     }
    return $users;
  }

/**
 * [fathers 根据当前用户ID 一般指管理员或区域管理 获取同一角色如项目主管列表]
 * @Author   huangxiaojian
 * @DateTime 2021-05-04T22:08:22+0800
 * @param    [type]                   $role [description]
 * @return   [type]                         [description]
 */
  function fathers($role){
       $id=$this->dduser['id'];
       $role=$this->frole($role);

       $ins=$this->sons($this->dduser['id'],0,$role);

       //如果选择的角色如果与当前登录用户是一致的则则显示登入用户，目前情况是管理员
       //添加用户的时候，选择区域管理员要用到下面这个处理
       if ($this->dduser['role']==$role){
           $ins=empty($ins)?$id:$ins.",".$id;
           $where=" and id in ($ins)";
       }else{
          $where=" and id in ($ins)";
       }
  
       $users=db()->select_all("user","*","role=$role $where");
        foreach ($users as $k=>$vo){
          $rolename=$this->role->get_role($vo['role']);
          $users[$k]['title']=$vo['realname']."[".$rolename['title']."]";
       }  
       return $users;

  }
/**
 * @Author   huangxiaojian
 * @DateTime 2021-04-03T11:57:58+0800
 * @param    [type]                   $uid [会员ID]
 * @return   [type]                        [description]
 */
  function select_role($uid){
  
    $role=db()->get_field("user",$uid,"role");
    if ($role==GLY)
        $res=db()->select_2_field("role","id,title","`status`=1 and id not in (1,".GLY.")");
   if ($role==HHR)
        $res=db()->select_2_field("role","id,title","`status`=1 and id  in (".YG.")");
    return $res;

}
/**
 * [equal 获取当前ID父类IDs]
 * @Author   huangxiaojian
 * @DateTime 2021-06-06T18:02:36+0800
 * @param    [type]                   $uid    [description]
 * @param    integer                  $self   [description]
 * @param    string                   $role   [description]
 * @param    integer                  $status [description]
 * @return   [type]                           [description]
 */
function equal($uid,$self=1,$role="",$status=1){
    if (!empty($role))
        $where=" and role in ($role)";
    if ($status==1){
       $where.=" and status=1";
    }
    $pid=db()->select("user","pid","id=$uid $where");
     while ($pid>0) {
      $data[]=$pid;
      $pid=db()->select("user","pid","id=$pid $where");
    
     } 
     if ($self==1){
         $data[]=$uid;
     }
     return implode(",", $data);
}
/**
 * [sons 根据父ID显示下级ID包含他自己]
 * @Author   huangxiaojian
 * @DateTime 2021-04-13T11:52:18+0800
 * @return   [type]                   [description]
 */
function sons($uid,$self=1,$role="",$status=1){


    $data=db()->select_all("user","id,pid","1=1 $where");
     
    $res=sons($data,$uid);
   
    foreach ($res as $key => $value) {
        $user=db()->get_table("user",$value);
        if (!empty($role)){
            $role=explode(",", $role);
            if (!in_array($user['role'],$role)){

               unset($res[$key]);
               counitue;
            }
                         
        }
         if ($status==1 and $user['status']==2){
             unset($res[$key]);
             counitue;
        }
    }

    if ($self==1)
        $res[]=$uid;
    return implode(",", $res);
}

/**
 * [frole 通过一个角色获取上级的角色]
 * @Author   huangxiaojian
 * @DateTime 2021-05-04T22:23:54+0800
 * @param    [type]                   $role [description]
 * @return   [type]                         [description]
 */
function frole($role){
    
    if ($role==XMFZR)
        return GLY;
    if ($role==DGL)
        return GLY;
    if ($role==YGL)
        return GLY;
    if ($role==CW)
        return GLY;
    if ($role==YS)
        return YGL;
    if ($role==DC)
        return DGL;
      if ($role==CG)
        return GLY;
}

function xls($where){
    $list=db()->select_all("user","*","1=1 $where");
    foreach ($list as $key => $value) {
        $list[$key]['subscribetext']=$value['subscribe']==1?"已关注":"未关注";
        $list[$key]['statustext']=$this->status[$value['status']];
        $list[$key]['typename']=$this->type[$value['type']];
        $list[$key]['code']=$value['code']?$value['code']."`":"";
        $list[$key]['ywyname']=$value['tjr']?$this->get_ywyname($value['tjr']):"";
    }
   
     $keys=array(
      array("field"=>"ywyname","width"=>12,"title"=>"班主任"),
      array("field"=>"typename","width"=>12,"title"=>"角色"),
      array("field"=>"ddusername","width"=>25,"title"=>"账号"),
      array("field"=>"regtime","width"=>25,"title"=>"注册时间"),
      array("field"=>"nickName","width"=>15,"title"=>"微信呢称"),
       array("field"=>"realname","width"=>10,"title"=>"姓名"),
      array("field"=>"mobile","width"=>13,"title"=>"手机"),
      array("field"=>"code","width"=>20,"title"=>"学号"),
       array("field"=>"school","width"=>15,"title"=>"报考学校"),
       array("field"=>"major","width"=>25,"title"=>"报考专业"),
    );
      $file_name=exportExcel($list,$keys,"会员数据导出",10000);
      json(0,"",$file_name);
}

//根据底下用户获取区域用户ID
function areaid($id){
  //总管理员 的ID返为福州区域
  if ($id==1){
     return 3699;
  }
  $pid=db()->select('user','pid','id='.$id);
  if ($pid==1)
      return $id;
  while ($pid!=1){
    $userid=$pid;
    $pid=db()->select('user','pid','id='.$pid);
  }
  return $userid;
  }

/**
 * [post 添加或编辑员工的post处理再返回]
 * @Author   huangxiaojian
 * @DateTime 2021-04-03T16:00:05+0800
 * @param    [type]                   $post [description]
 * @return   [type]                         [description]
 */
function post(){
   
     if ($_POST['act111']=="hpywy"){
         $this->hpywy();exit();
     }
 
}

function listwhere($where){

   if ($_POST['ddate']){
     
      $_POST["sdate"]=$_POST['ddateMin'];
      $_POST["edate"]=$_POST['ddateMax'];
    }
    if ($_POST["sdate"]){
       $where.=" and regtime>='".$_POST["sdate"]."'";
  }
  if ($_POST["edate"]){
      $edate=strtotime($_POST["edate"]);
      $edate=$edate+86400;
      $_POST["edate"]=date("Y-m-d",$edate);
       $where.=" and regtime<'".$_POST["edate"]."'";
  }
  if ($_POST["tg"]==1 and $this->uid){
          $where.=' and tjr='.$this->uid;
  }

  if ($_POST["status"]){
          $where.=' and status='.$_POST["status"];
  }
  if ($_POST["tjr"]){
     if ($_POST["tjr"]==99999)
        $where.=' and tjr=0';
        else
        $where.=' and tjr='.$_POST["tjr"];
  }
  if ($_POST["type"]){
          $where.=' and type='.$_POST["type"];
  }
  if ($_POST["subscribe"]){
          $where.=' and subscribe='.$_POST["subscribe"];
  }
  if ($_POST["xcx"]){
       $where.=' and status=2';
  }
  if (!empty($_POST["realname"])){
       $where.=' and realname like "%'.$_POST["realname"].'%"';
  }
  if (!empty($_POST["mobile"])){
       $where.=' and mobile like "%'.$_POST["mobile"].'%"';
  }
  if (!empty($_POST["ddusername"])){
       $where.=' and ddusername like "%'.$_POST["ddusername"].'%"';
  }
  if ($_POST["nickName"]){
       $where.=' and nickName like "%'.$_POST["nickName"].'%"';
  }
  if ($_POST['xls']==1){
     $this->xls($where);
  }

  return $where;
}
function list($list){

   foreach ($list as $key => $value) {
     
     $list[$key]['subscribetext']=$value['subscribe']==1?"已关注":"未关注";
      $list[$key]['statustext']=$this->status[$value['status']];
       $list[$key]['typename']=$this->type[$value['type']];

       $list[$key]['ywyname']=$value['tjr']?$this->get_ywyname($value['tjr']):"";
      $list[$key]['rfile']=$value['avatarUrl']?showrfile($value['avatarUrl']):"";
   }

   return $list;
}
function get_ywyname($id){
   $title=db()->select("user","realname","id=$id");
   return $title;
  }

 function get_name($id){
   $title=db()->select("user","nickName","id=$id");
   return $title;
  }



    function del($ids){


        foreach ($ids as $key => $value) {
            $num=db()->count("user","tjr=".$value);
            if ($num>0){
                json(1,"有相关推广记录,不能删除");
            }
        }
   }
}
?>