<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------
namespace app\services\auth;

use app\model\auth\Users;
use app\model\auth\RolesAccess;
use think\facade\Config;

class UsersService{
    
	/**
	 * @title 获取管理员列表
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function getUserList($request){
		$auth = $request->auth();
		$param = $request->param();
		$map = [];
		if(isset($param['name']) && $param['name']){
			$map[] = ["username|nickname", "like", "%{$param['name']}%"];
		}
		if(isset($param['department_id']) && $param['department_id']){
			$map[] = ["department_id", "IN", getDepartmentChild($param['department_id'])];
		}
		if(isset($param['role_id']) && $param['role_id']){
			$exp = is_array($param['role_id']) ? "IN" : "=";
			$subMap = [['role_id', $exp, $param['role_id']]];
			$map[] = ['uid', "IN", function($q) use($subMap){
				$q->name('user_has_roles')->where($subMap)->field('uid');
			}];
		}
		$list = Users::with(['roles', 'department'])->auth([])->where($map)->order('uid desc')->paginate($request->pageConfig)->each(function($item){
			$roleId = [];
            $roleName = [];
			$identify = [];
			foreach($item->roles as $val){
				$roleId[] = $val['id'];
                $roleName[] = $val['title'];
				$identify[] = $val['identify'];
			}
			$item->role_id = $roleId;
			$item->roleName = $roleName;
			$item->identify = $identify;
		});
		return $list;
	}
	/**
	 * 创建用户
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function createUsers($request){
		$param = $request->param();
		$data = [
			'username' => $param['username'],
			'nickname' => $param['nickname'],
			'password' => $param['password'],
			'department_id' => $param['department_id']
		];
		
		$user = Users::create($data);
		return $user;
	}
	/**
	 * @title 批量导入
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function insertAll($request){
		$data = $request->param('data');
		$users = [];
		foreach($data as $item){
			$user = Users::where('uid', $item['XH'])->findOrEmpty();
			if($user->isEmpty()){
				$users = [
					'uid' => $item['XH'],
					'username' => $item['XH'],
					'nickname' => $item['XM'],
					'password' => md5(''),
					'email' => "e@mail.cn",
					'avatar' => $this->request->domain() . str_replace("/pic", "/", $item['RXZP']),
					'creator_id' => 1,
					'department_id' => 3,
					'user_type' => $item['PYCC'],
					'status' => 1,
					'sex' => $item['XB'],
					'xueyuan' => $item['XY'],
					'student_class' => $item['BJMC'],
				];
				Users::create($users);
			}
		}
		return $users;
	}
	public function updateUsers($request){
		$param = $request->param();
		$roles = isset($param['role_id']) ? $param['role_id'] : [];
		$user = Users::where('uid', '=', $param['uid'])->findOrEmpty();
		if(!$user->isEmpty()){
			if(isset($param['nickname']) && $param['nickname']){
				$data['nickname'] = $param['nickname'];
			}
			if(isset($param['email']) && $param['email']){
				$data['email'] = $param['email'];
			}
			if(isset($param['avatar']) && $param['avatar']){
				$data['avatar'] = $param['avatar'];
			}
			if(isset($param['department_id']) && $param['department_id']){
				$data['department_id'] = is_array($param['department_id']) ? end($param['department_id']) : $param['department_id'];
			}
			$user->save($data);
		}
		if(!empty($roles)){
			$this->updateRoles($param['uid'], $roles);   //更新角色
		}
		
		return false;
	}

	public function updateUserPassword($request){
		$user = Users::where('uid', '=', $request->user['uid'])->findOrEmpty();
		$params = $request->param();
		if(!$user->isEmpty()){
			if(password_verify($params['oldpassword'], $user->password)){
				$user->save(['password' => $params['password']]);
			}else{
				throw new \think\Exception("当前密码错误！", 1);
			}
		}
	}

	/**
	 * @title 获取用户权限信息
	 *
	 * @return void
	 */
	public function getUserAuth($uid){
		$user = Users::with(['roles', 'roles.permissions', 'department'])->where('uid', '=', $uid)->findOrEmpty();
		if(!$user->isEmpty()){
			$permission = [];
			$apiList = [];
			$data_range = [];
			$mobile_module = [];
			foreach ($user->roles as $role) {
				$data_range[] = $role['data_range'];
				$mobile_module = array_merge($mobile_module, $role['mobile_module']);
				foreach($role->permissions as $item){
					$permission[] = $item['name'];
					$apiList = array_merge($apiList, $item['api_list']);
				}
			}
			$user['permission'] = $permission;
			$user['data_range'] = isset($data_range[0]) ? $data_range[0] : 1;   //暂时适配到过角色的数据权限问题 后续调整
			$user['mobile_module'] = $mobile_module;
			$user['apiList'] = $apiList;
			return $user;
		}else{
			return false;
		}
	}
	public function userInfo($uid){
		$user = $this->getUserAuth($uid);
		return $user->append(['access_token']);
	}
	/**
	 * @title 更新用户角色
	 *
	 * @param int $uid
	 * @param array $roles
	 * @param int $manage_class   用户班级权限
	 * @return void
	 */
	public function updateRoles($uid, $roles, $manage_class = 0){
		RolesAccess::where('uid', '=', $uid)->delete();
		$save = [];
		foreach ($roles as $role) {
			$save[] = ['role_id' => $role, 'uid' => $uid];
		}
		(new RolesAccess())->saveAll($save);
		if($uid && $manage_class){
			Users::update(['manage_class' => $manage_class], ['uid' => $uid]);
		}
		return true;
	}
}