<?php



/**

 * 会员中心

 */

namespace Phonegame\Controller;

use Common\Controller\PhonegameController;

class ProfileController extends PhonegameController {

	

	protected $users_model;

	function _initialize(){

		parent::_initialize();

		$this->users_model=D("Common/Users");

	}

	

    //编辑用户资料

	public function edit() {
		$userid=sp_get_current_userid();
		$user=$this->users_model->where(array("id"=>$userid))->find();
        $other=M('users_other')->where(array("uid"=>$userid))->find();
		$this->assign($user);
        if($other['province']!='0'){
        $other['pr'] = M('plugin_district')->where(array('id'=>$other['province'],'level'=>'1'))->getField('name');
        $other['ci'] = M('plugin_district')->where(array('id'=>$other['city'],'level'=>'2'))->getField('name');
        $other['di'] = M('plugin_district')->where(array('id'=>$other['district'],'level'=>'3'))->getField('name');
        $other['co'] = M('plugin_district')->where(array('id'=>$other['community'],'level'=>'4'))->getField('name');
        }else{
        $other['pr'] = '';
        $other['ci'] = '';
        $other['di'] = '';
        $other['co'] = '';
        }
        $hotgame = M("m_game")->where("isdisplay=1")->order('downloadnum desc')->limit('2')->getField('id,pic1,gametype,gamename,android_url_image,android_url,downloadnum');
        $this->assign("hotgame",$hotgame);
        $this->assign($other);
    	$this->display($this->template.'/template1'.'/User'.'/Profile'.'/edit');

    }

    

    public function edit_post() {
    	if(IS_POST){
    		$userid=sp_get_current_userid();
            $map['uid'] = $userid;
            $map['province'] = I('province');
            $map['city'] = I('city');
            $map['district'] = I('district');
            $map['community'] = I('community');
            $map['address'] = I('address');
            $map['zip_code'] = I('zip_code');
            $map['qq'] = I('qq');
            unset($_POST['province']);
            unset($_POST['city']);
            unset($_POST['district']);
            unset($_POST['community']);
            unset($_POST['address']);
            unset($_POST['zip_code']);
            unset($_POST['qq']);
    		$_POST['id']=$userid;
    		if ($this->users_model->create()) {
				if ($this->users_model->save()!==false) {
					$user=$this->users_model->find($userid);
                    $fal = M('users_other')->where(array("uid"=>$userid))->find();
                    if($fal){
                        M('users_other')->where(array("uid"=>$userid))->save($map);
                    }else{
                        M('users_other')->add($map);
                    }
					sp_update_current_user($user);
					$this->success("保存成功！",U("/profile/edit"));
				} else {
					$this->error("保存失败！");
				}
			} else {
				$this->error($this->users_model->getError());
			}
    	}
    }

    

    public function password() {

    	$userid=sp_get_current_userid();

    	$user=$this->users_model->where(array("id"=>$userid))->find();
        $hotgame = M("m_game")->where("isdisplay=1")->order('downloadnum desc')->limit('2')->getField('id,pic1,gametype,gamename,android_url_image,android_url,downloadnum');
        $this->assign("hotgame",$hotgame);

    	$this->assign($user);

    	$this->display($this->template.'/template1'.'/User'.'/Profile'.'/password');

    }

    

    public function password_post() {

    	if (IS_POST) {
    		if(empty($_POST['old_password'])){

    			$this->error("原始密码不能为空！");

    		}

    		if(empty($_POST['password'])){

    			$this->error("新密码不能为空！");

    		}

    		$uid=sp_get_current_userid();

    		$admin=$this->users_model->where("id=$uid")->find();

    		$old_password=$_POST['old_password'];

    		$password=$_POST['password'];

    		if(sp_compare_password($old_password, $admin['user_pass'])){

    			if($_POST['password']==$_POST['repassword']){

    				if(sp_compare_password($password, $admin['user_pass'])){

    					$this->error("新密码不能和原始密码相同！");

    				}else{

    					$data['user_pass']=sp_password($password);

    					$data['id']=$uid;

    					$r=$this->users_model->save($data);

    					if ($r!==false) {

    						$this->success("修改成功！");

    					} else {

    						$this->error("修改失败！");

    					}

    				}

    			}else{

    				$this->error("密码输入不一致！");

    			}

    	

    		}else{

    			$this->error("原始密码不正确！");

    		}

    	}

    	 

    }
   
