<?php

namespace app\admin\service;

use app\admin\model\AdminMenuModel;
use think\facade\Cache;

class AdminMenuService
{
    /**
     * @param string[] $order
     * @return mixed
     * @author 小夏
     * @email  449134904@qq.com
     * @date   2020-11-21 21:44:21
     */
    public static function getAll($order = ["app" => "ASC", "controller" => "ASC", "action" => "ASC"])
    {
        return AdminMenuModel::order($order)->select();
    }

    /**
     * 后台菜单列表,用于后台首页左侧菜单
     * @return mixed
     */
    public static function menus($adminId)
    {
        $menus = AdminMenuModel::where('type', 'in', [0, 1])->order('list_order asc')->select()->toArray();
        if ($adminId != 1) {
            foreach ($menus as $key => $menu) {
                $ruleName = "{$menu['app']}/{$menu['controller']}/{$menu['action']}";
                if (!cmf_auth_check($adminId, $ruleName)) {
                    $menus[$key]['status'] = 0;
                }
            }
        }
        return $menus;
    }

    /**
     * 按父ID查找菜单子项
     * @param int     $parentId 父菜单ID
     * @param boolean $withSelf 是否包括他自己
     * @return array|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function adminMenu($parentId, $withSelf = false)
    {
        //父节点ID
        $parentId = intval($parentId);
        $result   = AdminMenuModel::where(['parent_id' => $parentId, 'status' => 1])->order("list_order", "ASC")->select();

        if ($withSelf) {
            $result2[] = AdminMenuModel::where('id', $parentId)->find();
            $result    = array_merge($result2, $result);
        }

        //权限检查
        if (cmf_get_current_admin_id() == 1) {
            //如果是超级管理员 直接通过
            return $result;
        }

        $array = [];
        foreach ($result as $v) {

            //方法
            $action = $v['action'];

            //public开头的通过
            if (preg_match('/^public_/', $action)) {
                $array[] = $v;
            } else {
                if (preg_match('/^ajax_([a-z]+)_/', $action, $_match)) {
                    $action = $_match[1];
                }

                $ruleName = strtolower($v['app'] . "/" . $v['controller'] . "/" . $action);
                if (cmf_auth_check(cmf_get_current_admin_id(), $ruleName)) {
                    $array[] = $v;
                }
            }
        }

        return $array;
    }

    /**
     * 获取菜单 头部菜单导航
     * @param string $parentId 菜单id
     * @param bool   $bigMenu
     * @return array|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function subMenu($parentId = '', $bigMenu = false)
    {
        $array   = self::adminMenu($parentId, 1);
        $numbers = count($array);
        if ($numbers == 1 && !$bigMenu) {
            return '';
        }
        return $array;
    }

    /**
     * 菜单树状结构集合
     */
    public static function menuTree()
    {
        $data = self::getTree(0);
        return $data;
    }

    /**
     * 取得树形结构的菜单
     * @param        $myId
     * @param string $parent
     * @param int    $Level
     * @return bool|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getTree($myId, $parent = "", $Level = 1)
    {
        $data = self::adminMenu($myId);
        $Level++;
        $ret = NULL;
        if (count($data) > 0) {
            foreach ($data as $a) {
                $id         = $a['id'];
                $app        = $a['app'];
                $controller = ucwords($a['controller']);
                $action     = $a['action'];
                //附带参数
                $params = "";
                if (!empty($a['param'])) {
                    $params = htmlspecialchars_decode($a['param']);
                }

                if (strpos($app, 'plugin/') === 0) {
                    $pluginName = str_replace('plugin/', '', $app);
                    $url        = cmf_plugin_url($pluginName . "://{$controller}/{$action}{$params}");
                } else {
                    parse_str($params, $paramsArr);
                    $url = url("{$app}/{$controller}/{$action}", $paramsArr);
                }

                $app = str_replace('/', '_', $app);

                $array = [
                    "icon"   => $a['icon'],
                    "id"     => $id . $app,
                    "name"   => $a['name'],
                    "parent" => $parent,
                    "url"    => $url,
                    'lang'   => strtoupper($app . '_' . $controller . '_' . $action)
                ];


                $ret[$id . $app] = $array;
                $child           = self::getTree($a['id'], $id, $Level);

                //由于后台管理界面只支持三层，超出的不层级的不显示
                if ($child && $Level <= 3) {
                    $ret[$id . $app]['items'] = $child;
                }

            }
            return $ret;
        }

        return false;
    }

    /**
     * 更新缓存
     * @param null $data
     * @return array|null
     */
    public static function menuCache($data = null)
    {
        if (empty($data)) {
            $data = AdminMenuModel::order("list_order", "ASC")->column('*', 'id');
            Cache::set('Menu', $data, 0);
        } else {
            Cache::set('Menu', $data, 0);
        }
        return $data;
    }

    public static function menu($parentId, $withSelf = false)
    {
        //父节点ID
        $parentId = (int)$parentId;
        $result   = AdminMenuModel::where('parent_id', $parentId)->select();
        if ($withSelf) {
            $result2[] = AdminMenuModel::where('id', $parentId)->find();
            $result    = array_merge($result2, $result);
        }
        return $result;
    }

    /**
     * 得到某父级菜单所有子菜单，包括自己
     * @param int $parentId
     * @return array|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getMenuTree($parentId = 0)
    {
        $menus = AdminMenuModel::where("parent_id", $parentId)->order(["list_order" => "ASC"])->select();

        if ($menus) {
            foreach ($menus as $key => $menu) {
                $children = self::getMenuTree($menu['id']);
                if (!empty($children)) {
                    $menus[$key]['children'] = $children;
                }
                unset($menus[$key]['id']);
                unset($menus[$key]['parent_id']);
            }
            return $menus;
        } else {
            return $menus;
        }

    }
}
