<?php
// +----------------------------------------------------------------------
// | yershop网店管理系统
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://www.yershop.com All rights reserved.
// +----------------------------------------------------------------------
// | 版权申明：yershop网店管理系统不是一个自由软件，是贝云网络官方推出的商业源码，严禁在未经许可的情况下
// | 拷贝、复制、传播、使用yershop网店管理系统的任意代码，如有违反，请立即删除，否则您将面临承担相应
// | 法律责任的风险。如果需要取得官方授权，请联系官方http://www.yershop.com
// +----------------------------------------------------------------------
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Session;
use think\Request;

/**
 * 用户控制器
 * 包括用户中心，用户登录及注册
 */
class User extends Base {
    public function index(){
        if(!is_login()) {
		    $this->redirect( "User/login");
		}	
      	
        $Order=new \app\index\model\Order;
		$res=$Order->getPageList(3,"id desc") ;
		//查询条件
		$info=$res["info"];
        $this->assign('info',$info);
		//dump($info);
		unset($res["info"]);
		//分页数据
        $this->assign('res',$res);
		$this->meta_title ="个人中心";
		$uid=session_uid();	
		$map['uid']=$uid;//用户id
		$list=db("address")->where($map)->order("id desc")->select();
		$num=0;
		if($list){
			$num=count($list);										
		}
		$order[1]=db("order")->where("status",1)->order("id desc")->count();
		$order[2]=db("order")->where("status",2)->order("id desc")->count();
		$order[3]=db("order")->where("status",3)->order("id desc")->count();
		$this->assign('num', $num);
		$this->assign('order', $order);
		$this->assign('meta_title',$this->meta_title);
		return $this->fetch();
    }
   public function edit(){
        if(!is_login()) {
		    $this->redirect( "User/login");
		}		
        if($_POST){ //提交表单
		   $id=input('id'); 	
           if(!($id && is_numeric($id))){
		       $this->error('用户ID错误！');
		   } 
		   $uid=is_login();	
		   if($id!=$uid){
			  $this->error('用户ID不匹配！'); 
		   }
		   $map["id"]=$id;
		   $info=db("User")->where($map)->find();
		   if(!$info){
			   $this->error( "无对应的用户".$uid );
		   }
	  	    $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);
            }
        } 	   
		$list=explode("|",api('STAR'));
		$this->assign('list',$list);
		$this->meta_title ="个人中心";
		$this->assign('meta_title',$this->meta_title);
		return $this->fetch();
    }
  
	/* 注册页面 */
	public function register($mobile = "", $password = "", $repassword = "", $email = "", $verify = ""){
	
		if($_POST){ //注册用户
		    if(!api("USER_ALLOW_REGISTER")){
                 $this->error("注册已关闭");
             }
            $user=new \app\common\model\User; 
			
		    $res=$user->register();
			if($res){
				  $url= session("url")?session("url"):url('index/index');
			      $this->success("注册成功",$url);
			}else{
			   $this->error($user->getError());
			}

		} 
		else { 	
			
	      $meta_title = '会员注册'; 
		  session("url",null);
		  $url=input('server.HTTP_REFERER');
          session("url",$url); 
		  $code=$this->random();
          session("send_code",$code);
			$this->assign('code',$code);
		  $this->assign('meta_title',$meta_title);
		  return $this->fetch();
		}
	}
    	
