<?php
/**
* @author 龙虾 <15108148@qq.com>
* @version 2.0 2020-11-10
* @copyright 睿谷信息 <www.rgxx.com>
*/
namespace app\user\controller;

use app\common\model\User as UserModel;
use Request;
use Db;

class Index extends Base
{
	// 首页
	public function index()
	{
		$pagetitle = '会员首页';
		return $this->fetch('',compact('pagetitle'));
	}

	// 登陆
	public function login($returnUrl='')
	{
		if(Request::isPost())
		{
			Request::filter(['trim','strip_tags','htmlspecialchars']);
			$data = Request::only(['captcha','username','password','__token__'], 'post');
			if(empty($data['captcha'])) {
                $this->error('请填写验证码');
            }
            if(!captcha_check($data['captcha'])) {
                $this->error("验证码错误");
            }
			$validate = new \think\Validate;
			$rule = ['username|用户名或手机号' => 'require','password|密码' => 'require|alphaNum|min:6','__token__' => 'token'];
			$validate->rule($rule);
			if (!$validate->check($data)) {
				$this->error($validate->getError());
			}
			$hasUser = UserModel::hasWhere('usergroup',['Usergroup.status' => 1])->where('username|mobile',$data['username'])->where('User.status',1)->find();
			if(!$hasUser) $this->error('登陆失败');
			$password = md5($data['password'].$hasUser['salt']);
			if($password == $hasUser['password']) {
				$map = [
				'logincount' => $hasUser['logincount'] + 1,
				'ip' => getIp(),
				'update_time' => time()
				];
				UserModel::where('id',$hasUser['id'])->update($map);
				session('userid',$hasUser['id']);
				$goto = empty($returnUrl) ? uUrl('user','index','index') : base64_decode($returnUrl);
				$this->success('登陆成功',$goto);
			} else {
				$this->error('登陆失败');
			}
		}
		$pagetitle = '用户登录';
		return $this->fetch('',compact('pagetitle'));
	}

	// 找回密码
	public function forgot()
	{
		if(Request::isPost())
		{
			if(!config('app.email.email')) $this->error('系统未开启邮件功能');
			Request::filter(['trim','strip_tags','htmlspecialchars']);
			$data = Request::only(['captcha','email','__token__'], 'post');
			if(empty($data['captcha'])) {
                $this->error('请填写验证码');
            }
            if(!captcha_check($data['captcha'])) {
                $this->error("验证码错误");
            }
			$validate = new \think\Validate;
			$rule = ['email|电子邮箱' => 'require|email','__token__' => 'token'];
			$validate->rule($rule);
			if (!$validate->check($data)) {
				$this->error($validate->getError());
			}
			$hasUser = UserModel::whereEmail($data['email'])->find();
			if(!$hasUser) $this->error('无此用户');
			$find_code = random(10,'string');
			$find_cache_info = json_encode(['find_code' => $find_code,'find_time' => time()]);
			cache('userid_'.$hasUser['id'],$find_cache_info,1200); // 缓存找回信息
			$find_url = uUrl('user','index','reset',[],true,true).'?userid='.$hasUser['id'].'&token='.rg_encode($find_cache_info);
			$email_content = '用户名：'.$hasUser["username"].'<Br>邮箱：'.$hasUser['email'].'<Br>重置密码链接(有效期20分钟)：<a href="'.$find_url.'">'.$find_url.'</a>';
			if(sendMail($hasUser['email'],'密码重置：'.$this->siteinfo['name'],$email_content)) {
				$this->success('请至邮件中重置密码');
			} else {
				$this->error('找回失败');
			}
			
		}
		$pagetitle = '找回密码';
		return $this->fetch('',compact('pagetitle'));
	}

