<?php
namespace app\ucentre\service\local;

use app\ucentre\model\WendidUser;
use wendasns\Wend;
use think\helper\Str;
use think\Exception;

class WendidUserApi
{
	//获取用户信息
	public static function getUser(array $account)
	{
		$dm = WendidUser::where($account[0], $account[1])->find();
		if(!$dm){
			throw new \think\Exception('用户不存在');
		}
    	return $dm;
	}
	
	//添加账号
	public static function addUser(array $data)
	{
    	$sql = [
    		['username','=',$data['username']]
    	];
    	if(!empty($data['email'])) $sql[] = ['email','=',$data['email']];
    	if(!empty($data['mobile'])) $sql[] = ['mobile','=',$data['mobile']];
    	$dm = WendidUser::whereOr($sql)->find();
    	if($dm){
    		if($dm->username==$data['username']) throw new Exception('用户名已经存在');
    		if($dm->email==$data['email']) throw new Exception('邮箱已被注册');
    		if($dm->mobile==$data['mobile']) throw new Exception('手机号已被注册');
    	}
		$data['password'] = Wend::userpass($data['password'], $data['salt']);
    	$dm = WendidUser::create($data);
    	$dm->infos()->save([]);
    	$user = $dm->users()->save([
    		'username' => $data['username'],
    		'password' => md5(Str::random(6)),
    		'email' => $data['email'],
    		'mobile' => $data['mobile'],
    		'create_time' => $data['create_time'],
    	]);
    	return $user;
	}
	
	//编辑用户
	public static function editUser(array $data)
	{

		$dm = WendidUser::find($data['id']);
		if(!$dm){
			throw new Exception('用户不存在');
		}
		if(!empty($data['password'])){
			$salt = Str::random(6);
			$dm->salt = $salt;
    		$dm->password = Wend::userpass($data['password'], $salt);
		}
    	if(!empty($data['email']) && $dm->email!=$data['email']){
    		if(WendidUser::getByEmail($data['email'])) Exception('该邮箱已经被注册');
    		$dm->email = $data['email'];
    	}
    	
    	if(!empty($data['mobile']) && $dm->mobile!=$data['mobile']){
    		if(WendidUser::getByMobile($data['mobile'])) Exception('该手机号已经被注册');
    		$dm->mobile = $data['mobile'];
    	}
		$dm->save();
		return $dm;
	}
	
	//删除用户
	public static function deleteUser(array $data)
	{
		$dm = WendidUser::with(['infos','logins'])->select($data['uid']);
		foreach($dm as $v){
			$v->together(['infos','logins'])->delete();
		}
		$dm->delete();
	}
}