<?php


namespace App\Services;

use App\Services\BaseService;
use App\Models\Menu;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use App\Services\UserService;
use App\Services\RoleUserService;
use App\Services\RoleMenuService;

/**
 * 菜单
 */
class MenuService extends BaseService
{
    public static string $MODEL = Menu::class;
    /**
     * @description: 模型
     * @return {string}
     */
    public static function model(): string
    {
        return Menu::class;
    }

    /**
     * @description: 枚举
     * @return {*}
     */
    public static function enum(): string
    {
        return '';
    }

    /**
     * @description: 获取查询条件
     * @param {array} $search 查询内容
     * @return {array}
     */
    public static function getWhere(array $search = []): array
    {
        $where = [];
       
        if (isset($search['id']) && !empty($search['id'])) {
            $where[] = ['id', '=', $search['id']];
        }
        if (isset($search['parent_id']) && !empty($search['parent_id'])) {
            $where[] = ['parent_id', '=', $search['parent_id']];
        }
        if (isset($search['type']) && !empty($search['type'])) {
            $where[] = ['type', '=', $search['type']];
        }
        if (isset($search['uri']) && !empty($search['uri'])) {
            $where[] = ['uri', '=', $search['uri']];
        }
        if (isset($search['status']) &&  $search['status'] !='') {
            $where[] = ['status', '=', $search['status']];
        }
        if (isset($search['title']) && !empty($search['title'])) {
            $where[] = ['title', 'like', '%'.$search['title'].'%'];
        }
       
        return $where;
    }

    /**
     * @description: 查询单条数据
     * @param array $search
     * @return \App\Models\Coin|null
     */
    public static function findOne(array $search): ?Menu
    {
        return self::model()::where(self::getWhere($search))->first();
    }

    /**
     * @description: 查询所有数据
     * @param array $search
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public static function findAll(array $search = [])
    {
        return self::model()::where(self::getWhere($search))->orderBy('sort')->get();
    }

    /**
     * @description: 分页查询
     * @param array $search
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public static function paginate(array $search = [])
    {
        $limit = isset($search['limit']) ? $search['limit'] : 15;
        $paginator = self::model()::where(self::getWhere($search))
            ->orderBy("sort", 'asc')
            ->paginate($limit);
        return ['total' => $paginator->total(), 'data' => $paginator->items()];
    }

    /**
     * @description: 
     * @param {*} $params
     * @return {*}
     */    
    public static function submit($params = [])
    {
        $result = false;
        $msg['code'] = self::NOT;
        $msg['msg'] = '';
        // 2. 判断是否是更新
        if (!empty($params['id'])) {
            // 更新
            $info = self::findOne(['id'=>$params['id']] );
            if (!$info) {
                $msg['msg'] = '菜单不存在！';
            }else{
                $result = $info->update($params);
            }

        } else {
            // 创建
            $result = $info = self::model()::create($params);
        }


        if($result){
           $msg['code'] = self::YES;
           $msg['msg'] = '设置成功';
        }else{
            $msg['msg'] = empty($msg['msg']) ?'操作失败':$msg['msg'];
        }

        return $msg;
    }

    /**
     * @description: 获取菜单树
     * @return {*}
     */
    public static function getTree()
    {
        $list = self::findAll(['status' => self::model()::STATUS_SHOW]);
        $tree = self::toTree($list,0,0,'parent_id');
        return $tree;
    }

    /**
     * @description: 
     * @param {*} $userId
     * @param {*} $type
     * @return {*}
     */    
    public static function getUserMenu($userId ,$type = 1)
    {
        // 超级管理账号直接查看所有的菜单
        if($userId == 1){
            $list = self::findAll(['type' => $type ,'status' => self::$MODEL::STATUS_SHOW]);
        }else{
            $roleIds = RoleUserService::$MODEL::where('user_id',$userId)->pluck('role_id')->toArray();
       
            $roles = RoleService::$MODEL::with(['menus'=> function ($query) use ($type) {
                $query->where('type', $type);
            }])->whereIn('id',$roleIds)->get();
            $allMenus = [];

            foreach ($roles as $role) {
                if (!empty($role['menus'])) {
                    $allMenus = array_merge($allMenus, $role['menus']->toArray());
                }
            }
            $list = $allMenus;
        }
        if($type == 1){
            $tree = self::toTree($list,0,0,'parent_id');
        }else{
            $tree = $list;
        }
        return $tree;
    }

    /**
     * @description: 校验按钮权限
     * @param {*} $userId
     * @param {*} $uri
     * @return {*}
     */    
    public static function checkMenu($userId ,$uri)
    {
        if($userId == 1){
            return true;
        }else{
            $info = self::findOne(['uri' => $uri ,'status' => self::model()::STATUS_SHOW]);
            if($info){
                $menuId = $info->id;
                $roleIds = RoleUserService::$MODEL::where('user_id',$userId)->pluck('role_id')->toArray();
                $result = RoleMenuService::$MODEL::where('menu_id', $menuId)->whereIn('role_id', $roleIds)->count();
               
                if($result){
                    return true;
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }
        
    }
}