<?php
namespace app\ucentre\service;

use app\ucentre\model\User;
use app\ucentre\model\Member;
use app\ucentre\model\WendidUser;
use wendasns\facade\Wendid;
use think\helper\Str;

use wendasns\Wend;
use think\facade\Request;
use think\Exception;

class PwUser
{
	protected $data= [];//中间数组
	
	//检查账号
	public function checkAccount($account)
	{
		//手机号
    	if(preg_match("/^1[34578]{1}\d{9}$/", $account)){
    		$sql[] = ['mobile','=',$account];
    	}elseif(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/", $account)){
    		$sql[] = ['email','=',$account];
    	}else{
    		$sql[] = ['username','=',$account];
    	}

    	//独立系统
    	if(configure('wendid.system')=='local'){
    		$dm = User::where($sql)->find();
    	}else{
    		try{
    		$dm = Ucentre::get($account);
    		}catch (\Exception $e) {
    			
    		}
    	}
    	if($dm->id){
    		return true;
    	}
    	return false;
	}
	
	//获取用户信息
	public static function getUserInfo($uid)
	{
		$user = byUser::find($uid);
		if(!$user){
			return [];
		}
		$user_data = $user->datas()->hidden(['user_id'])->find();

        $user = $user->toArray();
        $user['data'] = $user_data;

        return $user;
	}
	
	//登录模式
	public function mode($type)
	{
		switch ($type){
			case 1:
				$obj = new \app\ucentre\service\login\Authorize();
				break;
			default:
				$obj = new \app\ucentre\service\login\Local();
		}
		$obj->account = $this->account;
		$obj->password = $this->password;
		$obj->rememberme = $this->rememberme;
		return $obj;
	}
	
	//注册
	public function register()
	{
		$create_time = Wend::getTime();
		$data = [
			'username' => $this->username,
			'password' => $this->password,
			'salt' => Str::random(6),
			'email' => $this->email,
			'mobile' => $this->mobile,
			'register_ip' => Request::ip(),
			'create_time' => $create_time
		];

    	//
    	$mode = configure('wendid.system');
    	if(!in_array($mode,['local','client'])){
    		throw new Exception('错误');
    	}
    	$class_name = 'app\\ucentre\\service\\'.$mode.'\\WendidUserApi';
    	$dm = invoke([$class_name, 'addUser'], ['data'=>$data]);
    	$this->id = $dm->id;
    	event('EndRegister', ['uid'=>$dm->id]);
    	return $this;
	}
	
	//编辑用户
	public function update()
	{
		$className = '\\app\\'.request()->app.'\\model\\User';
		$user = $className::find($this->id);
    	if(!$user){
    		throw new Exception('用户不存在');
    	}
    	if(!empty($this->password)){
    		$user->password = md5(Str::random(6));
    	}
    	
    	if(!empty($this->email) && $user->email!=$this->email){
    		if($className::getByEmail($this->email)) throw new Exception('该邮箱已经被注册');
    		$user->email = $this->email;
    	}
    	if(!empty($this->mobile) && $user->mobile!=$this->mobile){
    		if($className::getByMobile($this->mobile)) throw new Exception('该手机号已经被注册');
    		$user->mobile = $this->mobile;
    	}

    	$user->save();
    	
    	$this->data['id'] = $user->wend_id;
    	
    	$mode = configure('wendid.system');
    	if(!in_array($mode,['local','client'])){
    		throw new Exception('错误');
    	}
    	$class_name = 'app\\ucentre\\service\\'.$mode.'\\WendidUserApi';
    	$dm = invoke([$class_name, 'editUser'], ['data'=>$this->data]);
    	return $user;
	}

	//删除用户
	public function delete()
	{
		$className = '\\app\\'.request()->app.'\\model\\User';
		$dm = User::with(['froms','datas','behaviors'])->select($this->id);
		$uid = [];
		foreach($dm as $v){
			$uid[] = $v->wend_id;
			$v->together(['froms','datas','behaviors'])->delete();
		}
		$dm->delete();
		$data = [
			'uid' => $uid
		];
    	$mode = configure('wendid.system');
    	if(!in_array($mode,['local','client'])){
    		throw new \think\Exception('错误');
    	}
    	$class_name = 'app\\ucentre\\service\\'.$mode.'\\WendidUserApi';
    	invoke([$class_name, 'deleteUser'], ['data'=>$data]);
	}
	
	//上传认证
	public static function uploadAuth($path, $uid=0)
	{
		$uid = $uid ? $uid : request()->loginUser->uid;
		list($width, $height, $type, $attr) = getimagesize($path);
		$new_wh = ['mini'=>30,'middle'=>100,'big'=>168];
		$root = root_path();
		switch ($type){
			case 1://gif
				$src = imagecreatefromgif($path);
				$suffix = 'gif';
				$fun = 'imagegif';
				break;
			case 2://jpg
				$src = imagecreatefromjpeg($path);
				$suffix = 'jpg';
				$fun = 'imagejpeg';
				break;
			case 3://png
				$src = imagecreatefrompng($path);
				$suffix = 'png';
				$fun = 'imagepng';
				break;
			default:
				return false;
		}
		foreach($new_wh as $k=>$v){
			$paint = imagecreatetruecolor($v, $v);
			imagecopyresampled($paint, $src, 0,0,0,0, $v, $v, $width, $height);
			$l = sprintf('%supload\auth\%s_%s.%s', $root, $uid, $suffix);
			imagejpeg($paint, $l);
			imagedestroy($paint);
		}
		imagedestroy($src);
	}

	//编辑
	public function edit(int $uid, array $data = [])
	{
		$email = isset($data['email'])?$data['email']:'';
		$mobile = isset($data['mobile'])?$data['mobile']:'';
		$dm = User::where('id',$uid)->whereOr('email',$email)->whereOr('mobile',$mobile)->select();
		if(count($dm)==0){
			return new Exception('用户不存在');
		}
		
		$error = '';
		if($email || $mobile){
			foreach($dm as $v){
				if($email==$v->email && $uid<>$v->id){
					$error = '邮箱已被使用';
					break;
				}
				if($mobile==$v->mobile && $uid<>$v->id){
					$error = '手机号已被使用';
					break;
				}
				$user = $v;
			}
		}
		
		if($error){
			return new Exception($error);
		}
		if(isset($data['password'])){
			$salt = Str::random(6);
			$data['salt'] = $salt;
    		$data['password'] = $this->password($data['password'], $salt);
		}
		$user->save($data);
		return true;
	}
	
    public function __set($name, $value) {
        $this->data[$name] = $value;
        $this->$name = $value;
    }
}