<?php

namespace app\wendasns\service;

use think\facade\Log;
use app\wendasns\model\Question;
use app\wendasns\model\Category;
use app\wendasns\model\Allow;
use app\wendasns\model\User;
use app\wendasns\model\Member;
use app\wendasns\model\Sign;
use app\wendasns\model\Realname;
use app\wendasns\model\UserauthInfo;
use app\ucentre\service\PwUser as byUser;
use wendasns\facade\Wendid;
use wendasns\Wend;
use think\helper\Str;
use think\Exception;

class PwUser
{
	protected $data= [];
	
	//添加用户
	public function save()
	{
        $dm = new byUser();
        $dm->username = $this->username;
        $dm->password = $this->password;
        $dm->email = $this->email;
        $dm->mobile = $this->mobile;
        $dm->register();
        
    	$create_time = Wend::getTime();
    	$user = User::create([
    		'wend_id' => $dm->id,
    		'username' => $dm->username,
    		'password' => md5(Str::random(6)),
    		'email' => $dm->email,
    		'mobile' => $dm->mobile,
    		'create_time' => $create_time,
    	]);
    	$status = configure('register.validate')?0:1;
    	$user->members()->save(['group_id'=>$this->group,'status'=>$status]);
    	$user->datas()->save([]);
    	$user->behaviors()->save(['action'=>'register','create_time'=>$create_time]);
    	//钩子-注册后
    	event('EndRegister', ['uid'=>$user->id]);
	}

	//编辑用户
	public function update()
	{
        $user = new byUser();
        $user->id = $this->id;
        $user->password = $this->password;
        $user->email = $this->email;
        $user->mobile = $this->mobile;
        $user = $user->update();

    	if(!empty($this->data['password'])){
    		$user->password = md5(Str::random(6));
    	}
    	
    	if(!empty($this->data['email']) && $user->email!=$this->email){
    		if(User::getByEmail($this->email)) throw new Exception('该邮箱已经被注册');
    		$user->email = $this->email;
    	}
    	if(!empty($this->data['mobile']) && $user->mobile!=$this->mobile){
    		if(User::getByMobile($this->mobile)) throw new Exception('该手机号已经被注册');
    		$user->mobile = $this->mobile;
    	}
    	
    	$user->members->group_id = $this->group;
    	isset($this->admin) && $user->members->admin_id = $this->admin;
    	$user->members->status = $this->status;
    	$user->members->auths = $this->auths;
    	$user->members->save();
    	$user->save();

	}
	
    public function getUserData()
    {
    	$dm = User::find($this->id);
    	if(!$dm){
    		throw new \think\Exception('用户不存在');
    	}
    	$dm->data = $dm->datas()->find();
    	return $dm;
    }
    
	//记录用户操作
	public function setBehavior($action, $sourceid, $status = 'visible')
	{
		$dm = Behavior::create([
			'user_id' => $this->uid,
			'source_id' => $sourceid,
			'action' => $action,
			'create_time' => Wend::getTime(),
			'status' => $status
		]);
	}
	
	//wd_user_data表数据自增
	public function setInc($item, $value = 1)
	{
		Data::where('user_id', $this->uid)->inc($item, $value)->update();
	}

	//wd_user_data表数据自减
	public function setDec($item, $value = 1)
	{
		Data::where('user_id', $this->uid)->dec($item, $value)->update();
	}
	
	//权限检查
	public static function action_check(int $uid, string $keys)
	{
		$dm = User::find($uid);
		if($dm->status=='check'){
			return new \think\Exception('账号审核中，无法提问');
		}
    	$rkey = strtr($keys,['.'=>'_']);
    	$dm = Allow::where('group_id',$dm->group_id)->where('rkey',$rkey)->find();
    	if(!$dm || $dm->rvalue==0){
    		return new \think\Exception('没有权限');
    	}
        return true;
	}

	public function login($dm)
	{
		$status = configure('register.validate')?0:1;
        $user = User::where('wend_id', $dm->id)->find();
        if(!$user){
    		$user = User::create([
    			'wend_id' => $dm->id,
    			'username' => $dm->username,
    			'email' => $dm->email,
    			'password' => md5(Str::random(6)),
    			'create_time' => Wend::getTime()
    		]);
    		$user->members()->save(['group_id'=>1,'status'=>$status]);
    		$user->datas()->save([]);
        }else{
        	$member = Member::where('user_id',$user->id)->find();
        	if(!$member){
        		$user->members()->save(['group_id'=>1,'status'=>$status]);
        		$user->datas()->save([]);
        	}
        }
        
        $user->logins()->save([
			'mode' => $dm->mode,
			'client' => request()->isMobile()?'手机':'电脑',
			'system' => getSystem(),
			'loginip' => request()->ip(),
			'create_time' => Wend::getTime()
		]);
		
		$realname = Realname::where('user_id',$user->id)->find();
		if(!$realname){
			Realname::create(['user_id'=>$user->id]);
		}
		$UserauthInfo = UserauthInfo::where('user_id',$user->id)->find();
		if(!$UserauthInfo){
			UserauthInfo::create(['user_id'=>$user->id]);
		}

        $password = Wend::md5pwd($user->password);
    	$identity = Wend::strEncrypt($user->id."\t".$password);
        $expire = $dm->rememberme ? 31536000 : null;
        cookie('WendaUser',$identity,['expire'=>$expire]);
        //钩子-登录后
    	event('EndLogin', ['uid'=>$user->id]);
	}

	//获取活跃用户
	public static function getActive($limit)
	{
		$dm = Sign::distinct(true)->field('user_id')->whereWeek('create_time')->paginate($limit);
		return $dm;
	}
	
    public function __set($name, $value) {
        $this->data[$name] = $value;
        $this->$name = $value;
    }
}