    /**
     * 绑定邮箱
     * @author 顽皮蛋 <shf_l@163.com>
     */
    public function email() {
        $hotgame = M("m_game")->where("isdisplay=1")->order('downloadnum desc')->limit('2')->getField('id,pic1,gametype,gamename,android_url_image,android_url,downloadnum');
        $this->assign("hotgame",$hotgame);
       if (IS_POST) {
        $users_model=M("Users");
        $rules = array(
                //array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
                array('user_email', 'require', '邮箱不能为空！', 1 ),
                array('user_email','email','邮箱格式不正确！',1), // 验证email字段格式是否正确     
        );
        if($users_model->validate($rules)->create()===false){
            $this->error($users_model->getError());
        }
        $userid=sp_get_current_userid();
        $user=$this->users_model->where(array("id"=>$userid))->find();
        if($user['email_status']=='1')$this->error("邮箱已经绑定",U("/profile/email"));
        $email = I('user_email');
        $map['id'] = array('neq',$userid);
        $map['user_email'] =$email;
        $res=$this->users_model->where($map)->find();
        if($res)$this->error("邮箱已经存在",U("/profile/email"));
        $ucenter_syn=C("UCENTER_ENABLED");
        $uc_checkemail=1;
        if($ucenter_syn){
            include UC_CLIENT_ROOT."client.php";
            $uc_checkemail=uc_user_checkemail($email);
        }
        if($uc_checkemail<0)$this->error("邮箱已经存在",U("/profile/email"));
        $this->_send_to_bang($email);
        $users_model->where(array("id"=>$userid))->save(array("user_email"=>$email));
        $this->success("邮箱已发送，注意查收！",U("/profile/email"));
        }else{
            $userid=sp_get_current_userid();
            $user=$this->users_model->where(array("id"=>$userid))->find();
            $this->assign($user);
            $this->display($this->template.'/template1'.'/User'.'/Profile'.'/email');
        }
    }
    /**
     * 邮箱绑定返回操作
     * @author 顽皮蛋 <shf_l@163.com>
     */
    function active(){
        $hash=I("get.hash","");
        if(empty($hash)){
            $this->error("连接失效！");
        }
        $users_model=M("users_other");
        $find_user=$users_model->where(array("user_bang_key"=>$hash))->find();
        if($find_user){
            $result=$users_model->where(array("user_bang_key"=>$hash))->save(array("user_bang_key"=>""));
            M('users')->where(array("id"=>$find_user['uid']))->save(array("email_status"=>"1"));
            if($result){
                $this->success("邮箱绑定成功",__ROOT__."/");
            }else{
                $this->error("邮箱绑定失败!",U("/profile/email"));
            }
        }else{
            $this->error("邮箱绑定失败，绑定码无效！",U("user"));
        }
        
        
    }
    /*qq等第三方绑定*/
    function bang(){

    	$oauth_user_model=M("OauthUser");

    	$uid=sp_get_current_userid();

    	$oauths=$oauth_user_model->where(array("uid"=>$uid))->select();

    	$new_oauths=array();

    	foreach ($oauths as $oa){

    		$new_oauths[strtolower($oa['from'])]=$oa;

    	}

    	$this->assign("oauths",$new_oauths);

    	$this->display($this->template.'/template1'.'/User'.'/Profile'.'/bang');

    }

    

    function avatar(){

    	$userid=sp_get_current_userid();

		$user=$this->users_model->where(array("id"=>$userid))->find();
        $hotgame = M("m_game")->where("isdisplay=1")->order('downloadnum desc')->limit('2')->getField('id,pic1,gametype,gamename,android_url_image,android_url,downloadnum');
        $this->assign("hotgame",$hotgame);

		$this->assign($user);

    	$this->display($this->template.'/template1'.'/User'.'/Profile'.'/avatar');

    }


    function avatar_upload(){
    	$config=array(
    			'FILE_UPLOAD_TYPE' => sp_is_sae()?"Sae":'Local',//TODO 其它存储类型暂不考虑
    			'rootPath' => './'.C("UPLOADPATH"),
    			'savePath' => './avatar/',
    			'maxSize' => 512000,//500K
    			'saveName'   =>    array('uniqid',''),
    			'exts'       =>    array('jpg', 'png', 'jpeg'),
    			'autoSub'    =>    false,
    	);
    	$upload = new \Think\Upload($config);//
    	$info=$upload->upload();
    	//开始上传
    	if ($info) {
    	//上传成功
    	//写入附件数据库信息
    		$first=array_shift($info);
    		$file=$first['savename'];
    		$_SESSION['avatar']=$file;
    		$this->ajaxReturn(sp_ajax_return(array("file"=>$file),"上传成功！",1),"AJAX_UPLOAD");
    	} else {
    		//上传失败，返回错误
    		$this->ajaxReturn(sp_ajax_return(array(),$upload->getError(),0),"AJAX_UPLOAD");

    	}

    }

    

    function avatar_update(){
    	if(!empty($_SESSION['avatar'])){
    		$targ_w = intval($_POST['w']);
    		$targ_h = intval($_POST['h']);
    		$x = $_POST['x'];
    		$y = $_POST['y'];
    		$jpeg_quality = 90;
    		$avatar=$_SESSION['avatar'];
    		$avatar_dir=C("UPLOADPATH")."avatar/";
    		if(sp_is_sae()){//TODO 其它存储类型暂不考虑
    			$src=C("TMPL_PARSE_STRING.__UPLOAD__")."avatar/$avatar";
    		}else{
    			$src = $avatar_dir.$avatar;
    		}
    		$avatar_path=$avatar_dir.$avatar;
    		if(sp_is_sae()){//TODO 其它存储类型暂不考虑
    			$img_data = sp_file_read($avatar_path);
    			$img = new \SaeImage();
    			$size=$img->getImageAttr();
    			$lx=$x/$size[0];
            	$rx=$x/$size[0]+$targ_w/$size[0];
            	$ty=$y/$size[1];
            	$by=$y/$size[1]+$targ_h/$size[1];
    			$img->crop($lx, $rx,$ty,$by);
    			$img_content=$img->exec('png');
    			sp_file_write($avatar_dir.$avatar, $img_content);
    		}else{
    			$image = new \Think\Image();
    			$image->open($src);
    			$image->crop($targ_w, $targ_h,$x,$y);
    			$image->save($src);
    		}
    		$userid=sp_get_current_userid();
    		$result=$this->users_model->where(array("id"=>$userid))->save(array("avatar"=>$avatar));
    		$_SESSION['user']['avatar']=$avatar;
    		if($result){
    			$this->success("头像更新成功！");
    		}else{
    			$this->error("头像更新失败！");
    		}
    	}

    }

    

    

}

    

