<?php
// +----------------------------------------------------------------------
// | yershop网店管理系统
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://www.yershop.com All rights reserved.
// +----------------------------------------------------------------------
// | 版权申明：yershop网店管理系统不是一个自由软件，是贝云网络官方推出的商业源码，严禁在未经许可的情况下
// | 拷贝、复制、传播、使用yershop网店管理系统的任意代码，如有违反，请立即删除，否则您将面临承担相应
// | 法律责任的风险。如果需要取得官方授权，请联系官方http://www.yershop.com
// +----------------------------------------------------------------------
namespace app\index\controller;
use think\Db;
/**
 * 会员模型控制器
 */
class Safe extends Home {
	
    public function index(){
        if(!is_login()) {
		    $this->error( "您还没有登陆",url("User/login") );
		}		
        $uid=is_login(); 
		$map["id"]=$uid;
        $info=db("user")->where($map)->find();
		$this->assign('info',$info);
		$this->meta_title ="个人中心";
		$this->assign('meta_title',$this->meta_title);
		return $this->fetch();
    }
	
   public function edit(){
        if(!is_login()) {
		    $this->error( "您还没有登陆",url("User/login") );
		}		
       
		
		$this->meta_title ="验证身份";
		$this->assign('meta_title',$this->meta_title);
		session("send_code",$this->random());	
		$this->assign('code',session("send_code"));
		return $this->fetch();
    }
	
	 public function mobile(){
        if(!is_login()) {
		    $this->error( "您还没有登陆",url("User/login") );
		}
        $uid=is_login(); 
		$map["id"]=$uid;		
         if($_POST){
			 $mobile=isset($_POST["mobile"])?safe_replace($_POST["mobile"]):"";//过滤
             if(empty($mobile)){
		         $this->error('手机号码不能为空');
	         } 
             if(!preg_match("/1[34578]{1}\d{9}$/",$mobile)){
			  	      $this->error("手机号格式不正确！");
			 }	
			 $data["mobile"]=$mobile;
             if(Db::name("User")->where($data)->select())	{
				 $this->error("手机号已存在！");            				 
			 }	
			 $send_code=isset($_POST["send_code"])?safe_replace($_POST["send_code"]):"";//过滤
			 /* 检测验证码 */
			 if(!$send_code){
				$this->error("验证码不能为空！");
			}if(!isset($_SESSION['mobile_code'])){
				$this->error("验证码发送失败！");
			}
            if($send_code!==$_SESSION['mobile_code']){
				$this->error("验证码输入错误！");
			} 
			$User= new \app\index\model\User; 
            $field=["mobile"];			
		    $res=$User->allowField($field)->save($data,$map);
			 if(false !== $res){               
		         $this->success("绑定成功");
            } else {
                $error= $User->getError();
                $this->error(empty($error) ? '未知错误！' : $error);
            }
			
		}
		
        $info=db("user")->where($map)->find();
		$this->assign('info',$info);
		 if($info["mobile"]) {
		    $this->error( "已绑定",url("safe/index") );
		}	
		$this->meta_title ="绑定手机号";
		$this->assign('meta_title',$this->meta_title);
		session("send_code",$this->random());	
		$this->assign('code',session("send_code"));
		return $this->fetch();
    }
	
	public function over(){
        if(!is_login()) {
		    $this->error( "您还没有登陆",url("User/login") );
		}		
        
		$list=explode("|",api('STAR'));
		$this->assign('list',$list);
		$this->meta_title ="修改完成";
		$this->assign('meta_title',$this->meta_title);
		session("send_code",$this->random());	
		$this->assign('code',session("send_code"));
		return $this->fetch("end");
    }
	
	 public function bind(){
        if(!is_login()) {
		    $this->error( "您还没有登陆",url("User/login") );
		}		
        if($_POST){
			
			$send_code=isset($_POST["send_code"])?safe_replace($_POST["send_code"]):"";//过滤
			/* 检测验证码 */
			if(!$send_code){
				$this->error("验证码不能为空！");
			}if(!isset($_SESSION['mobile_code'])){
				$this->error("验证码发送失败！");
			}
            if($send_code!==$_SESSION['mobile_code']){
				$this->error("验证码输入错误！");
			} 
			session('step',2);
			$url=url("safe/bind");
		    $this->success("提交成功",$url);
		}
		
		$this->meta_title ="修改手机号码";
		$this->assign('meta_title',$this->meta_title);
		session("send_code",$this->random());	
		$this->assign('code',session("send_code"));
		return $this->fetch();
    }
	
	//发送验证码
     public function send($length = 6 , $numeric = 0,$verify="") {
	     if(!is_login()) {
		    $this->error( "您还没有登陆",url("User/login") );
		}	
			$mobile = $_POST['mobile'];		
			$mobile_code =$this-> random(4,1);
			if(empty($mobile)){
				$this->error('手机号码不能为空');
			}
			$send_code=input('send_code');
			if(!session('send_code')||$send_code!=session('send_code')){
				//防用户恶意请求
				$this->error('请求超时，请刷新页面后重试');
			}
			sendSms($mobile);
    }
	
