<?php
namespace wstmart\common\model;
use Think\Db;
/**
 * ============================================================================
 * 用户类
 */
class Users extends Base{
    /**
     * 我家朋友
     */
    public function myFriend($userId){
        $rs = [];
        $pid = Db::name('user_trees')->where(['uid'=>$userId])->value('pid');
        $rs['pInfo'] = '';
        if($pid){
            $pInfo = getUserInfo(['userId'=>$pid],'trueName,userPhone,userLevel,userStatus');
            if($pInfo)
                $rs['pInfo'] = ['trueName'=>$pInfo['trueName'],'userPhone'=>$pInfo['userPhone'],'userLevel'=>$this->getUserLevelName($pInfo['userLevel']),'userStatus'=>$this->getUserStatusName($pInfo['userStatus'])];
            else
                $rs['pInfo'] = ['trueName'=>'无上级账号','userPhone'=>'','userLevel'=>'','userStatus'=>$this->getUserStatusName($pInfo['userStatus'])];
        }
        $rs['lockUserCount'] = Db::name('users u')
            ->join('user_trees t','u.userId=t.uid')
            ->where(['t.pid'=>$userId,'u.dataFlag'=>1,'u.userStatus'=>0])
            ->count();
        $rs['userCount'] = Db::name('users u')
            ->join('user_trees t','u.userId=t.uid')
            ->where(['t.pid'=>$userId,'u.dataFlag'=>1,'u.userStatus'=>1,'u.userLevel'=>0])
            ->count();

        $rs['shopCount'] = Db::name('users u')
            ->join('user_trees t','u.userId=t.uid')
            ->where(['t.pid'=>$userId,'u.dataFlag'=>1,'u.userStatus'=>1,'u.userLevel'=>1])
            ->count();
        $rs['storeCount'] = Db::name('users u')
            ->join('user_trees t','u.userId=t.uid')
            ->where(['t.pid'=>$userId,'u.dataFlag'=>1,'u.userStatus'=>1,'u.userLevel'=>2])
            ->count();
        $rs['mallCount'] = Db::name('users u')
            ->join('user_trees t','u.userId=t.uid')
            ->where(['t.pid'=>$userId,'u.dataFlag'=>1,'u.userStatus'=>1,'u.userLevel'=>3])
            ->count();
        $rs['marketCount'] = Db::name('users u')
            ->join('user_trees t','u.userId=t.uid')
            ->where(['t.pid'=>$userId,'u.dataFlag'=>1,'u.userStatus'=>1,'u.userLevel'=>4])
            ->count();
        return $rs;
    }
     /**
     * 分配券值
     * @return [type] [description]
     */
     public function distributionInvestmentMoney(){
        $data = input('post.');
        $userId = $data['userId'];
        $type = (int)$data['type'];
        $typeName = ['1'=>'productNum','2'=>'couponsNum'];
        if(array_key_exists($type, $typeName)){
          $m = Model('common/Table');
          $m->setTable('users'); 
          $info = $m->getInfo(['userId'=>$userId],$typeName[$type].',payPwd');
          if(md5($data['payPwd']) != $info['payPwd']){
            exit(jsonReturn('操作密码错误'));
          }
          if($data['num'] < 15){
             exit(jsonReturn('分配券值数量最低15'));
          }
          if($data['num'] > $info[$typeName[$type]]){            
             exit(jsonReturn('超出最大可分配数量,最多可分配:'.$info[$typeName[$type]]));
          }
          Db::startTrans();
            try{
                // $isDec = $m->decNum(['userId'=>$userId],$typeName[$type],$data['num']);
                // if($isDec){                    
                    $m->setTable('auth_company_partner');
                    $list = $m->getList(['userId'=>$userId,'dataFlag'=>1],'partnerId,stake');
                    $allNum = 0;
                    foreach ($list as &$v) {
                        $num = $data['num']*($v['stake']*0.01);
                        $allNum += $num;
                        Model('common/LogMoneys')->addMoneyLog(0,$v['partnerId'],0,2,'合作分配',1,$num,'invPay',$type);
                    }
                    Model('common/LogMoneys')->addMoneyLog(0,$userId,0,2,'合作分配',0,$allNum,'invPay',$type);
                    Db::commit();
                    exit(jsonReturn('操作成功',1));
                //}
            }catch (\Exception $e) {
                Db::rollback();errLog($e);
            }
          exit(jsonReturn('操作超时,请重试'));
        }
        
    }
    /**
     * 我家朋友
     */
    public function myFriendList($userId){
        $userLevel = (int)input('post.userLevel/d');
        $isLock = (int)input('post.isLock/d');
        $rs = [];
        if($isLock){
            $rs = Db::name('users u')
                ->join('user_trees t','u.userId=t.uid')
                ->join('user_lock l','u.userId=l.userId')
                ->where(['t.pid'=>$userId,'u.userStatus'=>0,'u.userLevel'=>$userLevel])
                ->field('u.userId,u.loginName as trueName,u.userPhone,u.userLevel,l.lockReason,l.lockTime,from_unixtime(l.createTime) createTime')
                ->order('l.id DESC,u.userId DESC')
                ->paginate(input('pageSize/d'))->toArray();
        }else{
            $rs = Db::name('users u')
                ->join('user_trees t','u.userId=t.uid')
                ->where(['t.pid'=>$userId,'u.userStatus'=>1,'u.userLevel'=>$userLevel])
                ->field('u.userId,u.trueName,u.userPhone,u.userLevel,u.createTime')
                ->order('u.userId DESC')
                ->paginate(input('pageSize/d'))->toArray();
        }
        return $rs;
    }
    public function getHTTPS($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    /**
     * 用户登录验证
     */
    public function checkLogin($loginSrc = 0){
        $loginName = input("post.loginName");
        $loginPwd = input("post.loginPwd");
        $code = input("post.verifyCode");
        $rememberPwd = input("post.rememberPwd",1);
        // if(WSTVisitModule() == 'home'){//pc版的有验证码 mark 20170914
        //     if(!WSTVerifyCheck($code) && strpos(WSTConf("CONF.captcha_model"),"4")>=0){
        //         return WSTReturn('验证码错误!');
        //     }
        // }
        if(strlen($loginName) < 3 || strlen($loginPwd) < 3){
            return WSTReturn('请输入用户名和密码!');
        }
        $ip = request()->ip();
        if($loginSrc ==3 ){
            $ticket = input('post.ticket');
            $randstr = input('post.randstr');
            if($ticket && $randstr){
                try{
                   $url='https://ssl.captcha.qq.com/ticket/verify?aid=2089606583&AppSecretKey=02pqzvc15HUGyhYTAck38HQ**&Ticket='.$ticket.'&Randstr='.$randstr.'&UserIP='.$ip;
                    $check_captcha = $this->getHTTPS($url);
                    $check_captcha = json_decode($check_captcha);
                    if('1' !== $check_captcha->response){
                        if('fsdagsadfdsfsad3e3hg' != $ticket || 'hyjuoiyugsfae3fs887ts' != $randstr) return WSTReturn($check_captcha->err_msg);
                    }
                } catch (\Exception $e) {
                  return WSTReturn($e->getMessage());
                }
            }else{
                return WSTReturn('请先验证!');
            }
        }
        $rs = $this->where("loginName|userPhone",$loginName)
                    ->where(["dataFlag"=>1])
                    ->find();
        if(isset($rs['userStatus']) && 0 == $rs['userStatus']){//禁用状态
            $lockInfo = Db::name('user_lock')->where(['userId'=>$rs['userId']])->field('adminId,lockReason,lockTime,createTime')->order('id DESC')->find();
            if($lockInfo){
                if(0 == $lockInfo['adminId']){
                    return WSTReturn($lockInfo['lockReason']);
                }
                if(0 == $lockInfo['lockTime']){
                    return WSTReturn("账号已禁用,禁用原因:".$lockInfo['lockReason'].',禁用时间:永久');
                }
                $lockEndTime = $lockInfo['createTime']+($lockInfo['lockTime']*60);
                if(time() >= $lockEndTime){//大于锁定时间
                    $this->where(['userId'=>$rs['userId']])->update(['userStatus'=>1]);
                }else{
                    return WSTReturn("账号已禁用,禁用原因:".$lockInfo['lockReason'].',解禁日期:'.date('Y-m-d H:i:s',$lockEndTime));
                }
            }else{
                return WSTReturn('账号已禁用,禁用原因:未知,禁用时间:永久');
            }
        }
        //hook("beforeUserLogin",["user"=>&$rs]);
        /**
         * 添加整合登录插件 mark 20170829 
         */
        // if(empty($rs)){
        //     hook("beforeUserLogin",["user"=>&$rs]);            
        // }
        /**
         * end
         */
        
        if(!empty($rs)){
            if($rs['loginPwd']!=md5($loginPwd.$rs['loginSecret']))return WSTReturn("密码错误");
            if($rs['userPhoto']=='')$rs['userPhoto'] = WSTConf('CONF.userLogo');
            $userId = $rs['userId'];
            //获取用户等级
            $rrs = Db::name('user_ranks')->where(['dataFlag'=>1])->where('startScore','<=',$rs['userTotalScore'])->where('endScore','>=',$rs['userTotalScore'])->field('rankId,rankName,userrankImg')->find();
            $rs['rankId'] = $rrs['rankId'];
            $rs['rankName'] = $rrs['rankName'];
            $rs['userrankImg'] = $rrs['userrankImg'];
            if(input("post.typ")==2){
                $shoprs=$this->where(["dataFlag"=>1, "userStatus"=>1,"userType"=>1,"userId"=>$userId])->find();
                if(empty($shoprs)){
                    return WSTReturn('您还没申请店铺!');
                }
            }
            $update = [];
            $update = ["lastTime"=>date('Y-m-d H:i:s'),"lastIP"=>$ip];
            $wxOpenId = session('WST_WX_OPENID');
            if($wxOpenId){
                $update['wxOpenId'] = $rs['wxOpenId'] = session('WST_WX_OPENID');
                // 保存unionId【若存在】 详见 unionId说明 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839
                $userinfo = session('WST_WX_USERINFO');
                $update['wxUnionId'] = isset($userinfo['unionid'])?$userinfo['unionid']:'';
            }
            $token='';
            if($loginSrc ==3 ){//添加token mark hsf 20180212               
                $update['token'] = md5($userId.time().mt_rand(1,999));
                $token = $update['token'] ;
            }
            
            $this->where(["userId"=>$userId])->update($update);
            
            //如果是店铺则加载店铺信息
             if($rs['userType']>=1){
                 // $shop = Db::name("shops s")
        //                  ->join("__SHOP_USERS__ su","s.shopId=su.shopId")
        //                  ->field("s.*,su.roleId")
        //                  ->where(["su.userId"=>$userId,"s.dataFlag" =>1])->find();
        //                  dump($shop);die;
                 /*---------修复商家登录不上 mark hsf 20180227 */
                 $shop = Db::name("shops s")
                         ->join("__SHOP_USERS__ su","s.shopId=su.shopId")
                         ->field("s.*,su.roleId")
                         ->where(["su.userId"=>$userId,"s.dataFlag" =>1])->find();
                 if(empty($shop)){
                     $shop = Db::name("shops s")
                         ->field("s.*")
                         ->where(["s.userId"=>$userId,"s.dataFlag" =>1])->find();
                 }
               
                 if(!empty($shop))$rs = array_merge($shop,$rs->toArray());
                 /*---------end-------------*/
             }
       //      //签到时间
       //      if(WSTConf('CONF.signScoreSwitch')==1){
       //          $rs['signScoreTime'] = 0;
       //          $userscores = Db::name('user_scores')->where(["userId"=>$userId,"dataSrc"=>5,])->order('createTime desc')->find();
       //          if($userscores)$rs['signScoreTime'] = date("Y-m-d",strtotime($userscores['createTime']));
       //      }
            //记录登录日志
            $data = array();
            $data["userId"] = $userId;
            $data["loginTime"] = date('Y-m-d H:i:s');
            $data["loginIp"] = $ip;
            $data['loginSrc'] = $loginSrc;
            Db::name('log_user_logins')->insert($data);
            
            $rd = $rs;
            //记住密码
            // $t = time();
            // cookie("loginName", $loginName, $t+3600*24*90);
            if($rememberPwd == "on"){
                $datakey = md5($rs['loginName'])."_".md5($rs['loginPwd']);
                $key = $rs['loginSecret'];
                //加密
                $base64 = new \org\Base64();
                $loginKey = $base64->encrypt($datakey, $key);
                //cookie("loginPwd", $loginKey, $t+3600*24*90);
            }else{
              //  cookie("loginPwd", null);
            }
            session('WST_USER',$rs);
            hook('afterUserLogin',['user'=>$rs]);
            
            return WSTReturn("登录成功","1",['token'=>$token]);//添加返回token mark hsf 20170212
        
        }
        return WSTReturn("用户名或密码错误");
    }
    
    /**
     * 会员注册
     */
    public function regist($loginSrc = 0){
       // return WSTReturn('注册频繁');
        $data = array();
        $data['loginName'] = input("post.loginName");
        $data['loginPwd'] = input("post.loginPwd");
        $data['reUserPwd'] = $data['loginPwd'] ;//input("post.reUserPwd");
        $data['payPwd'] = input("post.payPwd");
        $data['regConfirmImg'] = input("post.regConfirmImg");//注册确认书
        $loginName = $data['loginName'];
        if(!$data['regConfirmImg']){
            return WSTReturn("请上传注册确认书!");
        }
        if($data['loginPwd']!=$data['reUserPwd']){
            return WSTReturn("两次输入密码不一致!");
        }
        if(strlen($data['loginPwd']) < 6){
             return WSTReturn("登录密码不可小于6位!");
        }
        if(strlen($data['payPwd']) < 6){
             return WSTReturn("操作密码不可小于6位!");
        }
        foreach ($data as $v){
            if($v ==''){
                return WSTReturn("注册信息请填写完整!");
            }
        }
        $nameType = (int)input("post.nameType");
        $mobileCode = input("post.mobileCode");
       // if(WSTVisitModule() !='home'){
       //      $code = input("post.verifyCode");
       //      if(!WSTVerifyCheck($code)){
       //          return WSTReturn("验证码错误!");
       //      }
       //  }
        $pInfo['userId']=0;
        //添加验证推荐人了 mark hsf 20171129
        $pName = input('post.pName');
        //if($pName){//写推荐人了
            $pInfo = getUserByName($pName,'userId');            
            if(!$pInfo){
                return WSTReturn("推荐人不存在!");
            }
        //}
        
        $fp = fopen("reg.lock", "r");
        if(flock($fp,LOCK_EX | LOCK_NB)) {//if(flock($fp,LOCK_EX))阻塞(等待)模式
             //检测账号是否存在
            $crs =  WSTCheckLoginKey($loginName);
            if($crs['status']!=1){
                flock($fp,LOCK_UN);
                fclose($fp);
                return $crs;
            }
            //------end------//
           // if($nameType==3 && WSTConf("CONF.smsOpen")==1){//手机号码
           //if(WSTConf("CONF.smsOpen")==1){//手机号码
                //$data['userPhone'] = $loginName;
                $verify = session('VerifyCode_userPhone');
                $startTime = (int)session('VerifyCode_userPhone_Time');
                if((time()-$startTime)>120){
                    flock($fp,LOCK_UN);
                    fclose($fp);
                    return WSTReturn("验证码已超过有效期!");
                }
                if($mobileCode=="" || $verify != $mobileCode){
                    flock($fp,LOCK_UN);
                    fclose($fp);
                    return WSTReturn("短信验证码错误!");
                }
                //$loginName = WSTRandomLoginName($loginName);
            // }else if($nameType==1){//邮箱注册
            //     $data['userEmail'] = $loginName;
            //     $unames = explode("@",$loginName);
            //     $loginName = WSTRandomLoginName($unames[0]);
                
            // }else{
            //     flock($fp,LOCK_UN);
            //     fclose($fp);
            //     return WSTReturn("注册失败,请重试!");
            // }
            // if($loginName==''){
            //     flock($fp,LOCK_UN);
            //     fclose($fp);
            //     return WSTReturn("注册失败!");//分派不了登录名
            // }
            $data['loginName'] = $loginName;
            unset($data['reUserPwd']);
            unset($data['protocol']);
            //检测账号,邮箱,手机是否存在
            $data["loginSecret"] = '';//rand(1000,9999);
            $data['loginPwd'] = md5($data['loginPwd'].$data['loginSecret']);
            $data['payPwd'] = md5($data['payPwd'].$data['loginSecret']);
            $data['userType'] = 0;
            $data['userName'] = input("post.userName");
            $data['userQQ'] = "";
            $data['userScore'] = 0;
            $data['userTotalScore'] = 0;      
            $data['createTime'] = date('Y-m-d H:i:s');
            $data['dataFlag'] = 1;
            $wxOpenId = session('WST_WX_OPENID');
            if($wxOpenId){
                $data['wxOpenId'] = session('WST_WX_OPENID');
                $userinfo = session('WST_WX_USERINFO');
                if($userinfo){
                    $data['userName'] = $userinfo['nickname'];
                    $data['userSex'] = $userinfo['sex'];
                    $data['userPhoto'] = $userinfo['headimgurl'];
                    // 保存unionId【若存在】 详见 unionId说明 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839
                    $data['wxUnionId'] = isset($userinfo['unionid'])?$userinfo['unionid']:'';
                }
            }
            Db::startTrans();
            try{
                $userId = $this->data($data)->save();
                if(false !== $userId){
                    //保存注册信息
                    $userId = $this->userId;
                    $logData['userId']=$userId;
                    $logData['loginSrc']=$loginSrc;
                    $logData['createTime']=time();
                    $logResult = db('login_src')->insert($logData);
                    
                    $data = array();
                    $ip = request()->ip();
                    $data['lastTime'] = date('Y-m-d H:i:s');
                    $data['lastIP'] = $ip;
                    $userId = $this->userId;
                    $this->where(["userId"=>$userId])->update($data);
                    //记录登录日志
                    // $data = array();
                    // $data["userId"] = $userId;
                    // $data["loginTime"] = date('Y-m-d H:i:s');
                    // $data["loginIp"] = $ip;
                    // $data['loginSrc'] = $loginSrc;
                    // Db::name('log_user_logins')->insert($data);
                    $user = $this->get($userId);
                    if($user['userPhoto']=='')$user['userPhoto'] = WSTConf('CONF.userLogo');
                    session('WST_USER',$user);
                    //注册成功后执行钩子
                    hook('afterUserRegist',['user'=>$user]);
                    //发送消息
                    $tpl = WSTMsgTemplates('USER_REGISTER');
                    if( $tpl['tplContent']!='' && $tpl['status']=='1'){
                        $find = ['${LOGIN_NAME}','${MALL_NAME}'];
                        $replace = [$user['loginName'],WSTConf('CONF.mallName')];
                        WSTSendMsg($userId,str_replace($find,$replace,$tpl['tplContent']),['from'=>0,'dataId'=>0]);
                    }
                    create_tree($userId,$pInfo['userId']);
                    Db::commit();
                    flock($fp,LOCK_UN);
                    fclose($fp);
                    return WSTReturn("注册成功",1);
                }
            }catch (\Exception $e) {
                Db::rollback();errLog($e);
                flock($fp,LOCK_UN);
                fclose($fp);
            }
            return WSTReturn("注册失败!");
        }else{
            fclose($fp);
            return WSTReturn('系统繁忙,请稍后再试');  
        }
    }
    
    /**
     * 查询用户手机是否存在
     * 
     */
    public function checkUserPhone($userPhone,$userId = 0,$field='userId'){
        $dbo = Db::name('users')->where(["dataFlag"=>1, "userPhone"=>$userPhone]);
        if($userId>0){
            $dbo->where("userId","<>",$userId);
        }
        $rs = $dbo->field($field)->find();
        if($rs){
            return WSTReturn("手机号已存在!",-1,$rs);
        }else{
            /* 增加检测联盟手机号 mark 20170915*/
            // if(getLMUserByName($userPhone)){
            //     return WSTReturn("手机号已存在!");
            // }
            /* end */
            return WSTReturn("",1);
        }
        // $rs = $dbo->count();
        // if($rs>0){
        //     return WSTReturn("手机号已存在!");
        // }else{
        //     return WSTReturn("",1);
        // }
    }

    /**
     * 修改用户密码
     */
    public function editPass($id){
        $data = array();
        $newPass = input("post.newPass");
        $decrypt_data = WSTRSA($newPass);
        if($decrypt_data['status']==1){
            $newPass = $decrypt_data['data'];
        }else{
            return WSTReturn('修改失败');
        }
        if(!$newPass){
            return WSTReturn('密码不能为空',-1);
        }
        $rs = $this->where('userId='.$id)->find();
        //核对密码
        if($rs['loginPwd']){
            $oldPass = input("post.oldPass");
            $decrypt_data2 = WSTRSA($oldPass);
            if($decrypt_data2['status']==1){
                $oldPass = $decrypt_data2['data'];
            }else{
                return WSTReturn('修改失败');
            }
            if($rs['loginPwd']==md5($oldPass.$rs['loginSecret'])){
                $data["loginPwd"] = md5($newPass.$rs['loginSecret']);
                $rs = $this->update($data,['userId'=>$id]);
                if(false !== $rs){
                    hook("afterEditPass",["userId"=>$id]);
                    return WSTReturn("密码修改成功", 1);
                }else{
                    return WSTReturn($this->getError(),-1);
                }
            }else{
                return WSTReturn('原始密码错误',-1);
            }
        }else{
            $data["loginPwd"] = md5($newPass.$rs['loginSecret']);
            $rs = $this->update($data,['userId'=>$id]);
            if(false !== $rs){
                hook("afterEditPass",["userId"=>$id]);
                return WSTReturn("密码修改成功", 1);
            }else{
                return WSTReturn($this->getError(),-1);
            }
        }
    }
    /**
     * 修改用户支付密码
     */
    public function editPayPass($id){
        $data = array();
        $newPass = input("post.newPass");
        //添加二次密码验证  mark hsf 20180321
        $reNewPass = input("post.reNewPass");
        if($newPass != $reNewPass){
            return WSTReturn('二次密码输入不一致,请重新输入!',-1);
        }
        //end
        $decrypt_data = WSTRSA($newPass);
        if($decrypt_data['status']==1){
            $newPass = $decrypt_data['data'];
        }else{
            return WSTReturn('修改失败');
        }
        if(!$newPass){
            return WSTReturn('支付密码不能为空',-1);
        }
        $rs = $this->where('userId='.$id)->find();
        //核对密码
        if($rs['payPwd']){
            $oldPass = input("post.oldPass");
            $decrypt_data2 = WSTRSA($oldPass);
            if($decrypt_data2['status']==1){
                $oldPass = $decrypt_data2['data'];
            }else{
                return WSTReturn('修改失败');
            }
            if($rs['payPwd']==md5($oldPass.$rs['loginSecret'])){
                $data["payPwd"] = md5($newPass.$rs['loginSecret']);
                $rs = $this->update($data,['userId'=>$id]);
                if(false !== $rs){
                    return WSTReturn("支付密码修改成功", 1);
                }else{
                    return WSTReturn("支付密码修改失败",-1);
                }
            }else{
                return WSTReturn('原始支付密码错误',-1);
            }
        }else{
            $data["payPwd"] = md5($newPass.$rs['loginSecret']);
            $rs = $this->update($data,['userId'=>$id]);
            if(false !== $rs){
                return WSTReturn("支付密码设置成功", 1);
            }else{
                return WSTReturn("支付密码修改失败",-1);
            }
        }
    }
    /**
     * 重置用户支付密码
     */
    public function resetbackPay($uId=0){
        $timeVerify = session('Verify_backPaypwd_Time');
        if(time()>floatval($timeVerify)+10*60){
            session('Type_backPaypwd',null);
            return WSTReturn("校验码已失效,请重新验证!");
            exit();
        }
        $data = array();
        $data["payPwd"] = input("post.newPass");
        $decrypt_data = WSTRSA($data["payPwd"]);
        if($decrypt_data['status']==1){
            $data["payPwd"] = $decrypt_data['data'];
        }else{
            return WSTReturn('修改失败');
        }
        if(!$data["payPwd"]){
            return WSTReturn('支付密码不能为空',-1);
        }
        $userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
        $rs = $this->where('userId='.$userId)->find();
        $data["payPwd"] = md5($data["payPwd"].$rs['loginSecret']);
        $rs = $this->update($data,['userId'=>$userId]);
        if(false !== $rs){
            session('Type_backPaypwd',null);
            session('Verify_backPaypwd_info',null);
            session('Verify_backPaypwd_Time',null);
            return WSTReturn("支付密码设置成功", 1);
        }else{
            return WSTReturn("支付密码修改失败",-1);
        }
    }
   /**
    *  获取用户信息
    */
    public function getById($id){
        $rs = $this->get(['userId'=>(int)$id]);
        $rs['ranks'] = WSTUserRank($rs['userTotalScore']);
        return $rs;
    }
    /**
     * 编辑资料
    */
    public function edit(){
        $Id = (int)session('WST_USER.userId');
        $data = input('post.');
        if(isset($data['brithday']))$data['brithday'] = ($data['brithday']=='')?date('Y-m-d'):$data['brithday'];
        WSTAllow($data,'brithday,trueName,userName,userId,userPhoto,userQQ,userSex');
        Db::startTrans();
        try{
            if(isset($data['userPhoto']) && $data['userPhoto']!='')
                 WSTUseImages(0, $Id, $data['userPhoto'],'users','userPhoto');
             
            $result = $this->allowField(true)->save($data,['userId'=>$Id]);
            if(false !== $result){
                Db::commit();
                return WSTReturn("编辑成功", 1);
            }
        }catch (\Exception $e) {
            Db::rollback();errLog($e);
            return WSTReturn('编辑失败',-1);
        }   
    }
    /**
    * 绑定邮箱
     */
    public function editEmail($userId,$userEmail){
        $data = array();
        $data["userEmail"] = $userEmail;
        Db::startTrans();
        try{
            $user = Db::name('users')->where(["userId"=>$userId])->field(["userId","loginName,userEmail"])->find();
            $rs = $this->update($data,['userId'=>$userId]);
            if(false !== $rs){
                hook("afterEditEmail",["user"=>$user]);
                Db::commit();
                return WSTReturn("绑定成功",1);
            }else{
                Db::rollback();errLog('失败');
                return WSTReturn("",-1);
            }
        }catch (\Exception $e) {
            Db::rollback();errLog($e);
            return WSTReturn('编辑失败',-1);
        }
    }
    /**
     * 绑定手机
     */
    public function editPhone($userId,$userPhone){
        $data = array();
        $data["userPhone"] = $userPhone;
        $rs = $this->update($data,['userId'=>$userId]);
        if(false !== $rs){
            return WSTReturn("绑定成功", 1);
        }else{
            return WSTReturn($this->getError(),-1);
        }
    }
    /**
     * 查询并加载用户资料
     */
    public function checkAndGetLoginInfo($key){
        if($key=='')return array();
        $rs = $this->where(["loginName|userEmail|userPhone"=>['=',$key],'dataFlag'=>1])->find();
        return $rs;
    }
    /**
     * 重置用户密码
     */
    public function resetPass($uId=0){
        if(time()>floatval(session('REST_Time'))+30*60){
            return WSTReturn("连接已失效!", -1);
        }
        $reset_userId = (int)session('REST_userId');
        if($reset_userId==0){
            return WSTReturn("无效的用户!", -1);
        }
        $user = $this->where(["dataFlag"=>1,"userStatus"=>1,"userId"=>$reset_userId])->find();
        if(empty($user)){
            return WSTReturn("无效的用户!", -1);
        }
        $loginPwd = input("post.loginPwd");
        if($uId==0){// 大于0表示来自app端
            $decrypt_data = WSTRSA($loginPwd);
            if($decrypt_data['status']==1){
                $loginPwd = $decrypt_data['data'];
            }else{
                return WSTReturn('修改失败');
            }
        }
        if(trim($loginPwd)==''){
            return WSTReturn("无效的密码!", -1);
        }
        $data['loginPwd'] = md5($loginPwd.$user["loginSecret"]);
        $rc = $this->update($data,['userId'=>$reset_userId]);
        if(false !== $rc){
            hook("afterEditPass",["userId"=>$reset_userId]);//修改密码插件 mark 20170915
            session('REST_userId',null);
            session('REST_Time',null);
            session('REST_success',null);
            session('findPass',null);
            return WSTReturn("修改成功", 1);
        }
        return [];
    }
    
    /**
     * 获取用户可用惠宝
     */
    public function getFieldsById($userId,$fields){
        return $this->where(['userId'=>$userId,'dataFlag'=>1])->field($fields)->find();
    }
    /*获取用户分享列表*/
    public function getShareList(){
        $id=session('WST_USER.userId');
        //普通用户分享列表
        $userType=(int)input('userType');
        //$userType=1;
        if($userType=='0'){
           $user_lists=Db::name('user_trees')->alias('a')->join('users b','b.userId=a.uid')
                   ->where('a.pid',$id)->where('b.userType','0')->field('b.userId,b.loginName,b.createTime,b.userPhoto')->order('userId DESC')
                   ->paginate(input('pagesize/d'))->toArray();
           if(empty($user_lists)){
                exit(jsonReturn('暂无分享用户',0));
           }else{
                foreach ($user_lists['Rows'] as &$v) {
                    if(!Db::name('log_user_logins')->where(['userId'=>$v['userId'],'loginSrc'=>3])->field('userId')->find()){
                        $v['isLogin'] = 0;
                    }else{
                        $v['isLogin'] = 1;
                    }
                }
                exit(json_encode($user_lists));
           }

        }elseif ($userType=='1') {
          $merchants_lists=Db::name('user_trees')->alias('a')->join('users b','b.userId=a.uid')
          ->where('a.pid',$id)->where('b.userType','1')->field('b.userId,b.loginName,b.createTime,b.userPhoto')->order('userId DESC')
          ->paginate(input('pagesize/d'))->toArray();

          if(empty($merchants_lists)){
                exit(jsonReturn('暂无分享商家',0));
           }else{
                foreach ($merchants_lists['Rows'] as &$v) {
                    if(!Db::name('log_user_logins')->where(['userId'=>$v['userId'],'loginSrc'=>3])->field('userId')->find()){
                        $v['isLogin'] = 0;
                    }else{
                        $v['isLogin'] = 1;
                    }
                }
                exit(json_encode($merchants_lists));
           }
        }else{
           exit(jsonReturn('请输入有效类型!',-1));
        }
    }
    /*获取用户分享信息*/
    public function getShareInfo(){
        $userId=session('WST_USER.userId');
        //普通用户分享列表
        $userType=(int)input('userType');
        if(in_array($userType, [0,1])){
            $sid=(int)input('sid');
            $data['ect']=Db::name('user_reward')->alias('r')
                                ->join('__ORDERS__ o','o.orderId=r.orderId')
                                ->where(['r.userId'=>$userId,'r.sid'=>$sid,'r.isSeller'=>$userType,'r.payType'=>1])
                               // ->group('r.orderId')
                                ->field('SUM(o.realTotalMoney) order_num,SUM(r.rewardNum) reward_num')
                                ->find();
             $data['money']=Db::name('user_reward')->alias('r')
                                ->join('__ORDERS__ o','o.orderId=r.orderId')
                                ->where(['r.userId'=>$userId,'r.sid'=>$sid,'r.isSeller'=>$userType,'r.payType'=>2])
                               // ->group('r.orderId')
                                ->field('SUM(o.realTotalMoney) order_num,SUM(r.rewardNum) reward_num')
                                ->find();
            exit(json_encode($data));
        }else{
           exit(jsonReturn('请输入有效类型!',-1));
        }
    }
    function getUserStatusName($userStatus){
        $statusName = '禁用';
        switch($userStatus){
            case 1:
                $statusName = '正常';
                break;
        }
        return $statusName;
    }
    function getUserLevelName($userLevel){
        $levelName = '普通用户';
        switch($userLevel){
            case 1:
                $levelName = '商户';
                break;
            case 2:
                $levelName = '商超';
                break;
            case 3:
                $levelName = '商厦';
                break;
            case 4:
                $levelName = '商都';
                break;
        }
        return $levelName;
    }
    function addUserVouchersSummary($expectedProductNum,$expectedCouponsNum){
        
    }
}