<?php
/**
 * Created by PhpStorm.
 * User: duwenjun
 * Date: 2021/8/25
 * Time: 5:33 PM
 */

namespace App\Admin\Service;

use App\Models\Cms\CmsBusinessConfigModel;
use App\Models\Cms\CmsRolePermModel;
use App\Models\Cms\CmsUser;
use App\Models\Cms\CmsUserDepartmentModel;
use App\Models\Cms\CmsUserPermModel;
use Illuminate\Support\Facades\Log;

class PermService
{

    const SELF_SYSTEM_NAME = "深贸后台";

    const ROLE_ADMIN = 1; // 管理员角色

    const ROLE_SALE = 200; // 普通销售

    const ROLE_SALE_LEADER = 201; // 销售经理

    const ROLE_SALE_DIRECTOR = 202; // 销售总监

    const ROLE_NULL = 0;  // 未设置角色

    // 获取当前用户角色
    public static function getUserRoles($uid = 0, $email = "")
    {
        $admin = request()->get("user");
        $uid = $uid ?: $admin->userId;
        $email = $email ?: $admin->email;
//        dump($uid);
//        dump($email);
        // 如果是管理员邮箱,直接返回管理员角色
        if ($email == 'admin@ichunt.com') {
            return [self::ROLE_ADMIN];
        }

        // 根据域名查询系统业务ID
        $business = self::getBusinessInfo();
        if (!$business) {
            return [];
        }
        $bid = $business['bid'];

        // 权限系统配置的管理帐号, 如果是权限系统中配置的管理员邮箱,直接返回管理员角色
        $adminAccount = json_decode($business['admin'], true);
        if (in_array($email, $adminAccount)) {
            return [self::ROLE_ADMIN];
        }

        // 根据用户ID和业务ID查看角色
        $userPerm = CmsUserPermModel::getUserPermByUidAndBid($uid, $bid);
        if (empty($userPerm)) {
            return [];
        }

        // 没有选择角色
        if ($userPerm['roles'] == 'null') {
            return [];
        }

        $role_list = [];
        $role_ids = json_decode($userPerm['roles'], true);
        if ($role_ids) {
            $role_perm_list = CmsRolePermModel::getRolePermInfosByRoleIds($role_ids, $bid);
            if ($role_perm_list) {
                $role_name_list = array_column($role_perm_list, 'name');
                foreach ($role_name_list as $role_name) {
                    if (isset(self::$role_name_map[$role_name])) {
                        $role_list[] = self::$role_name_map[$role_name];
                    }
                }
            }
        }

        return $role_list;
    }
    // 获取用户所有权限
    public static function getUserPerms()
    {
        $userAllPermList = [];
        $business = self::getBusinessInfo();
        //获取用户单独的权限
        if (isset($business['bid'])) {
            $bid = $business['bid'];
            $userPerm = CmsUserPermModel::getUserPermByUidAndBid(request()->user->userId, $bid);//获取用户权限信息
            if ($userPerm && isset($userPerm['perms'])) {
                $userPermList = json_decode($userPerm['perms']);
                if (is_array($userPermList)) {
                    $userAllPermList = array_merge($userAllPermList, $userPermList);
                }
            }
        }
        //获取用户所在角色的权限
        $rolePermList = [];
        if (isset($userPerm['roles'])) {
            $roleIds = json_decode($userPerm['roles'], true);//用户所有的角色
            if ($roleIds) {
                $rolePermData = CmsRolePermModel::getRolePermInfosByRoleIds($roleIds, $bid);
                if ($rolePermData) {
                    foreach ($rolePermData as $param) {//获取用户的角色权限
                        $arrParam = json_decode($param['perms']);
                        $rolePermList = array_merge($rolePermList, $arrParam);
                    }
                }
            }
        }
        $userAllPermList = array_merge($userAllPermList, $rolePermList);

        if (empty($userAllPermList)) {
            Log::error("该用户未配置权限,请联系管理员,uid:" . request()->user->userId);
        }
        return $userAllPermList;
    }

    // 判断用户是否拥有某角色
    public static function hasRole($role, $role_list)
    {
        return in_array($role, $role_list);
    }


    // 判断用户是否拥有某权限
    public static function hasPerm($perm_id)
    {
        $user_perms = self::getUserPerms();
        return in_array($perm_id, $user_perms);
    }



    // 获取系统信息
    public static function getBusinessInfo()
    {
        return CmsBusinessConfigModel::getInfoByTitle(self::SELF_SYSTEM_NAME);
    }



    // 获取指定用户下级所有人员
    public static function getSubUserId($userId)
    {
        $sub_user_ids = [];
        array_unshift($sub_user_ids, $userId); // 将当前用户添加到数组

        $user_info = CmsUser::getInfoByUserId($userId);

        if (empty($user_info) || !$user_info['department_id']) {
            return $sub_user_ids;
        }

        // 获取所有下级部门
        $department_ids = self::_getDepartmentIds($user_info['department_id']);
        // 获取下级部门的人员
        $sub_user_ids = CmsUser::getUserIdsByDepartmentIds($department_ids);
        return array_unique($sub_user_ids);
    }

    // 获取查询的部门id,查询销售和采购部门下所有子部门的ids
    // 这里要使用循环的查询方法,如果改部门下面还有子部门,那么一并查询,最终合并用户子部门id集
    public static function _getDepartmentIds($top_department_id)
    {
        $all_department_ids = $next_department_ids = [$top_department_id];
        while ($next_department_ids) {
            $next_department_ids = CmsUserDepartmentModel::getDepartmentIdsParrentIds($next_department_ids);
            $all_department_ids = array_merge($all_department_ids, $next_department_ids);
        }
        return $all_department_ids;
    }


}