	public function verify(){
		 if(!is_login()) {
		    $this->error( "您还没有登陆",url("User/login") );
		}	
		if($_POST){
			
			 
             $mobile=isset($_POST["mobile"])?safe_replace($_POST["mobile"]):"";//过滤
             if(empty($mobile)){
		         $this->error('手机号码不能为空');
	         } 
             if(!preg_match("/1[34578]{1}\d{9}$/",$mobile)){
			  	      $this->error("手机号格式不正确！");
			 }	
			 $data["mobile"]=$mobile;
             if(!Db::name("user")->where($data)->find())	{
				 $this->error("手机号不存在！");            				 
			 }	
			 
			 $send_code=isset($_POST["send_code"])?safe_replace($_POST["send_code"]):"";//过滤
			/* 检测验证码 */
			if(!$send_code){
				$this->error("验证码不能为空！");
			} 
            if(($mobile!==$_SESSION['mobile'])&&($send_code!==$_SESSION['mobile_code'])){
				$this->error("验证码输入错误！");
			} 
			 $field=["mobile"];
		     $map["id"]=is_login();
		     $res=model("User")->allowField($field)->save($data,$map);
			session('mobile',$mobile);
			session('username',$username);
			session('step',2);
			$url=url("safe/over");
		    $this->success("提交成功",$url); 
		}
	
	}
	//发送验证码
    public function sendSms($length = 6 , $numeric = 0,$verify="") {
	 if(!is_login()) {
		    $this->error( "您还没有登陆",url("User/login") );
		}
	$uid=is_login();
	$user=db("User")->find($uid);    
	$mobile = $user['mobile'];
    $map["mobile"]=safe_replace($mobile);
	
	$target = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
	
	$send_code = $_POST['send_code'];
	$mobile_code =$this-> random(4,1);
	if(empty($mobile)){
		$this->error('手机号码不能为空');
	}
	if(!session('send_code')||$send_code!=session('send_code')){
		//防用户恶意请求
		$this->error('请求超时，请刷新页面后重试');
	}
    $u=api('HUYIUSERNAME');
	$p=api('HUYIPASSWORD');
	$post_data = "account={$u}&password={$p}&mobile=".$mobile."&content=".rawurlencode("您的验证码是：".$mobile_code."。请不要把验证码泄露给其他人。");

	//密码可以使用明文密码或使用32位MD5加密
	$gets = $this->xml_to_array($this->Post($post_data, $target));
	if($gets['SubmitResult']['code']==2){
		$_SESSION['mobile'] = $mobile;
		$_SESSION['mobile_code'] = $mobile_code;
		$this->success($gets['SubmitResult']['msg']);
	}else{
	    $this->error($gets['SubmitResult']['msg']);
	}

    }  

      public   function Post($curlPost,$url){
	    $url = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_NOBODY, true);
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
		$return_str = curl_exec($curl);
		curl_close($curl);
		return $return_str;
}
	 public function xml_to_array($xml){
		$reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
		if(preg_match_all($reg, $xml, $matches)){
			$count = count($matches[0]);
			for($i = 0; $i < $count; $i++){
			$subxml= $matches[2][$i];
			$key = $matches[1][$i];
				if(preg_match( $reg, $subxml )){
					$arr[$key] = $this->xml_to_array( $subxml );
				}else{
					$arr[$key] = $subxml;
				}
			}
		}
		return $arr;
   }
	   public  function random($length = 6 , $numeric = 0) {
	PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
	if($numeric) {
		$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
	} else {
		$hash = '';
		$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
		$max = strlen($chars) - 1;
		for($i = 0; $i < $length; $i++) {
			$hash .= $chars[mt_rand(0, $max)];
		}
	}
	return $hash;
}
	
    public  function update() {
        if(!is_login()) {
			$this->error( "您还没有登陆",url("User/login") );
		}		
	    if($_POST){ //提交表单
		   $id=input('id'); 	
           if(!($id && is_numeric($id))){
		       $this->error('用户ID错误！');
		   }
		   $map["id"]=$id;
		   $info=db("User")->where($map)->find();
		   if(!$info){
			   $this->error( "无对应的用户" );
		   }
	  	   $User= new \app\index\model\User; 
		 $data=array();
        foreach($_POST as $key=>$val){
		      $data[$key]=safe_replace($val);
             
		}
           $field=["mobile","username","birthday","star","sex","cover_id"];
		  $res=model("User")->allowField($field)->save($data,$map);
		
            if(false !== $res){
                $this->success('更新成功！');
            } else {
               $error= $User->getError();
                $this->error(empty($error) ? '未知错误！' : $error);
            }
        } 	    
    }
}
