<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;

class ConfigController extends Controller
{
    public function index(): JsonResponse
    {
        $siteConfigs = DB::table('config_items')
            ->where('status', 1)
            ->pluck('value', 'code')
            ->toArray();

        $siteName = $siteConfigs['site_name'] ?? 'CMSPRO';

        $config = [
            'logo' => [
                'title' => $siteName,
                'image' => '/Admin/images/logo.png',
            ],
            'menu' => [
                'data' => '/api/admin/menus.json',
                'method' => 'GET',
                'accordion' => true,
                'collapse' => false,
                'control' => true,
                'select' => '23',
                'defaultOpen' => 0,
            ],
            'tab' => [
                'enable' => true,
                'keepState' => true,
                'session' => true,
                'preload' => true,
                'max' => '30',
                'index' => [
                    'id' => '23',
                    'href' => '/admin/dashboard',
                    'title' => '首页',
                    'type' => '_iframe',
                ],
            ],
            'theme' => [
                'defaultColor' => '3',
                'defaultMenu' => 'dark-theme',
                'defaultHeader' => 'dark-theme',
                'allowCustom' => true,
                'banner' => false,
                'dark' => false,
            ],
            'colors' => [
                ['id' => '1', 'color' => '#16baaa', 'second' => '#ecf5ff'],
                ['id' => '2', 'color' => '#009688', 'second' => '#ecf5ff'],
                ['id' => '3', 'color' => '#36b368', 'second' => '#f0f9eb'],
                ['id' => '4', 'color' => '#f6ad55', 'second' => '#fdf6ec'],
                ['id' => '5', 'color' => '#f56c6c', 'second' => '#fef0f0'],
                ['id' => '6', 'color' => '#3963bc', 'second' => '#ecf5ff'],
            ],
            'other' => [
                'keepLoad' => '1200',
                'autoHead' => false,
                'footer' => true,
            ],
            'header' => [
                'message' => '',
            ],
        ];

        return response()->json($config);
    }

    public function menus(): JsonResponse
    {
        $user = auth('admin')->user();

        if ($user && $user->isSuperAdmin()) {
            $menus = DB::table('admin_menus')
                ->where('status', 1)
                ->where('visible', 1)
                ->where(function ($query) {
                    $query->where('terminal_type', 'admin')
                        ->orWhereNull('terminal_type');
                })
                ->orderBy('sort', 'asc')
                ->get()
                ->toArray();
        } else {
            // 非超管：只返回当前用户角色被授予的菜单
            $roleIds = $user ? $user->roles()->pluck('admin_roles.id')->toArray() : [];

            $menus = DB::table('admin_menus')
                ->join('admin_role_menus', 'admin_menus.id', '=', 'admin_role_menus.menu_id')
                ->whereIn('admin_role_menus.role_id', $roleIds)
                ->where('admin_menus.status', 1)
                ->where('admin_menus.visible', 1)
                ->where(function ($query) {
                    $query->where('admin_menus.terminal_type', 'admin')
                        ->orWhereNull('admin_menus.terminal_type');
                })
                ->orderBy('admin_menus.sort', 'asc')
                ->select('admin_menus.*')
                ->distinct()
                ->get()
                ->toArray();

            // 补全父级菜单：子菜单被授权时，其所有祖先菜单也需要显示（否则树形结构断裂）
            $menuIds = array_column($menus, 'id');
            $allMenus = DB::table('admin_menus')
                ->where('status', 1)
                ->where('visible', 1)
                ->where(function ($query) {
                    $query->where('terminal_type', 'admin')
                        ->orWhereNull('terminal_type');
                })
                ->get()
                ->keyBy('id')
                ->toArray();

            $missingIds = [];
            foreach ($menus as $menu) {
                $parentId = $menu->parent_id ?? 0;
                while ($parentId != 0 && !in_array($parentId, $menuIds)) {
                    $missingIds[] = $parentId;
                    $menuIds[] = $parentId;
                    $parentId = isset($allMenus[$parentId]) ? ($allMenus[$parentId]->parent_id ?? 0) : 0;
                }
            }

            if (!empty($missingIds)) {
                $parentMenus = DB::table('admin_menus')
                    ->whereIn('id', array_unique($missingIds))
                    ->where('status', 1)
                    ->where('visible', 1)
                    ->get()
                    ->toArray();
                $menus = array_merge($menus, $parentMenus);
            }
        }

        // 确保菜单按sort排序（array_merge补全父级菜单后可能破坏原有排序）
        usort($menus, function ($a, $b) {
            return ($a->sort ?? 0) <=> ($b->sort ?? 0);
        });

        $menuTree = $this->buildMenuTree($menus);

        return response()->json($menuTree);
    }

