<?php

namespace App\Game\Services;




use App\Game\AgentLinks;
use App\Game\GlobalUserInfo;
use App\Game\Route;
use App\Game\RouteModel;
use App\Game\WebChannelConfig;
use App\Game\WebRegionConfig;
use App\Models\AccountsInfo;
use Illuminate\Http\Request;

class RouteService
{
    public function createRoute(array $data)
    {
        $model = RouteModel::create($data);
        return $model;
    }
    /**
     * 获取所有路由及其层级结构
     *
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function getAllRoutesWithHierarchy($StateConfig=1)
    {
        // 仅加载顶层路由，并预加载所有嵌套子路由
        return RouteModel::whereNull('parent_id')
            ->whereRaw('state&'.$StateConfig.'='.$StateConfig)
            ->with('subs.subs.subs')  // 根据实际层级深度调整
            ->get();
    }

    /**
     * 通过访问的网站获取配置区分
     * @param Request|null $request
     * @return int
     */
    public  static function getStateConfig(Request $request=null)
    {
//        if(!$request){
//            $origin = $_SERVER['HTTP_ORIGIN'] ?? '*';
//        }else{
//            $origin = $request->server('HTTP_ORIGIN') ?? '*';
//        }
//
////        $routes = $this->routeService->getAllRoutesWithHierarchy();
//        $StateConfig=1;
//        if(strstr($origin,"24680.pro")||strstr($origin,"localhost")){
//            $StateConfig=2;
//        }
        $config=self::getChannelConfig($request);
        $StateConfig=$config->StateNo;
        return $StateConfig;
    }

    /**
     * @param Request|null $request
     * @return string
     */
    public static function getStateToWhereRaw(Request $request=null)
    {
        $StateConfig=self::getStateConfig($request);
        return 'state&'.$StateConfig.'='.$StateConfig;
    }

    private static $_ChannelConfig=null;
    public static function clearChannelConfig(){
        self::$_ChannelConfig=null;
    }
    /**
     * @param Request|null $request
     * @return WebRegionConfig|null
     */
    public static function getRegionConfig()
    {
        $RegionID = $_REQUEST['regionid'] ?? '';
        if (empty($RegionID) ) {
            $origin = ($_SERVER['HTTP_ORIGIN'] ?? $_SERVER['HTTP_REFERER'] ??'');
            if(!empty($origin)) {
                $RegionID = explode('.', $origin)[str_starts_with($origin, 'www') ? 1 : 0];
            }
        }

        if(empty($RegionID)) {
            $RegionID= env('DEFAULT_REGIONID','winus777');
        }
        $regionConfig = WebRegionConfig::query()->where('RegionID', $RegionID)->first();
        if ($regionConfig) return $regionConfig;
        return null;
    }
    public static function getThemeKey()
    {
        $regionConfig=self::getRegionConfig();
        if($regionConfig)return $regionConfig->ThemeKey;
        return env('DEFAULT_THEME_KEY','Theme1');
    }
    /**
     * @param Request|null $request
     * @return WebChannelConfig|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|\LaravelIdea\Helper\App\Game\_IH_WebChannelConfig_QB|mixed|object|null
     */
    public static function getChannelConfig(Request $request=null)
    {
        if(!is_null(self::$_ChannelConfig)){
            return self::$_ChannelConfig;
        }
        $Channel=self::getChannel($request);
        $config=WebChannelConfig::getByChannel($Channel);
        if(!$config){
            $config=WebChannelConfig::getByChannel(env('REGION_24680_DEFAULT_CHANNEL',100));
            if(!$config)$config=WebChannelConfig::query()->first();
        }else if($config->SHADOW_CHANNEL()!=$config->Channel){
            $config=WebChannelConfig::getByChannel($config->SHADOW_CHANNEL());
        }
        self::$_ChannelConfig=$config;
        return $config;
    }
    public static function getChannel(Request $request=null)
    {
        //从参数获取
        $origin = $request
            ? ($request->server('HTTP_ORIGIN') ?? $request->server('HTTP_REFERER') ?? '*')
            : ($_SERVER['HTTP_ORIGIN'] ?? $_SERVER['HTTP_REFERER'] ?? '*');

        $Channel = $request ? $request->input('c', '') : ($_REQUEST['c'] ?? '');
        $Channel = explode('/', $Channel)[0];

        // 如果没有 Channel，尝试从 pixel 获取
        if (!$Channel) {
            $pixel = trim($request ? $request->input('pixel', '') : ($_REQUEST['pixel'] ?? ''));
            if ($pixel) {
                $config = WebChannelConfig::where('PlatformID', $pixel)->first();
                if ($config) {
                    $Channel = $config->Channel;
                }
            }
        }

        //从用户获取
        if(GlobalUserInfo::$me){
            $Channel=GlobalUserInfo::$me->Channel;
        }else if(isset($_REQUEST['act'])&&!empty($_REQUEST['act'])){
            $ActCode = $_REQUEST['act'];
            $link = AgentLinks::getByCode($ActCode);
            if ($link) {
                $Channel = $link->Channel;
            }
        }
        //默认值用region绑定

        if(empty($Channel)||$Channel==env('REGION_24680_DEFAULT_CHANNEL',100)) {
            //根据域名获取渠道
            $RegionID = $request ? $request->input('regionid', '') : ($_REQUEST['regionid'] ?? '');
            if (empty($RegionID) && !empty($origin)) {
                $RegionID = explode('.', $origin)[str_starts_with($origin, 'www') ? 1 : 0];
            }
            if (!empty($RegionID)) {
                $exist = WebChannelConfig::where('RegionID', $RegionID)->whereRaw('SpecialMode&' . SPECIAL_MODE_REGION_UNIQUE)->value('Channel');
                if ($exist) {
                    $Channel = $exist;
                }
            }
        }
        return $Channel??env('REGION_24680_DEFAULT_CHANNEL',100);
    }
    public static function isTestSite()
    {
        $origin = $_SERVER['HTTP_ORIGIN'] ??$_SERVER['HTTP_REFERER']?? '*';
//        if(isset($_REQUEST['c'])&&!empty($_REQUEST['c'])){
//            $Channel=$_REQUEST['c'];
//            $Channel=explode('/',$Channel)[0];
//        }
        if (strstr($origin, "test")||strstr($origin, "dev")) {
//            $Channel = 44;
            return $origin;
        }
        return false;
    }
    public static function isTestOrLocalSite()
    {
//        return true;
        $origin = self::isTestSite();
//        if(isset($_REQUEST['c'])&&!empty($_REQUEST['c'])){
//            $Channel=$_REQUEST['c'];
//            $Channel=explode('/',$Channel)[0];
//        }
        if (strstr($origin, "localhost")) {
//            $Channel = 44;
            return $origin;
        }
        return false;
    }
}