	// 重置密码
	public function reset($userid='',$token='')
	{
		if(empty($userid) || empty($token)) $this->error('禁止访问');
		if(!cache('?userid_'.$userid)) $this->error('页面过期');
		$userinfo = UserModel::get($userid);
		$find_cache = json_decode(cache('userid_'.$userid),true);
		$find_info = json_decode(rg_decode($token),true);
		if(time()-$find_info['find_time']>1200 || $find_info['find_code'] !== $find_cache['find_code']) $this->error('页面过期');
		// 表单提交
		if(Request::isPost()) {
			Request::filter(['trim','strip_tags','htmlspecialchars']);
			$data = Request::only(['captcha','password','password_confirm','__token__'], 'post');
			if(empty($data['captcha'])) {
                $this->error('请填写验证码');
            }
            if(!captcha_check($data['captcha'])) {
                $this->error("验证码错误");
            }
			$validate = new \think\Validate;
			$rule = ['password|密码' => 'require|confirm|alphaNum|min:6','__token__' => 'token'];
			$validate->rule($rule);
			if (!$validate->check($data)) {
				$this->error($validate->getError());
			}
			$password = md5($data['password'].$userinfo['salt']);
			$result = UserModel::where('id',$userinfo['id'])->update(['password' => $password]);
			cache('userid_'.$userid,NULL);
			if ($result) {
				$this->success('密码重置成功',uUrl('user','index','login'));
			} else {
				$this->error('密码重置失败');
			}
		}
		$pagetitle = '重置密码';
		return $this->fetch('',compact('pagetitle'));
	}

	// 退出登陆
	public function loginout()
	{
		session('userid',NULL);
		session('session_start_time_user',NULL);
		$this->relogin();
	}

	// 注册
	public function reg()
	{
		if(!config('app.user.userregon')) $this->error('系统禁止注册');
		if(Request::isPost())
		{
			Request::filter(['trim','strip_tags','htmlspecialchars']);
			$data = Request::only(['captcha','username','password','password_confirm','agree','__token__'], 'post');
			if(empty($data['captcha'])) {
                $this->error('请填写验证码');
            }
			$validate = new \think\Validate;
			$rule = ['username|用户名' => 'require|unique:user|alphaNum|min:5','password|密码' => 'require|confirm|alphaNum|min:6','agree|服务协议' => 'accepted','__token__' => 'token'];
			$validate->rule($rule);
			if (!$validate->check($data)) {
				$this->error($validate->getError());
			}
			// $smscookie = cookie('smsreg_'.$data['mobile']);
			// if(!$smscookie) {
			// 	$this->error('验证码过期');
			// }
			// if($data['code']!==$smscookie['code']) {
			// 	$this->error('验证码错误');
			// }
			$data['face'] = '/public/static/images/face/01.png'; // 头像
			$data['usergroup_id'] = config('app.user.userreggroup'); // 默认分配组
			$data['status'] = config('app.user.userregcheck') ? 0 : 1; // 审核
			if(!captcha_check($data['captcha'])) {
                $this->error("验证码错误");
            }
            $data['salt'] = random();
			$data['password'] = md5(trim($data['password']).$data['salt']);
			$result = UserModel::create($data,true);
			if ($result) {
				session('userid',$result->id);
				$this->success('注册成功',uUrl('user','index','index'));
			} else {
				$this->error('注册失败');
			}
		}
		$pagetitle = '用户注册';
		return $this->fetch('',compact('pagetitle'));
	}

	// 会员信息
	public function userinfo()
	{
		if(Request::isPost()) {
			Request::filter(['trim','strip_tags','htmlspecialchars']);
			$data = Request::only(['id' => session('userid'),'face','nickname','mobile','address','sex'], 'post');
			$validate = new \think\Validate;
			$rule = ['nickname|昵称' => 'require|unique:user|chsAlphaNum|min:2','email|电子邮箱' => 'unique:user|email','mobile|手机号' => 'unique:user|mobile'];
			$validate->rule($rule);
			if (!$validate->check($data)) {
				$this->error($validate->getError());
			}
			$userinfo = UserModel::get(session('userid'));
			$result = $userinfo->allowField(true)->save($data);
			if ($result) {
				$this->success('修改成功');
			} else {
				$this->error('修改失败');
			}
		}
		$pagetitle = '个人信息';
		return $this->fetch('',compact('pagetitle'));
	}

