<?php

namespace App\Game;

use App\Game\Services\RouteService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class PageModule extends Model
{
    //
    protected $connection='mysql';
    public $timestamps = false; // 表中没有 Laravel 自动管理的时间戳字段
    const TABLE = 'webgame.modules';
    protected $table = self::TABLE;

    protected $fillable = ['page_id', 'pos_index','icon','type', 'api', 'data','game_ids','tabtype','title','state'];

    protected $casts = [
        'data' => 'array',
    ];

//    public function subs()
//    {
//        return $this->hasMany(PageModule::class, 'parent_id','id');
//    }
//
//    public function parent()
//    {
//        return $this->belongsTo(PageModule::class, 'parent_id','id');
//    }
    // 多对多关系 - 上级模块
    public function parents()
    {
        return $this->belongsToMany(PageModule::class, 'webgame.module_parents', 'module_id', 'parent_id');
    }

    // 多对多关系 - 下级模块
    public function subs()
    {
        return $this->belongsToMany(PageModule::class, 'webgame.module_parents', 'parent_id', 'module_id')->whereRaw(RouteService::getStateToWhereRaw());
    }

//    public function games()
//    {
//        return $this->belongsToMany(GameCard::class, null, 'game_ids');
//    }
// 添加了 state 状态过滤
    public function games()
    {
        if(strlen($this->game_ids)) {
            $gameIds = $this->parseGameIds(); // 假设这是一个解析 game_ids 字段的方法

            // 将 $gameIds 转换为逗号分隔的字符串，用于 SQL 查询中的 FIELD 函数
            $orderClause = 'FIELD(id, ' . $this->game_ids . ')';
            $games = GameCard::whereIn('id', $gameIds)->orderByRaw($orderClause); // 只获取状态为 1 的游戏


            return $games;
        }
        return null;
    }

    protected function parseGameIds()
    {
        // 这里简化处理，假设 game_ids 字段是逗号分隔的字符串
        return explode(',', $this->game_ids);
    }
    public function banners()
    {
        return Banner::where('link_module',$this->id)->whereRaw(RouteService::getStateToWhereRaw());
//        return $this->hasMany(Banner::class, 'link_module', 'id');
    }
    // 返回特定模块类型的结构化数据
    public function getSpecificDataAttribute()
    {
        switch ($this->type) {
            case 'ModuleAutoBanner':
                return $this->handleAutoBanner();
            case 'ModuleWinList':
                return $this->handleWinList();
            case 'ModuleSearch':
                return $this->handleSearch();
            case 'ModuleGameTabs':
                return $this->handleGameTabs();
            case 'GameTab':
                return $this->handleTab();

            case 'ModuleHomeWithdraw':
                return $this->handleWithdraw();

            case 'ModuleSmallGameList':
            case 'ModuleRollSmallGameList':
                return $this->handleSmallGameList();
            case 'ModuleGameList':
                return $this->handleGameList();
            default:
                return $this->data;
        }
    }


    private function handleWithdraw()
    {

        return [
            'title'=>$this->title,
            'type' => $this->type,
            'api' => $this->api,
            'tabtype' =>$this->tabtype,
            'tabs' => "",
        ];
    }


    private function handleAutoBanner()
    {
        return [
            'type' => $this->type,
            'data'=>$this->banners()->get()
            ];
    }

    private function handleWinList()
    {
        $data['type']=$this->type;
        BigWinner::FindWinnerFromGame();
        $titles=[0=>'win_list.tab_all',1=>'win_list.tab_slots',2=>'win_list.tab_sport'];
        // 获取所有唯一的 gtype
        $cache=BigWinner::getCache();
        $gtypes = $cache['gtypes'];

        // 为每个 gtype 检索赢家数据
        $data['tabs']=[];
        foreach ($gtypes as $type) {
            $data['tabs'][]=['type'=>$type,'title'=>$titles[$type]];
        }
        $data['data']= $cache['data'];

        return $data;

    }

    private function handleSearch()
    {

        return [
            'title'=>$this->title,
            'type' => $this->type,
            'api' => $this->api,
            'tabtype' =>$this->tabtype,
            'tabs' => "",
        ];
    }

    private function handleTab()
    {
        return [
            'id'=>$this->id,
            'title'=>$this->title,
            'icon' => $this->icon,
            'tabtype' =>$this->tabtype,
            'link' => $this->link,
        ];
    }
    private function handleGameTabs()
    {
        $data=['type'=>$this->type,'tabtype'=>$this->tabtype,'id'=>$this->id];
        $data['data'] = $this->subs()->where('type','<>','GameTab')->get()->map(function ($sub) {
            return $sub->getSpecificDataAttribute();
        });
        $data['tabs'] = $this->subs()->where('type','GameTab')->get()->map(function ($sub) {
            return $sub->getSpecificDataAttribute();
        });
        return $data;
    }

    private function handleSmallGameList()
    {

        $pageSize = 16; // 从请求获取pageSize或使用默认值
        // 获取与模块相关的游戏列表并应用分页
        $gamesQuery = $this->games();
        if($gamesQuery) {
            $games = $gamesQuery->forPage(1, $pageSize)->get();
            $games = GameCard::formatGames($games);
            $this->data = $games;
        }else{
            $games=null;
        }

        return [
            'id'=>$this->id,
            'title'=>$this->title,
            'icon' => $this->icon,
            'type' => $this->type,
            'api' => $this->api,
            'tabtype' =>$this->tabtype,
            'data_key' =>$this->data_key,
            'data' => $games,
            'link' => $this->link,
        ];

    }
    private static  $DEFAULT_PAGE_SIZE=9;
    public static function getDefaultPageSize()
    {
        self::$DEFAULT_PAGE_SIZE= ($_REQUEST['_d']??"m")=="m"?23:24;
        return self::$DEFAULT_PAGE_SIZE;
    }
    private function handleGameList()
    {

        $pageSize = self::getDefaultPageSize(); // 从请求获取pageSize或使用默认值
        $page = 1; // 从请求获取当前页或使用默认值

        // 根据模块获取游戏ID列表
        // 获取与模块相关的游戏列表并应用分页
        $gamesQuery = $this->games();
        $total = $gamesQuery->count();
//        print_r([$total,$gamesQuery->toSql(),$pageSize]);die;
        $games = $gamesQuery->forPage($page, $pageSize)->get();
        $games=GameCard::formatGames($games);
        $totalPage = ceil($total / $pageSize);
        $this->data=$games;

        return [
            'id'=>$this->id,
            'title'=>$this->title,
            'tabtype' =>$this->tabtype,
            'icon' => $this->icon,
            'type' => $this->type,
            'api' => $this->api,
            'data' => $games,
            'data_key' =>$this->data_key,
            'page' => $page,
            'pageSize' => $pageSize,
            'total' => $total,
            'totalPage' => $totalPage,
        ];
    }
    /**
     * 关闭state检查
     * @var bool
     */
    public static $enableStateCheck=true;
    protected static function boot()
    {
        parent::boot();

        // 默认按照 pos_index 升序排序
        static::addGlobalScope('order', function (Builder $builder) {
            $builder->orderBy('pos_index', 'asc');
        });

        if(self::$enableStateCheck) {
            static::addGlobalScope('where', function (Builder $builder) {
//            $builder->where('state', 1);
                $builder->whereRaw(RouteService::getStateToWhereRaw());
            });
        }
    }
}
