<?php
namespace wstmart\app\controller;
use think\Db;
use wstmart\app\model\Users as M;
use wstmart\app\model\Favorites;
use wstmart\app\model\Messages;
use wstmart\common\model\LogSms;
use wstmart\common\model\Users as MUsers;
use wstmart\common\model\UserTrees;
use think\Collection;
/**
 * ============================================================================
 * 用户控制器
 */
class Users extends Base{

	// 前置方法执行列表
    protected $beforeActionList = [
          'checkAuth' =>  ['except'=>'checklogin,login,check_login_name,get_puser_info,register,getverify,toregister,forgetpass,forgetpasst,forgetpasss,forgetpassf,findpass,getfindphone,resetpass,getphoneverifycode,checkuserphone']// 访问这些except下的方法不需要执行前置操作
          ];
    /**
     * 我的亲人投资列表
     * @return [type] [description]
     */
    public function familyInvestmentList(){
    	//if(0 == $this->user['authType'])exit(jsonReturn('请先实名认证'));
    	$m = Model('common/Table');
       
      $userId = $this->getUserId();
      $list = db('auth_company_partner p')
      					->join('__AUTH_FAMILY_PERSONAL__ f','f.familyId=p.partnerId')        					
      					->join('__AUTH_COMPANY__ c','c.userId=p.userId')
      					->where(['f.userId'=>$userId,'p.dataFlag'=>1,'c.status'=>1])
      					->field('c.userId,c.companyName,c.headImg,c.companyAddress,c.createTime,p.positionName,p.stake')
                ->select();
      					//->paginate(input('pageSize/d',10))->toArray();
      $m->setTable('auth_company_partner');
      foreach ($list as &$v) {
      	$v['headImg'] = WSTImg($v['headImg'],3);
      	$v['count'] = $m->getCount(['userId'=>$v['userId'],'dataFlag'=>1],'id'); 
      }
      exit(jsonReturn('',1,$list));
    }
    //合作认证详细信息
    public function investmentInfo(){
      $userId = input('userId');
      $m = Model('common/Table');
      $m->setTable('auth_company_partner');
      $list = $m->getList(['userId'=>$userId,'dataFlag'=>1],'uName,positionName,businessImg,stake,createTime');      
      exit(jsonReturn('',1,$list));
    }
    /**
     * 获取合作券值
     * @return [type] [description]
     */
     public function getInvestmentMoney(){
        $userId = input('userId');
        $field = 'productNum,couponsNum';
        $m = Model('common/Table');
        $m->setTable('users'); 
        $info = $m->getInfo(['userId'=>$userId],$field);
        exit(jsonReturn('',1,$info));
        
    }
    /**
     * 分配券值
     * @return [type] [description]
     */
    public function distributionInvestmentMoney(){
         $m = new MUsers();
         $rs = $m->distributionInvestmentMoney();
         exit(json_encode($rs));
    }

    /**
     * 检测会员名
     */
    public function check_login_name(){
      $loginName = input('post.loginName');
      if(strlen($loginName) < 6 ){
          exit(jsonReturn('用户名不能小于6个字符!'));
      }
      exit(json_encode(WSTCheckLoginKey($loginName)));
    }
    /**
     * 获取券值
     * @return [type] [description]
     */
     public function getMoney(){
        $type = (int)input('post.type');
        $typeName = ['0'=>'productNum,couponsNum,wangNum','1'=>'productNum','2'=>'couponsNum','3'=>'wangNum'];
        if(array_key_exists($type, $typeName)){
          $m = Model('common/Table');
          $m->setTable('users'); 
          $info = $m->getInfo(['userId'=>$this->getUserId()],$typeName[$type]);
          exit(jsonReturn('',1,$info));
        }
        
    }
      /**
     * 获取推荐人信息
     */
    public function get_puser_info(){
      $pName = trim(input('post.pName'));
      $pInfo = getUserInfo(['loginName|userPhone'=>$pName],'loginName,userPhone');
      if($pInfo){
         exit(jsonReturn('',1,$pInfo));
      }
      exit(jsonReturn('未找到推荐信息'.$pName));
    }
    /**
     * 我家朋友
     */
    public function myFriend(){
        $m = new MUsers();
        $userId = $this->getUserId();
        $rs =  $m->myFriend($userId);
        $rs['user'] = ['userId'=>$userId,'loginName'=>$this->user['loginName']];
        $rs['share_url'] = 'http://t.ect99.com/mobile/reg/reg.html?pName='.$this->user['loginName'];
        exit(jsonReturn('',1,$rs));
    }
    /**
     * 我家朋友列表
     */
    public function myFriendList(){
        $m = new MUsers();
        $userId = $this->getUserId();
        $rs =  $m->myFriendList($userId);
        exit(jsonReturn('',1,$rs));
    }

