<?php


namespace App\Services;


use App\Menu;
use App\UserVisitMenuLog;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use App\Traits\ServiceAppAop;


class CheckActiveMenuService
{
    use ServiceAppAop;
    protected $modelClass=CheckActiveMenu::class;
    /**
     *同步数据到数据库并且将L1转移到L2
     */
    public static function sync()

    {
        try {
            self::syncToDB();
            self::switchL1ToL2();
        } catch (\Exception $e) {
            // 同步异常的处理策略
            return;
        }
    }

    /**
     * 将用户菜单点击事件保存
     * @param Request $request
     */
    public static function set(Request $request): void
    {
        // 请求方法为get
        $userId = Auth::user()['id']??null;
        if(!$userId)return;
        if ($request->method() == 'GET') {
            $menu = Cache::remember('menu:route:'.$request->getRequestUri()
                ,config('cache.expirations.rarelyChange')
                ,function()use($request){
                    return Menu::query()->where('route', substr($request->getRequestUri(), 1))->first();
                });
            if ($menu) {
                //redis正常保存在缓存中
                $date = date('Y-m-d H:i:s');
                $userVisitMenuLog = new UserVisitMenuLog([
                    'user_id' => $userId,
                    'menu_id' => $menu->id,
                    'created_at' => $date,
                    'updated_at' => $date,
                ]);
                try {
                    //菜单点击入缓存
                    Redis::LPUSH('UserVisitMenuLogsL1', $userVisitMenuLog);
                } catch (\Exception $e) {
                    //缓存异常的处理策略
                    $userVisitMenuLog->save();
                }
            }
        }
    }

    /**
     * 获取活跃菜单
     * @return Builder|Builder[]|\Illuminate\Database\Eloquent\Collection|Model|null
     */
    public static function activeMenus()
    {
        $user_id = self::getUserId();
        $result = collect();
        try {
            Redis::LLEN('UserVisitMenuLogsL1');
            if (Redis::LLEN('UserVisitMenuLogsL1') + Redis::LLEN('UserVisitMenuLogsL2') > 0) {
                //缓存中有数据
                $result= self::getFromRedis($user_id);
            }else{
                $result= self::getFromDB($user_id);
            }
        } catch (\Exception $e) {
            //缓存异常的处理策略
            $result=self::getFromDB($user_id);
        }

        $result = self::filterRepetitionMenu($result);
        return $result;
    }

    /**
     * 将缓存中的数据拿出保存，转换为数组，方便数据库保存
     * @param $userVisitMenuLogsStr
     * @return array
     */
    public static function redisListToArray($userVisitMenuLogsStr): array
    {
        $userVisitMenuLogsArr = [];
        foreach ($userVisitMenuLogsStr as $userVisitMenuLog) {
            $userVisitMenuLogObj = json_decode($userVisitMenuLog);
            $userVisitMenuLogsArr[] = [
                'user_id' => $userVisitMenuLogObj->user_id,
                'menu_id' => $userVisitMenuLogObj->menu_id,
                'created_at' => $userVisitMenuLogObj->created_at,
                'updated_at' => $userVisitMenuLogObj->updated_at,
            ];
        }
        return $userVisitMenuLogsArr;
    }

    /**
     *将L1缓存转移到L2
     */
    public static function switchL1ToL2(): void
    {
        while (Redis::LLEN('UserVisitMenuLogsL1') > 0) {
            Redis::LPUSH('UserVisitMenuLogsL2', Redis::LPOP('UserVisitMenuLogsL1'));
        }
    }

    /**
     * @return int
     */
    public static function getUserId(): int
    {
        $user_id = 1;
        if (Auth::user()) {
            $user_id = Auth::user()->id;
        }
        return $user_id;
    }

    /**
     * 从数据库获取活跃菜单
     * @param $user_id
     * @return Builder|Builder[]|\Illuminate\Database\Eloquent\Collection|Model|null
     */
    public static function getFromDB($user_id)
    {
        return self::getMenusAndSort(self::getMenuIdsFromDB($user_id));
    }

    /**
     * 从缓存获取活跃菜单
     * @param $user_id
     * @return Builder|Builder[]|\Illuminate\Database\Eloquent\Collection|Model|null
     */
    public static function getFromRedis($user_id)
    {
        return self::getMenusAndSort(self::getMenuIdsFromRedis($user_id));
    }

