<?php

namespace app\traits\cms;

use app\model\Menu;
use app\repository\CmsRepository;
use tauthz\facade\Enforcer;
use think\Collection;

trait MenuTrait
{
    // 获取菜单列表
    public function getMenuList(string $type = 'all', string $show = 'all'): Collection
    {
        return Menu::field("id,pid,title,type,name,icon,href,target,sort")
            ->where('status', Menu::STATUS_NORMAL)
            ->when($type != 'all', function ($q) use ($show) {
                $q->where('is_show', $show);
            })
            ->when($type != 'all', function ($q) use ($type) {
                $q->where('type', $type);
            })
            ->order('sort', 'desc')
            ->order('id', 'asc')
            ->select();
    }

    //递归获取子菜单
    public function buildMenuChild(int $pid, array $menus, string $childName = 'children'): array
    {
        $treeList = [];
        foreach ($menus as $v) {
            if ($pid == $v['pid']) {
                $node                 = $v;
                $node['has_children'] = false;
                $child                = $this->buildMenuChild($v['id'], $menus, $childName);
                if (!empty($child)) {
                    $node[$childName]     = $child;
                    $node['has_children'] = true;
                }

                // todo 后续此处加上用户的权限判断

                $treeList[] = $node;
            }
        }
        return $treeList;
    }


    //菜单权限过滤
    public function handMenuRule(int $accountId, array $menus): array
    {
        $rules = CmsRepository::getInstance()->getUserRules($accountId);

        foreach ($menus as $k => $m) {
            $menus[$k]['icon'] = !empty($m['icon']) ? 'fa '.$m['icon'] : '';
            $menus[$k]['href'] = ltrim($m['href'], '/');

            if ($m['pid'] !== 0) {
                $name = $m['name'];
                $nameArr = explode(':', $name);
                if (count($nameArr) <= 1) {
                    $name = $name.':index';
                }

                if (!in_array($name, $rules)) {
                    unset($menus[$k]);
                }
            }else{
                $name = $m['name'];
                $nameArr = explode(':', $name);
                if (count($nameArr) <= 1) {
                    $name = $name.':index';
                }

                if (!in_array($name, $rules)) {
                    unset($menus[$k]);
                }
            }

        }
        return $menus;
    }

    /**
     * 检测批量数据下 是否有子栏目
     *
     * @param  array  $ids
     * @return bool
     */
    public function hasChildrenMenuByIds(array $ids): bool
    {
        return Menu::whereIn('pid', $ids)->count() > 0;
    }

    /**
     * 批量删除
     *
     * @param  array  $ids
     * @return bool
     */
    public function delMenuByIds(array $ids): bool
    {
        return Menu::deleteByIds($ids);
    }
}