    /**
     * 会员登录
     */
    public function checkLogin(){
    	$m = new M();
    	$rs =  $m->checkLogin(3);
    	$rs['url'] = session('WST_MO_WlADDRESS');
    	exit(json_encode($rs));
    }
    public function get_name_and_money(){
        $data['name'] = session('WST_USER.loginName');
        $data['money'] = session('WST_USER.userMoney');
        $data['userECT'] = session('WST_USER.userECT');
        exit(jsonReturn('',1,$data));
    }
    /**
     * 会员注册
     */
    public function register(){
    	$m = new M();
    	$rs =  $m->regist(3);
    	$rs['url'] = session('WST_MO_WlADDRESS');
    	exit(json_encode($rs));
    }
    /**
     * 手机号码是否存在
     */
    public function checkUserPhone(){
    	$userPhone = input("post.userPhone");
    	$m = new M();
    	$rs = $m->checkUserPhone($userPhone,$this->getUserId());
    	if($rs["status"]!=1){
    		exit(jsonReturn("手机号已注册",-1));
    	}else{
    		exit(jsonReturn("",1));
    	}
    }
    /**
     * 获取验证码
     */
    public function getPhoneVerifyCode(){
    	$userPhone = input("post.userPhone");
    	$rs = array();
    	if(!WSTIsPhone($userPhone)){
    		exit(jsonReturn("手机号格式不正确!"));
    	}
    	$m = new M();
    	$rs = $m->checkUserPhone($userPhone,0,'loginName');
      //是否是推荐人注册 0不是,1是
       if(0 == WSTConf('CONF.referrerOpen')){
        if($rs["status"]!=1){
          exit(jsonReturn("手机号已存在!"));
        }else{          
          $phoneVerify = rand(1000,9999);
          $tpl = WSTMsgTemplates('PHONE_USER_REGISTER_VERFIY');
        }
      }else{
        if($rs["status"]==1){
          exit(jsonReturn("手机号不存在!"));
        }else{
          $phoneVerify = rand(1000,9999);
          $tpl = WSTMsgTemplates('PHONE_PUSER_REGISTER_VERFIY');          
        }
      }
      $rv['status'] = -1;
      $rv['msg'] = '发送失败';
    	if( $tpl['tplContent']!='' && $tpl['status']=='1'){
        $params = ['tpl'=>$tpl,'params'=>['name'=>$rs['data']['loginName'],'code'=>$phoneVerify]];
        $m = new LogSms();
        $rv = $m->sendSMS(0,$userPhone,$params,'getPhoneVerifyCode',$phoneVerify);
      }    	
    	if($rv['status']==1){
    		session('VerifyCode_userPhone',$phoneVerify);
    		session('VerifyCode_userPhone_Time',time());
    	}
    	exit(json_encode($rv));
    }
	/**
	 * 会员中心
	 */
	public function index(){
		$userId = $this->getUserId();
		$m = new M();
		$user = $m->getById($userId);
		if($user['userName']=='')
			$user['userName']=$user['loginName'];
		$this->assign('user', $user);

		//商城未读消息的数量 及 各订单状态数量
		$data = model('index')->getSysMsg('msg','order');
		$this->assign('data',$data);
		return $this->fetch('users/index');
	}
  /**
   * 会员中心
   */
  public function getIndex(){
    $userId = $this->getUserId();
    $m = Model('common/Table');
    $m->setTable('user_vouchers_summary');
    $data = $m->getInfo(['userId'=>$userId],'expectedProductNum,expectedCouponsNum,alreadyProductNum,alreadyCouponsNum');
    $m->setTable('shops');
    $shopIds = $m->getColumn(['status'=>1,'userId'=>$userId],'shopId');
    if($shopIds){
      $m->setTable('orders');
      $data['expectedWangNum'] =  $m->getField(['shopId'=>['in',$shopIds],'orderStatus'=>['BETWEEN','0,1']],'SUM((productNum - productHandlingFee - productTaxFee) + (couponsNum - couponsHandlingFee - couponsTaxFee) + wangNum)');//预获旺旺券 
    }else{
      $data['expectedWangNum'] =  0;//预获旺旺券
    }
    $data['expectedProductNum'] = isset($data['expectedProductNum']) ? $data['expectedProductNum']  : 0;
    $data['expectedCouponsNum'] = isset($data['expectedCouponsNum']) ? $data['expectedCouponsNum']  : 0;
    $data['user'] = getUserInfo(['userId'=>$userId],'userId,loginName,userType,userName,trueName,userPhone,userPhoto,userStatus,token,userLevel,authType,couponsNum,productNum,wangNum');
    if(1 == $this->user['authType']){
      $m->setTable('auth_personal');
      $data['user']['userPhoto'] = $m->getField(['userId'=>$userId,'status'=>1],'headImg');
    }elseif(2 == $this->user['authType']){
      $m->setTable('auth_company`');
      $data['user']['userPhoto'] = $m->getField(['userId'=>$userId,'status'=>1],'headImg');
    }
    //$data['favoritesNum'] = $this->getFavoritesNum(0);   
    //商城未读消息的数量 及 各订单状态数量  
    //$data['sysMsg'] = $this->getSysMsg(0);
   
    exit(jsonReturn("",1,$data));
  }
  /**
   * 设置点赞记数
   */
  public function setRewardLike(){
      $rewardId = (int)input("param.rewardId/d",0);
      $isLike = (int)input("param.isLike/d",0);
      if($rewardId){
          $s = model('shops');
          $s->setRewardLike($rewardId,$this->getUserId(),$isLike);
          exit(jsonReturn('',1));
      }
      exit(jsonReturn('设置失败'));
  }
  /**
   * 商城未读消息的数量 及 各订单状态数量
   * @param  integer $returnJson [1代表返回json数据,其他代表返回数组]
   */
  public function getSysMsg($returnJson = 1){
    $data = model('index')->getSysMsg('msg','order');
    if($returnJson  == 1){
      exit(jsonReturn("",1,$data));
    }else{
      return $data;
    }
  }
 /**
  * 商城未读消息的数量
  * @param  integer $returnJson [1代表返回json数据,其他代表返回数组]
  */
  public function getMsgNum($returnJson = 1){
    $data = model('index')->getSysMsg('msg');
    if($returnJson  == 1){
      exit(jsonReturn("",1,$data));
    }else{
      return $data;
    }
  }
  /**
  * 商城各订单状态数量
  * @param  integer $returnJson [1代表返回json数据,其他代表返回数组]
  */
  public function getOrderNum($returnJson = 1){
    $data = model('index')->getSysMsg('','order');
    if($returnJson  == 1){
      exit(jsonReturn("",1,$data));
    }else{
      return $data;
    }
  }
  /**
   * 获取会员信息
   * @param  integer $returnJson [1代表返回json数据,其他代表返回数组]
   */
  public function getUserInfo($returnJson = 1){
     $userId = session('WST_USER.userId');
     $m = new M();
     $user = $m->getUserInfo($userId,'*');
      // $where = [];
      // $where['cr.userId'] = $this->getUserId();
      // $where['cr.isUse'] = 0;
      // $now=time();
      // // $where['ck.begin_time']=array('lt',$now);
      // $where['ck.end_time']=array('gt',$now);
      
      // $user['couponNum'] = db('coupon_record')->alias('cr')
      // ->join('__COUPON_KIND__ ck','cr.couponId=ck.Id','inner')
      // ->where($where)
      // ->count();

     if($returnJson  == 1){        
        exit(jsonReturn("",1,$user));
     }else{
        return $user;
     }
  }
  /**
   * 获取会员关注商品数和关注商家数
   * @param  integer $returnJson [description]
   * @return [type]              [description]
   */
  public function getFavoritesNum($returnJson = 1){
     $m = new Favorites();
     $data = $m->getFavoritesNum($this->getUserId());
    $data['shareNum'] = (int)model('UserTrees')->getShareNum(['pid'=>$this->getUserId()]);
     if($returnJson  == 1){
        exit(jsonReturn("",1,$data));
     }else{
        return $data;
     }
  }
	/**
	 * 个人信息
	 */
	public function edit(){
		$userId = $this->getUserId();
		$m = new M();
		$user = $m->getById($userId);
    exit(jsonReturn('',1,$user));
		//$this->assign('user', $user);
		//return $this->fetch('users/edit');
	}
	/**
	 * 编辑个人信息
	 */
	public function editUserInfo(){
       $m = new M();
       return $m->edit();
   }
	/**
	 * 账户安全
	 */
	public function security(){
  	$m = new M();
		$userId =  $this->getUserId();
		$user = $m->getById($userId);
		$payPwd = $user['payPwd'];
		$userPhone = $user['userPhone'];
		$loginPwd = $user['loginPwd'];
		$user['loginPwd'] = empty($loginPwd)?0:1;
		$user['payPwd'] = empty($payPwd)?0:1;
		$user['userPhone'] = empty($userPhone)?0:1;
		//$this->assign('user', $user);
		session('Edit_userPhone_Time', null);
    exit(jsonReturn('',1,$user));
		//return $this->fetch('users/security/index');
	}
	/**
	 * 修改登录密码
	 */
	public function editLoginPass(){
		$m = new M();
		$userId =  $this->getUserId();
		$user = $m->getById($userId);
		$loginPwd = $user['loginPwd'];
		$user['loginPwd'] = empty($loginPwd)?0:1;
    exit(jsonReturn('',1,$user));
		// $this->assign('user', $user);
		// return $this->fetch('users/security/user_login_pass');
	}
	public function editloginPwd(){
		$m = new M();
		$userId = $this->getUserId();
		return $m->editPass($userId);
	}
	/**
	 * 修改支付密码
	 */
	public function editPayPass(){
		$m = new M();
		$userId =  $this->getUserId();
		$user = $m->getById($userId);
		$payPwd = $user['payPwd'];
		$user['payPwd'] = empty($payPwd)?0:1;
    exit(jsonReturn('',1,$user));
		//$this->assign('user', $user);
		//return $this->fetch('users/security/user_pay_pass');
	}
	public function editpayPwd(){
		$m = new M();
		$userId = $this->getUserId();
		exit(json_encode($m->editPayPass($userId)));
	}
	/**
	 * 忘记支付密码
	 */
	public function backPayPass(){
		$m = new M();
		$userId =  $this->getUserId();
		$user = $m->getById($userId);
		$userPhone = $user['userPhone'];
		$user['userPhone'] = WSTStrReplace($user['userPhone'],'*',3);
		$user['phoneType'] = empty($userPhone)?0:1;
		$backType = (int)session('Type_backPaypwd');
		$timeVerify = session('Verify_backPaypwd_Time');
		$user['backType'] = ($backType==1 && time()<floatval($timeVerify)+10*60)?1:0;
    exit(jsonReturn('',1,$user));
		//$this->assign('user', $user);
		//return $this->fetch('users/security/user_back_paypwd');
	}
	/**
	 * 忘记支付密码:发送短信
	 */
	public function backpayCode(){
		$m = new MUsers();
		$data = $m->getById($this->getUserId());
		$userPhone = $data['userPhone'];
		$phoneVerify = rand(1000,9999);
		$rv = ['status'=>-1,'msg'=>'短信发送失败'];
		$tpl = WSTMsgTemplates('PHONE_FOTGET_PAY');
		if( $tpl['tplContent']!='' && $tpl['status']=='1'){
			$params = ['tpl'=>$tpl,'params'=>['code'=>$phoneVerify]];
			$m = new LogSms();
			$rv = $m->sendSMS(0,$userPhone,$params,'getPhoneVerifyt',$phoneVerify);
		}
		if($rv['status']==1){
			$USER = [];
			$USER['userPhone'] = $userPhone;
			$USER['phoneVerify'] = $phoneVerify;
			session('Verify_backPaypwd_info',$USER);
			session('Verify_backPaypwd_Time',time());
			exit(jsonReturn('短信发送成功!',1));
		}
		exit(json_encode($rv));
	}
	/**
	 * 忘记支付密码:验证短信
	 */
	public function verifybackPay(){
		$phoneVerify = input("post.phoneCode");
		$timeVerify = session('Verify_backPaypwd_Time');
		if(!session('Verify_backPaypwd_info.phoneVerify') || time()>floatval($timeVerify)+10*60){
			exit(jsonReturn("校验码已失效,请重新发送!"));
		}
		if($phoneVerify==session('Verify_backPaypwd_info.phoneVerify')){
			session('Type_backPaypwd',1);
			exit(jsonReturn("验证成功",1));
		}
		exit(jsonReturn("校验码不一致,请重新输入!"));
	}
	/**
	 * 忘记支付密码:重置密码
	 */
	public function resetbackPay(){
		$m = new M();
		exit(json_encode($m->resetbackPay()));
	}
	/**
	 * 修改手机
	 */
	public function editPhone(){
		$m = new M();
		$userId = $this->getUserId();
		$user = $m->getById($userId);
		$userPhone = $user['userPhone'];
		$user['userPhone'] = WSTStrReplace($user['userPhone'],'*',3);
		$user['phoneType'] = empty($userPhone)?0:1;
		//$this->assign('user', $user);
		session('Edit_userPhone_Time', null);
    exit(jsonReturn('',1,$user));
		//return $this->fetch('users/security/user_phone');
	}
	/**
	 * 绑定手机:发送短信验证码
	 */
	public function sendCodeTie(){
		$userPhone = input("post.userPhone");
        if(!WSTIsPhone($userPhone)){
            return jsonReturn("手机号格式不正确!");
            exit();
        }
        $rs = array();
        $m = new MUsers();
        $rs = WSTCheckLoginKey($userPhone,$this->getUserId());
        if($rs["status"]!=1){
            return jsonReturn("手机号已存在!");
            exit();
        }
        $data = $m->getById($this->getUserId());
        $phoneVerify = rand(1000,9999);
        $rv = ['status'=>-1,'msg'=>'短信发送失败'];
        $tpl = WSTMsgTemplates('PHONE_BIND');
        if( $tpl['tplContent']!='' && $tpl['status']=='1'){
            $params = ['tpl'=>$tpl,'params'=>['LOGIN_NAME'=>$data['loginName'],'VERFIY_CODE'=>$phoneVerify,'VERFIY_TIME'=>10]];
            $m = new LogSms();
            $rv = $m->sendSMS(0,$userPhone,$params,'sendCodeTie',$phoneVerify);
        }
        if($rv['status']==1){
            $USER = '';
            $USER['userPhone'] = $userPhone;
            $USER['phoneVerify'] = $phoneVerify;
            session('Verify_info',$USER);
            session('Verify_userPhone_Time',time());
            return jsonReturn('短信发送成功!',1);
        }
        exit(json_encode($rv));
    }
	/**
	 * 绑定手机
	 */
	public function phoneEdit(){
		$phoneVerify = input("post.phoneCode");
        $process = input("post.process");
        $timeVerify = session('Verify_userPhone_Time');
        if(!session('Verify_info.phoneVerify') || time()>floatval($timeVerify)+10*60){
            return jsonReturn("校验码已失效,请重新发送!");
            exit();
        }
        if($phoneVerify==session('Verify_info.phoneVerify')){
            $m = new M();
            $rs = $m->editPhone($this->getUserId(),session('Verify_info.userPhone'));
            exit(json_encode($rs));
        }
        return jsonReturn("校验码不一致,请重新输入!");
    }
	/**
	 * 修改手机:发送短信验证码
	 */
	public function sendCodeEdit(){
       $m = new MUsers();
       $data = $m->getById($this->getUserId());
       $userPhone = $data['userPhone'];
       $phoneVerify = rand(1000,9999);
       $rv = ['status'=>-1,'msg'=>'短信发送失败'];
       $tpl = WSTMsgTemplates('PHONE_EDIT');
       if( $tpl['tplContent']!='' && $tpl['status']=='1'){
          $params = ['tpl'=>$tpl,'params'=>['LOGIN_NAME'=>$data['loginName'],'VERFIY_CODE'=>$phoneVerify,'VERFIY_TIME'=>10]];
          $m = new LogSms();          
          $rv = $m->sendSMS(0,$userPhone,$params,'getPhoneVerifyt',$phoneVerify);
      }
      if($rv['status']==1){
          $USER = '';
          $USER['userPhone'] = $userPhone;
          $USER['phoneVerify'] = $phoneVerify;
          session('Verify_info2',$USER);
          session('Verify_userPhone_Time2',time());
          exit(jsonReturn('短信发送成功!',1));
      }
      exit(json_encode($rv));
}
	/**
	 * 修改手机
	 */
	public function phoneEdito(){
		$phoneVerify = input("post.phoneCode");
        $timeVerify = session('Verify_userPhone_Time2');
        if(!session('Verify_info2.phoneVerify') || time()>floatval($timeVerify)+10*60){
            return jsonReturn("校验码已失效,请重新发送!");
            exit();
        }
        if($phoneVerify==session('Verify_info2.phoneVerify')){
            session('Edit_userPhone_Time',time());
            exit(jsonReturn("验证成功",1));
        }
        exit(jsonReturn("校验码不一致,请重新输入!",-1));
    }
    public function editPhoneo(){
        $m = new M();
        $userId = $this->getUserId();
        $user = $m->getById($userId);
        $userPhone = $user['userPhone'];
        $user['userPhone'] = WSTStrReplace($user['userPhone'],'*',3);
        $timeVerify = session('Edit_userPhone_Time');
        if(time()>floatval($timeVerify)+15*60){
            $user['phoneType'] = 1;
        }else{
            $user['phoneType'] = 0;
        }
        $this->assign('user', $user);
        return $this->fetch('users/security/user_phone');
    }
	/**
	 * 用户退出
	 */
	public function logout(){
    model('users')->appLogOut($this->getUserId());
		return jsonReturn("",1);
	}