/* 手机号注册页面 */
    public function reg($mobile = "", $password = "", $repassword = "", $send_code =""){
	
		if($_POST){ //注册用户
		     if(!api("USER_ALLOW_REGISTER")){
                 $this->error("注册已关闭");
             }
			 $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(($mobile!==$_SESSION['mobile'])&&($send_code!==$_SESSION['mobile_code'])){
				$this->error("验证码输入错误！");
			}   
             $password =safe_replace($_POST["password"]);//过滤
			 if(!$password){
			    $this->error("密码不能为空！");
			 }
			 if(strlen($password)<6) {
              $this->error("密码必须包含至少含有6个字符！");
               
             } 
			 $repassword =input("repassword");//过滤
			 if($repassword){ 
			    $repassword =safe_replace($_POST["repassword"]);//过滤
			 } 
             if(!$repassword){
			    $this->error("确认密码不能为空！");
			 }
			 if($repassword!==$password) {
                 $this->error("密码与确认密码不符合！");
              
                 
			 }  
			
            $user=new \app\common\model\User; 
			
		    $res=$user->reg();
			if($res){
				  $url= session("url")?session("url"):url('index/index');
			      $this->success("注册成功",$url);
			}else{
			   $this->error($user->getError());
			}

		} 
		else { 	
			
	      $meta_title = '会员注册'; 
		  session("url",null);
		  $url=input('server.HTTP_REFERER');
          session("url",$url);
          $code=$this->random();
          session("send_code",$code);
			$this->assign('code',$code);
		  $this->assign('meta_title',$meta_title);
		  return $this->fetch("user/reg");
		}
	}
	/* 登录页面 */
	public function login(){
		
		if($_POST){ 
			
		    $user=new \app\common\model\User; 
		    $res=$user->login();
			if($res){
				  $url= session("url")?session("url"):url('index/index');
			      $this->success("登录成功",$url);
			}else{
			   $this->error($user->getError());
			}

		}else {
             if(is_login()){
			   $this->redirect("index/index");
		     }
             session("url",null);
		     $url=input('server.HTTP_REFERER');
             session("url",$url); 
			 $code=$this->random();
          session("send_code",$code);
			$this->assign('code',$code);
		     $this->meta_title = '登录';	
			//显示登录表单
			 return $this->fetch();
		}
	}
  

    public function forget($username = "", $password = ""){
		
		    session("send_code",$this->random());
			$this->assign('code',session("send_code"));
			return $this->fetch();
		
	}

	/* 退出登录 */
	public function logout(){
		if(is_login()){
			$Member =model("Member");
			$Member->logout();
			$this->redirect("index/index");
		} else {
			$this->redirect("User/login");
		}
	}



	
  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 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 sendSms() {
	
	$mobile = $_POST['mobile'];
    $send_code = $_POST['send_code'];
	if(!session('send_code')||$send_code!=session('send_code')){
		//防用户恶意请求
		$this->error('请求超时，请刷新页面后重试');
	}
	if(empty($mobile)){
		$this->error('手机号码不能为空');
	}
    sendSms($mobile);//发送短信

}
     public function confirm($mobile = '', $verify = ''){
		
		if($_POST){ //注册用户
			/* 检测验证码 */
			if(($mobile!==$_SESSION['mobile'])&&($verify!==$_SESSION['mobile_code'])){
				$this->error("动态码输入错误！");
			} 
			else{
                $this->success("验证成功！");
            }
			
		}
	}



    public function xml_to_array($xml){
		$arr=array();
		$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 update(){
		if(!is_login()) {
		    $this->redirect( "User/login");
		}
        if ($_POST) {
            
             //获取参数
            $uid        =   is_login();
            $password   =  safe_replace( input("post.old"));
            $repassword =safe_replace(input("post.repassword"));
            $data["password"] = safe_replace(input("post.password"));
            
            empty($password) && $this->error("请输入原密码");
            $password   =  md5(sha1( input("post.old")).config('database.key'));
            $where["password"] = $password;
			$where["id"] = $uid;
            $res = db('User')->where($where)->find();
            if(!$res){
                $this->error("原密码错误！");
            }

            empty($data["password"]) && $this->error("请输入新密码");
            empty($repassword) && $this->error("请输入确认密码");
            if($data["password"] !== $repassword){
                $this->error("您输入的新密码与确认密码不一致");
            }
			$map["id"]=$uid;
            $data['password']=md5(sha1($repassword).config('database.key'));
            $res = db('User')->where($map)->field('password')->update($data);
            if($res){
                $this->success("修改密码成功！");
            }else{
                $this->error("修改失败");
            }
        }
    }

}
