<?php

namespace App\Http\Controllers\User;

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['user_center_name'] ?? $siteConfigs['site_name'] ?? '用户中心';

        $config = [
            'logo' => [
                'title' => $siteName,
                'image' => '/Admin/images/logo.png',
            ],
            'menu' => [
                'data' => '/api/user/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' => '/user/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
    {
        $menus = DB::table('admin_menus')
            ->where('status', 1)
            ->where('visible', 1)
            ->where('terminal_type', 'user')
            ->orderBy('sort', 'asc')
            ->get()
            ->toArray();

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

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

    public function clearCache(): JsonResponse
    {
        try {
            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',
        ];

        $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'])) {
                $menuNode['openType'] = '_iframe';
                $menuNode['href'] = $item['path'];
            }

            $tree[] = $menuNode;
        }

        return $tree;
    }
}