	/************************************************* 忘记密码 ********************************************************/
    // 页面过期/失效
    protected function expire($msg=''){
        $message = $msg?$msg:'页面已失效!';
        return jsonReturn($message,-1);
        //$html = '<h1>'.$message.'</h1><script>setTimeout(function(){location.href="'.url('app/users/index','','',true).'";},1000)</script>';
        //return $this->display($html);
    }
	 /**
     * 忘记密码
     */
     public function forgetPass(){
       return $this->fetch('forget_pass');
   }
   public function forgetPasst(){
       if(time()<floatval(session('findPass.findTime'))+30*60){
          $userId = session('findPass.userId');
          $m = new M();
          $info = $m->getUserInfo($userId,'loginName,userPhone');
          if($info['userPhone']!='')$info['userPhone'] = WSTStrReplace($info['userPhone'],'*',3);
          //if($info['userEmail']!='')$info['userEmail'] = WSTStrReplace($info['userEmail'],'*',2,'@');
          exit(jsonReturn('',1,$info));
      }else{
          exit($this->expire());
      }
  }

    /**
    * 重置密码
    */
    public function resetPass(){
       if(!session('findPass')){
        exit($this->expire());
    }
    return $this->fetch('forget_pass3');
}
public function forgetPasss(){
    if(!session('findPass')){
        exit($this->expire());
    }
    $USER = session('findPass');
    if(empty($USER) && $USER['userId']!=''){
      $this->expire('请在同一浏览器操作!');
  }
  $uId = session('findPass.userId');
  $key = session("findPass.key");
        // 验证邮箱中的验证码
  $secretCode = input('secretCode');
  if($key==$secretCode){
    session('REST_userId',$uId);
    session('REST_success','1');
    return jsonReturn('验证成功',1);
}else{
    return jsonReturn('校验码错误',-1);
}

}
    /**
     * 找回密码
     */
    public function findPass(){
    	//禁止缓存
    	header('Cache-Control:no-cache,must-revalidate');
    	header('Pragma:no-cache');
    	$code = input("post.verifyCode");
    	$step = input("post.step/d");
    	switch ($step) {
    		case 1:#第一步,验证身份
        //  if(!WSTVerifyCheck($code)){
        //     return jsonReturn('验证码错误!',-1);
        // }
        $loginName = input("post.loginName");
        $rs = WSTCheckLoginKey($loginName);
        if($rs["status"]==1){
            return jsonReturn("用户名不存在!");
            exit();
        }
        $m = new M();
        $info = $m->checkAndGetLoginInfo($loginName);
        if ($info != false) {
            session('findPass',array('userId'=>$info['userId'],'loginName'=>$loginName,'userPhone'=>$info['userPhone'],'userEmail'=>$info['userEmail'],'loginSecret'=>$info['loginSecret'],'findTime'=>time()));
            return jsonReturn("操作成功",1);
        }else return jsonReturn("用户名不存在!");
        break;
    		case 2:#第二步,验证方式
         if (session('findPass.loginName') != null ){
            if(input("post.modes")==1){
              if ( session('findPass.userPhone') == null) {
                  return jsonReturn('Error-10002:你没有预留手机号码,请联系客服找回密码!',-1);
              }
              $phoneVerify = input("post.Checkcode");
              if(!$phoneVerify){
                  return jsonReturn('校验码不能为空!',-1);
              }
              return $this->checkfindPhone($phoneVerify);
            }else{
              if (session('findPass.userEmail')==null) {
                  return jsonReturn('你没有预留邮箱,请通过联系客服找回密码!',-1);
              }
              if(!WSTVerifyCheck($code)){
                  return jsonReturn('验证码错误!',-1);
              }
              return $this->getfindEmail();
            }
        }else exit($this->expire());
        break;
    		case 3:#第三步,设置新密码
         $resetPass = session('REST_success');
         if($resetPass != 1)exit($this->expire());
         $loginPwd = input("post.loginPwd");
         $repassword = input("post.repassword");
         $decrypt_data = WSTRSA($loginPwd);
         $decrypt_data2 = WSTRSA($repassword);
         if($decrypt_data['status']==1 && $decrypt_data2['status']==1){
            $loginPwd = $decrypt_data['data'];
            $repassword = $decrypt_data2['data'];
        }else{
            return jsonReturn('设置失败');
        }
        if ($loginPwd == $repassword) {
            $m = new M();
            $rs = $m->resetPass();
            if($rs['status']==1){
               exit(json_encode($rs));
           }else{
               exit(json_encode($rs));
           }
       }else return jsonReturn('两次密码不同!',-1);
       break;
       default:
       exit($this->expire());
       break;
   }
}
    /**
     * 手机验证码获取
     */
    public function getfindPhone(){
        session('WST_USER',session('findPass.userId'));
        if(session('findPass.userPhone')==''){
            return jsonReturn('Error-10001:你没有预留手机号码,请联系客服找回密码!',-1);
        }
        $phoneVerify = rand(1000,9999);
        session('WST_USER',null);
        $rv = ['status'=>-1,'msg'=>'短信发送失败'];
        $tpl = WSTMsgTemplates('PHONE_FOTGET');
        if( $tpl['tplContent']!='' && $tpl['status']=='1'){
            $params = ['tpl'=>$tpl,'params'=>['code'=>$phoneVerify]];
            $m = new LogSms();
            $rv = $m->sendSMS(0,session('findPass.userPhone'),$params,'getPhoneVerify',$phoneVerify);
        }
        if($rv['status']==1){
            // 记录发送短信的时间,用于验证是否过期
            session('REST_Time',time());
            $USER = '';
            $USER['phoneVerify'] = $phoneVerify;
            $USER['time'] = time();
            session('findPhone',$USER);
            exit(jsonReturn('短信发送成功!',1));
        }
        exit(json_encode($rv));
    }
    /**
     * 手机验证码检测
     * -1 错误,1正确
     */
    public function checkfindPhone($phoneVerify){
    	if(!session('findPhone.phoneVerify') || time()>floatval(session('findPhone.time'))+10*60){
    		return jsonReturn("校验码已失效,请重新发送!");
    		exit();
    	}
    	if (session('findPhone.phoneVerify') == $phoneVerify ) {
    		$fuserId = session('findPass.userId');
    		if(!empty($fuserId)){
                session('REST_userId',$fuserId);
                session('REST_success','1');
                $rs['status'] = 1;
                $rs['url'] = url('app/users/resetPass');
                exit(json_encode($rs));
            }
            return jsonReturn('无效用户',-1);
        }
        return jsonReturn('校验码错误!',-1);
    }
    /**
     * 发送验证邮件/找回密码
     */
    public function getfindEmail(){
        $code = rand(0,999999);
        $sendRs = ['status'=>-1,'msg'=>'邮件发送失败'];
        $tpl = WSTMsgTemplates('EMAIL_FOTGET');
        if( $tpl['tplContent']!='' && $tpl['status']=='1'){
            $find = ['${LOGIN_NAME}','${SEND_TIME}','${VERFIY_CODE}','${VERFIY_TIME}'];
            $replace = [session('findPass.loginName'),date('Y-m-d H:i:s'),$code,30];
            $sendRs = WSTSendMail(session('findPass.userEmail'),'密码重置',str_replace($find,$replace,$tpl['content']));
        }
        if($sendRs['status']==1){
            $uId = session('findPass.userId');
            session("findPass.key", $code);
            // 发起重置密码的时间;
            session('REST_Time',time());
            return jsonReturn("发送成功",1);
        }else{
            return jsonReturn($sendRs['msg'],-1);
        }
    }
    /** 获取分享信息  mark cheng 20180320*/
   public function get_share(){
       $name = session('WST_USER.loginName');
       $data['url'] = 'http://www.juzi199.com/mobile/users/reg?pName='.$name;
       $data['bg_share'] = 'upload/sysconfigs/share_3.png';
       $data['title'] = '新会员注册,即送388元红包,10个ECT,马上注册吧!';
       $data['desc'] = '新会员注册,即送388元红包,10个ECT,马上注册吧!';
       exit(jsonReturn('',1,$data));
   }
   /*获取用户分享列表*/
    public function getShareList(){
        $m = new M();
        return $m->getShareList();
    }
  /**
  * 获取用户分享信息  * 
  */
  public function getShareInfo(){
      $m = new MUsers();
      return $m->getShareInfo();
  }


