<?php

use think\facade\Route;

defined('DS') || define('DS', DIRECTORY_SEPARATOR);

Route::miss(function () {
    $appRequest = request()->pathinfo();
    if ($appRequest === null) {
        $appName = '';
    } else {
        $appRequest = str_replace('//', '/', $appRequest);
        $appName = explode('/', $appRequest)[0] ?? '';
    }
    
    $publicPath = app()->getRootPath() . 'public' . DS;
    
    $staticExtensions = ['js', 'css', 'png', 'jpg', 'jpeg', 'gif', 'svg', 'ico', 'woff', 'woff2', 'ttf', 'eot'];
    $pathParts = explode('.', $appRequest);
    $extension = strtolower(end($pathParts));
    
    if (in_array($extension, $staticExtensions)) {
        $filePath = $publicPath . $appRequest;
        if (file_exists($filePath)) {
            $mimeTypes = [
                'js' => 'application/javascript',
                'css' => 'text/css',
                'png' => 'image/png',
                'jpg' => 'image/jpeg',
                'jpeg' => 'image/jpeg',
                'gif' => 'image/gif',
                'svg' => 'image/svg+xml',
                'ico' => 'image/x-icon',
                'woff' => 'font/woff',
                'woff2' => 'font/woff2',
                'ttf' => 'font/ttf',
                'eot' => 'application/vnd.ms-fontobject',
            ];
            header('Content-Type: ' . ($mimeTypes[$extension] ?? 'application/octet-stream'));
            return file_get_contents($filePath);
        }
    }
    
    switch (strtolower($appName)) {
        case 'admin':
            $filePath = $publicPath . 'admin' . DS . 'index.html';
            break;
        case 'home':
        case 'pages':
        default:
            $filePath = $publicPath . 'admin' . DS . 'client.html';
            break;
    }
    
    if (file_exists($filePath)) {
        header('Content-Type: text/html; charset=UTF-8');
        return file_get_contents($filePath);
    }
    
    return json([
        'code' => 404,
        'msg' => '页面不存在'
    ], 404);
});