    /**
     * 获取活跃菜单并按照活跃度排序
     * @param Collection $menuIds
     * @return Builder|Builder[]|\Illuminate\Database\Eloquent\Collection|Model|Collection|\Tightenco\Collect\Support\Collection|null
     */
    public static function getMenusAndSort(Collection $menuIds)
    {
        return self::buildResult(self::getMenusAndSortByActive($menuIds));
    }

    /**
     * @param $user_id
     * @return Collection|\Tightenco\Collect\Support\Collection
     */
    public static function getMenuIdsFromRedis($user_id)
    {
        return collect(array_merge(self::redisListToArray(Redis::LRANGE('UserVisitMenuLogsL1', 0, -1)), self::redisListToArray(Redis::LRANGE('UserVisitMenuLogsL2', 0, -1))))
            //从缓存中查找全部用户的活跃菜单数据，合并L1，L2
            ->filter(function ($item) use ($user_id) {
                return $user_id === $item['user_id'];
            })
            //根据user_id筛选
            ->groupBy('menu_id')
            //根据menu_id分组
            ->sortByDesc(function ($item) {
                return $item->count();
            })
            //根据分组结果的二级列表降序排列
//            ->forPage(0, 5)
            //取前数量最高的五条
            ->keys();
        //只获取对应的菜单Id
    }

    /**
     * @param $user_id
     * @return Builder[]|\Illuminate\Database\Eloquent\Collection|Collection
     */
    public static function getMenuIdsFromDB($user_id)
    {
        return UserVisitMenuLog::query()
            ->selectRaw('menu_id')
            ->where('user_id', $user_id)
            ->groupBy('menu_id')
            ->get()->sortByDesc(function ($item) {
                return $item->count();
            })
//            ->forPage(0, 5)
            ->map(function ($item) {
                return $item->menu_id;
            });
    }

    public static function syncToDB(): void
    {
        UserVisitMenuLog::query()->insert(self::redisListToArray(Redis::LRANGE('UserVisitMenuLogsL1', 0, -1)));
    }

    /**
     * 将排好序的菜单集合构造为一级菜单嵌套二级菜单的形式
     * @param $menus
     * @return Collection|\Tightenco\Collect\Support\Collection
     */
    public static function buildResult($menus)
    {
        $result = collect([]);
        foreach ($menus as $menu) {
            switch ($menu->level) {
                case 1:
                    if (!$result->where('id', $menu->parent_id)->first()) {
                        //结果集中尚未包含当前菜单，添加
                        $result->add($menu);
                    }
                    break;
                case 2:
                    self::setToParent($result, $menu);
                    //查找到对应子菜单的父菜单，并将其放入到父菜单的集合中
                    break;
                default:
                    break;
            }
        }
        return $result;
    }

    /**
     * 查找到对应子菜单的父菜单，并将其放入到父菜单的集合中
     * @param $data
     * @param $menu
     */
    public static function setToParent($data, $menu): void
    {
        //二级菜单
        $firstLevelMenu = $data->where('id', $menu->parent_id)->first();
        if (!$firstLevelMenu) {
            //当前集合中不存在该一级菜单，从数据库中获取，并将其放入集合中
            $firstLevelMenu = Menu::query()->where('id', $menu->parent_id)->first();
            $data->push($firstLevelMenu);
        }
        $secondLevelMenu = $firstLevelMenu->secondLevelMenu ?? collect();
        $secondLevelMenu->push($menu);
        $firstLevelMenu->secondLevelMenu = $secondLevelMenu;
    }

    /**
     * 根据菜单Id查询菜单，并安装点击频率排序
     * @param Collection $arr
     * @return Builder|Builder[]|\Illuminate\Database\Eloquent\Collection|Model|null
     */
    public static function getMenusAndSortByActive(Collection $arr)
    {
        return Menu::query()
            ->find($arr)
            //根据菜单Id查询
            ->sortBy(function ($item) use ($arr) {
                return $arr->search($item->id);
                //将查询结果按照上面拍好的顺序重新排列
            });
    }


    protected static function filterRepetitionMenu($result)
    {
        $response = $result->duplicates('id');
        if (!empty($response)) {
            $result = $result->filter(function ($item) use ($response) {
                return !($response->contains($item->id) && empty($item->secondLevelMenu));
            });
        }
        return $result;
    }
}