	// 上传头像
	public function uploadImg()
    {
    	if(Request::isPost()) {
    		$data = Request::post();
    		halt($data);
    		//获取文件对象
	        $file = $this->request->file('file');
	        //验证并上传
	        $info = $file->validate(['size'=>config("app.upload.imageAllowFiles"),'ext'=>'jpg,gif,png'])
	            ->move('/upload/user/');
	        //判断是否成功
	        if($info){
	            $data['src'] = '/upload/user/'.$info->getSaveName();
	            $this->success('上传成功',$data);
	        }else{
	            $this->error('上传失败');
	        }
    	}
        
    }

	// 修改密码
	public function changepwd()
	{
		if(Request::isPost())
		{
			Request::filter(['trim','strip_tags','htmlspecialchars']);
			$data = Request::only(['captcha','l_password','n_password','n_password_confirm'], 'post');
			if(empty($data['captcha'])) {
                $this->error('请填写验证码');
            }
            if(!captcha_check($data['captcha'])) {
                $this->error("验证码错误");
            }
			$validate = new \think\Validate;
			$rule = ['n_password|新密码' => 'require|confirm|alphaNum|min:6'];
			$validate->rule($rule);
			if (!$validate->check($data)) {
				$this->error($validate->getError());
			}
			// 验证密码
			$userinfo = UserModel::get(session('userid'));
			if(md5(trim($data['l_password']).$userinfo['salt']) == $userinfo['password']) {
				$n_password = md5(trim($data['n_password']).$userinfo['salt']);
				$result = $userinfo->save(['password' => $n_password]);
				if ($result) {
					session('userid',NULL);
					$this->success('密码修改成功，请重新登陆');
				} else {
					$this->error('修改失败');
				}
			} else {
				$this->error("当前账户密码错误");
			}
		}
		$pagetitle = '修改密码';
		return $this->fetch('',compact('pagetitle'));
	}

	// 邮箱绑定
	public function setemail()
	{
		if(!cookie('?userid_'.session('userid').'_setemail')) {
			$step = 1;
			if(Request::isPost())
			{
				if(!config('app.email.email')) $this->error('系统未开启邮件功能');
				Request::filter(['trim','strip_tags','htmlspecialchars']);
				$data = Request::only(['captcha','n_email'], 'post');
				if(empty($data['captcha'])) {
	                $this->error('请填写验证码');
	            }
				$validate = new \think\Validate;
				$rule = ['n_email|邮箱' => 'require|email|unique:user,email'];
				$validate->rule($rule);
				if (!$validate->check($data)) {
					$this->error($validate->getError());
				}
				if(!captcha_check($data['captcha'])) {
	                $this->error("验证码错误");
	            }
				// 生成验证码并发送
				$setemail_code = random(5,'string');
				$setemail_cache_info = rg_encode(json_encode(['email' => $data['n_email'],'code' => $setemail_code,'userid' => session('userid')]));
				cookie('userid_'.session('userid').'_setemail',$setemail_cache_info,1200);
				if(sendMail($data['n_email'],'邮箱绑定：'.$this->siteinfo['name'],'当前绑定的邮箱：'.$data['n_email'].'<br>激活码：'.$setemail_code.'(有效期20分钟)')) {
					$this->success('激活邮件发送成功，请至邮件中查看');
				} else {
					$this->error('激活邮件发送失败');
				}
			}
		} else {
			$step = 2;
			if(Request::isPost())
			{
				Request::filter(['trim','strip_tags','htmlspecialchars']);
				$action = Request::post('action');
				if($action == 'reset') {
					cookie('userid_'.session('userid').'_setemail',NULL);
					$this->success('重置设置成功');
				}
				$email_code = Request::post('email_code');
				if(!$email_code) $this->error('请输入激活码');
				if(!cookie('?userid_'.session('userid').'_setemail')) $this->error('操作超时');
				$setemail_cache_info = json_decode(rg_decode(cookie('userid_'.session('userid').'_setemail')),true);
				if($email_code!==$setemail_cache_info['code']) $this->error('激活码错误');
				$result = UserModel::where('id',$setemail_cache_info['userid'])->update(['email' => $setemail_cache_info['email']]);
				if ($result) {
					cookie('userid_'.session('userid').'_setemail',NULL);
					$this->success('邮箱绑定成功');
				} else {
					$this->error('邮箱绑定失败');
				}
			}
		}
		
		$pagetitle = '邮箱绑定';
		return $this->fetch('',compact('pagetitle','step'));
	}

}