    public function setting_recive() {
        $userId =  $this->getUserId();
        if ($this->request->isPost()) {
            $data = [
                'realname'=>input('post.realname'),
                'bankName'=>input('post.bankName'),
                'bankNo'=>input('post.bankNo'),
                'alipayRecive'=>input('post.alipayRecive'),
                'wechatRecive'=>input('post.wechatRecive'),
            ];
            if(Db::name('user_recive')->where('userId', '=', $userId)->count() > 0) {
                Db::name('user_recive')->where('userId', '=', $userId)->update($data);
            } else {
                $data['userId'] = $userId;
                Db::name('user_recive')->insert($data);
            }
            return WSTReturn("成功", 1, $data);
        } else {
            $data = Db::name('user_recive')->where('userId', '=', $userId)->find();
            return WSTReturn("成功", 1, $data);
        }
    }

    public function unregister_get_sms_code() {
        $m = new MUsers();
        $data = $m->getById($this->getUserId());
        $userPhone = '15270565305';
//        $userPhone = $data['userPhone'];
        $phoneVerify = rand(1000,9999);
        $tpl = WSTMsgTemplates('PHONE_UNREGISTER');
        $rv = ['status'=>-1,'msg'=>'短信发送失败'];
        if( $tpl['tplContent']!='' && $tpl['status']=='1'){
            $params = ['tpl'=>$tpl,'params'=>['code'=>$phoneVerify]];
            $m = new LogSms();
            $rv = $m->sendSMS(0,$userPhone,$params,'unregister_get_sms_code',$phoneVerify);
            $rv['sms_code'] = $phoneVerify;
        }
        session('unreg.time', time());
        session('unreg.code', $phoneVerify);
        exit(json_encode($rv));
    }

    /**
     * 注销
     */
    public function unregister(){
        $m = new M();
        $userId =  $this->getUserId();
        $user = $m->getById($userId);
        if (empty($user)) exit(jsonReturn('系统异常',0,[]));
        $opUser = input('post.op_user');
        $opContent = input('post.op_content', '');
        $opPic = input('post.op_pic', '');

        if (empty($opUser)) {
            exit(jsonReturn('操作用户不能为空!',-1));
        }
        Db::startTrans();
        Db::name('user_unregister')->insert([
            'historyData'=>json_encode($user),
            'historyUserName'=>$user['loginName'],
            'op_user'=>$opUser,
            'op_content'=>$opContent,
            'op_pic'=>$opPic,
        ]);
        Db::name('user_lock')->insert([
            'lockTime'=>0,
            'lockReason'=>'账号已注销,操作人:'.$opUser.',注销申请内容:'.$opContent,
            'createTime'=>time(),
            'adminId'=>0,
            'userId'=>$userId,
        ]);
        $m->where('userId', '=', $userId)->update([
            'userStatus'=>0,
        ]);
        Db::commit();
        exit(jsonReturn('账号注销成功',1,[]));
    }
}