<?php
	namespace App\Http\Controllers;

	use Illuminate\Http\Request;
	use App\Http\Requests;
	use App\Http\Controllers\Controller;
	use DB;

	class PermController extends Controller 
	{
		// 获取用户角色
		public function getUserRole(Request $request) 
		{
			$uid   = $request->user->userId;
			$email = $request->user->email;

			if ($email == 'admin@ichunt.com') {
				return 1;
			}

			// 根据域名查询系统业务ID
			$domain = Config('website.order_url');

			$business = DB::table('t_business_config')->where('url', $domain)->first();

			if ($business) {
				$bid = $business->bid;

				// 权限系统配置的管理帐号
				$adminAccount = json_decode($business->admin, true);

				if (in_array($email, $adminAccount)) {
					return 1;
				}

				// 根据用户ID和业务ID查看角色
				$userPerm = DB::table('t_user_perm')->where(['userId' => $uid, 'bid' => $bid])->first();
				$role = json_decode($userPerm->roles, true);

				if (empty($role)) {
					return 0;
				} else {
					foreach ($role as $v) {
						$department = DB::table('t_role_perm')->where(['roleId' => $v, 'bid' => $bid])->first();

						if ($department->name == '管理员') {
							return 1;
						}else if ($department->name == '经理') {
							return 2;
						} else if ($department->name == '交易员') {
							return 3;
						} else {
							return 0;
						}
					}
				}
			}

			return 0;
		}

		// 获取所有角色用户集合
		public function getRoleUsers(Request $request, $roleName) 
		{
			// 根据域名查询系统业务ID
			$domain = Config('website.order_url');

			$business = DB::table('t_business_config')->where('url', $domain)->first();

			$userId = array();
			$roleUsers = array();

			if ($business) {
				$bid = $business->bid;

				$role = DB::table('t_role_perm')->where(['bid' => $bid, 'name' => $roleName])->first();

				$roleId = $role->roleId;

				$user = DB::select("SELECT * FROM `t_user_perm` WHERE `bid` = $bid AND `roles` REGEXP $roleId");

				if ($user) {
					foreach ($user as $v) {
						$userId[] = $v->userId;
					}

					if ($userId) {
						foreach ($userId as $id) {
							$userInfo = DB::table('user_info')->where('userId', $id)->first();

							// 判断用户是否已离职 4为离职状态
							if ($userInfo->status != 4) {
								$roleUsers[] = $userInfo;
							}

							continue;
						}
						
					}
				}
			}

			return $roleUsers;
		}

		// 获取权限系统用户的所有权限
		public function getUserPerms(Request $request, $uid)
		{
			// 根据域名查询系统业务ID
			$domain = Config('website.order_url');

			$business = DB::table('t_business_config')->where('url', $domain)->first();

			if ($business) {
				$bid = $business->bid;

				// 权限系统配置的管理帐号
				$adminAccount = json_decode($business->admin, true);

				$configs = Config('perm');

				// 若是管理员,则返回Config所有权限
				if (in_array($request->user->email, $adminAccount)) {
					return $configs;
				}

				// 获取用户权限
				$perms = json_decode($this->curlPermApi($uid, $bid), true);

				if ($perms['retcode'] == 0) {
					$userPerms = $perms['data']['perms'];				

					$matchPerms = $this->matchUserPerms($configs, $userPerms);

					return $matchPerms;
				}			
			}
			
			return false;
		}

		// 处理用户权限值
		public function handlePerms(Request $request, $uid) 
		{
			$perms = $this->getUserPerms($request, $uid);

			$userPerms = array();

			foreach ($perms as $perm) {
				if(is_array($perm)) {
					foreach ($perm as $val) {
						if (is_array($val)) {
							foreach ($val as $v) {
								$userPerms[] = $v;
							}
						}
					}
				}
			}

			return $userPerms;
		}

		/**
		 * 请求权限系统接口
		 * @param  [Integer] $uid [用户ID]
		 * @param  [Integer] $bid [业务ID]
		 * @return [Json]    返回权限数据
		 */
		public function curlPermApi($uid, $bid)
		{
			$url = Config('website.perm_api').$uid.'/'.$bid;

			$ch = curl_init();

			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_HEADER, 0);

			$result = curl_exec($ch);

			curl_close($ch);

			return $result;
		}

		/**
		 * 匹配用户在菜单的权限
		 * @param  [Array] $config [配置菜单权限]
		 * @param  [Array] $perms  [用户所有权限]
		 * @return [Json] 
		 */
		public function matchUserPerms($configs, $perms)
		{
			foreach ($configs as $key=>$config) {
				if (is_array($config)) {
					foreach($config as $k=>$v) {
						if (is_array($v)) {
							$menu[$key][$k] = array_intersect($v, $perms);
							continue;
						} else {
							if (in_array($v, $perms)) {
								$menu[$key][$k] = $v;
							}
							continue;
						}						
					}
				}

				continue;
			}

			return $menu;
		}


		/**
	     * 获取权限菜单
	     * @param  [Array] $menus [数据表菜单]
	     * @return [Array] 返回处理后的菜单 
	     */
	    public function getPermMenu(Request $request, $menus)
	    {
	        $menuPerm = $this->getUserPerms($request, $request->user->userId);

	        $menuData = array();
	        $newMenu = array();
	        $matchMenu = array();

	        if ($menuPerm) {
	            // 处理返回的菜单---简化
	            foreach ($menuPerm as $key => $val) {
	                if (is_array($val)) {
	                    // 处理二级菜单内容
	                    foreach ($val as $k => $v) {
	                        if (is_array($v)) {
	                            foreach ($v as $k1 => $v1) {
	                                if (preg_match('/_check/', $v1)) {
	                                    $menuData[$key][] = $k;
	                                    continue;
	                                }
	                            }
	                        } else {
	                            if (strpos($v, '_check') !== false) {
	                                $menuData[$key][] = $k;
	                                continue;
	                            } 
	                        }
	                    }
	                }
	            }
	 
	            // 匹配菜单
	            if ($menus) {
	                foreach ($menus as $k => $v) {
	                    // 遍历简化过的菜单
	                    foreach ($menuData as $pk => $pv) {
	                        // 匹配标题
	                        if ($pk == $v->title) {
	                            // 遍历对应标题下的子项
	                            foreach ($pv as $pk1 => $pv1) {
	                                if (is_array($v->childs) && !empty($v->childs)) {
	                                    foreach ($v->childs as $k1 => $v1) {
	                                        if ($pv1 == $v1->title) {
	                                            $childs[] = $v1;

	                                            $object = (object)[
	                                                'title'  =>  $v->title,
	                                                'href'   =>  $v->href,
	                                                'class'  =>  $v->class,
	                                                'childs' =>  $childs,
	                                            ];

	                                            $matchMenu[$k] = $object;

	                                            continue;
	                                        }
	                                    }
	                                } else {
	                                    $object = (object)[
	                                        'title'  =>  $v->title,
	                                        'href'   =>  $v->href,
	                                        'class'  =>  $v->class,
	                                        'childs' =>  $v->childs,
	                                    ];

	                                    $matchMenu[$k] = $object;
	                                    continue;
	                                }
	                            } 
	                            
	                            unset($childs); // 清除内容                          
	                        }
	                    }
	                }
	            }

	            // 重新组合数组
	            if ($matchMenu) {
	                foreach ($matchMenu as $v) {
	                    $newMenu[] = $v;
	                }
	            }
	        }

	        return $newMenu;
	    }

	}