    public function clearCache(): JsonResponse
    {
        try {
            // cache:clear 会清除所有缓存，包括用户权限缓存（user:*:permissions）
            // 和权限码存在性缓存（permission:exists:*）
            Artisan::call('cache:clear');
            Artisan::call('config:clear');
            Artisan::call('route:clear');
            Artisan::call('view:clear');
            Artisan::call('event:clear');

            return response()->json([
                'code' => 0,
                'message' => '缓存清除成功',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 1,
                'message' => '缓存清除失败：'.$e->getMessage(),
            ]);
        }
    }

    private function buildMenuTree(array $items, int $parentId = 0): array
    {
        $iconMap = [
            'IconSetting' => 'layui-icon layui-icon-set',
            'IconUser' => 'layui-icon layui-icon-user',
            'IconShield' => 'layui-icon layui-icon-vercode',
            'IconMenu' => 'layui-icon layui-icon-menu-fill',
            'IconImage' => 'layui-icon layui-icon-picture',
            'IconFile' => 'layui-icon layui-icon-file',
        ];

        $pathMap = [
            '/system' => '/admin',
            '/system/user' => '/admin/user',
            '/system/role' => '/admin/role',
            '/system/menu' => '/admin/menu',
            '/system/config' => '/admin/config',
            '/system/setting' => '/admin/setting',
            '/system/attachment' => '/admin/attachment',
            '/system/log' => '/admin/log',
            '/system/operation-log' => '/admin/operation-log',
            '/system/database' => '/admin/database',
            '/admin/dashboard' => '/admin/dashboard',
            '/admin/content-category' => '/admin/content-category',
            '/admin/content-model' => '/admin/content-model',
            '/admin/content' => '/admin/content',
            '/admin/front-user' => '/admin/front-user',
            '/admin/user-group' => '/admin/user-group',
        ];

        $tree = [];
        foreach ($items as $item) {
            $item = (array) $item;
            if (($item['parent_id'] ?? 0) != $parentId) {
                continue;
            }

            $type = (int) ($item['type'] ?? 1);
            if ($type === 3) {
                continue;
            }

            $children = $this->buildMenuTree($items, $item['id']);
            $icon = $item['icon'] ?? '';
            if (strpos($icon, 'fa ') === 0 || strpos($icon, 'fa-') === 0) {
                $iconClass = $icon;
            } elseif (isset($iconMap[$icon])) {
                $iconClass = $iconMap[$icon];
            } else {
                $iconClass = 'layui-icon layui-icon-'.strtolower($icon);
            }

            $menuNode = [
                'id' => (string) $item['id'],
                'title' => $item['name'],
                'icon' => $iconClass,
                'type' => $children ? 0 : 1,
            ];

            if ($children) {
                $menuNode['children'] = $children;
            }

            if (! $children && $type === 2 && ! empty($item['path'])) {
                $href = $item['path'];
                $resolvedHref = isset($pathMap[$href]) ? $pathMap[$href] : $href;
                $menuNode['openType'] = '_iframe';
                $menuNode['href'] = $resolvedHref;
                if ($resolvedHref === '/admin/dashboard') {
                    $menuNode['id'] = '10';
                }
            }

            $tree[] = $menuNode;
        }

        return $tree;
    }
}
