<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Sport as SportModel;
use App\Models\SportTeam;
use App\Models\SportLeague;
use App\Services\SportClientService;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Models\Config;

class Basketball extends Command
{
    /**
     * 命令名称和签名
     *
     * @var string
     */
    protected $signature = 'basketball {is_live=0}';
    protected $is_live = 0;

    protected  $short_status = [
            'NS' => 0,
            'Q1' => 1,
            'Q2' => 1,
            'Q3' => 1,
            'Q4' => 1,
            'OT' => 1,
            'BT' => 1,
            'HT' => 1,
            'FT' => 2,
            'AOT' => 2,
            'POST' => 3,
            'CANC' => 4,
            'SUSP' => 4,
            'AWD' => 4,
            'ABD' => 4,
        ];

    protected $long_status = [
        'Not Started' => 0,
        'Quarter 1' => 1,
        'Quarter 2' => 1,
        'Quarter 3' => 1,
        'Quarter 4' => 1,
        'Over Time' => 1,
        'Break Time' => 1,
        'Halftime' => 1,
        'Game Finished' => 2,
        'After Over Time' => 2,
        'Game Postponed' => 3,
        'Game Cancelled' => 4,
        'Game Suspended' => 4,
        'Game Awarded' => 4,
        'Game Abandoned' => 4,
    ];        

    /**
     * 命令描述
     *
     * @var string
     */
    protected $description = '当天会去更新明天的赛事（23:59:00执行一次）';
    /**
     * 执行命令
     *
     * @return int
     */
    public function handle()
    {
        // $date = '2026-05-21';
        // // $data = SportClientService::basketballGames(['date' => $date]);
        // // file_put_contents('basketballGames-21.json', json_encode($data));

        // $data_id = 499637;
        // $data = SportClientService::basketballOdds(['game' => $data_id]);
        // file_put_contents('basketballOdds-499637.json', json_encode($data));
        // print_r($data);
        // die;
        // $this->info('开始执行统计比赛数据任务...');
        $this->is_live = $this->argument('is_live');
        if ($this->is_live == 0) {
            //未开始的赛事拉取
            $this->fixtures();
        } elseif ($this->is_live == 1) {
            
        } elseif ($this->is_live == 2){
            $this->checkLiveFixtures();
        } elseif ($this->is_live == 3) {
            $this->checkOvertimeFixtures();
        } 
        
    }


    //到了比赛开始时间，但是状态还是未开始，检查比赛
    public function checkOvertimeFixtures()
    { 
        // 比赛开始后，状态还是未开始的数据检测
        $ids = SportModel::where('type', 2)->where('state', 0)->where('game_time', '<=', time())->where('game_time', '>', strtotime(date('Y-m-d')))->pluck('data_id')->toArray();
        if ($ids) {
            foreach ($ids as $id) {
                $data = SportClientService::basketballGames(['id' => $id]);
                $this->updateOrCreateSport($data, 1);
            }
        }
        return true;
    }

    //进行中超过3分钟没有更新数据的赛事，检查比赛是否结束
    public function checkLiveFixtures()
    { 
        //1. 统一锁盘时间（比赛开始前1分钟）
        SportModel::where('type', 2)->where(['is_locked' => 0, 'is_roll' => 0])->where('game_time', '<=', time() + 90)->update(['is_locked' => 1]);

        //2. 比赛进行中，超过3分钟未更新的数据检测
        $end_time = date("Y-m-d H:i:s", time() - 180);
        $ids = SportModel::where('type', 2)->where('state', 1)->where('updated_at', '<=', $end_time)->pluck('data_id')->toArray();
        if ($ids) {
            foreach ($ids as $id) {
                $data = SportClientService::basketballGames(['id' => $id]);
                $this->updateOrCreateSport($data, 1);
            }
        }
        return true;
    }

    private function updateOrCreateSport($data, $is_check = 0) {
        //体育赛事结束前几(分钟)锁盘,90分钟结束
        $sport_locked = Config::where('field', 'sport_locked')->first()->val ?? 1;

        $data = $data['response'];
        $tableData = [];
        $status = $this->short_status;
        foreach ($data as $item) {
            $data_id = $item['id'];
            $sport_data = [
                'data_id' => $item['id'],
                'type' => 2,
                'home_team_id' => $item['teams']['home']['id'],
                'home_team_en' => $item['teams']['home']['name'],
                'home_team_logo' => $item['teams']['home']['logo'],
                'guest_team_id' => $item['teams']['away']['id'],
                'guest_team_en' => $item['teams']['away']['name'],
                'guest_team_logo' => $item['teams']['away']['logo'],
                'half_score' => "",
                'rbt' => $item['timestamp'],
                'score' => isset($item['scores']['home']) && isset($item['scores']['away']) ? "{$item['scores']['home']['total']}-{$item['scores']['away']['total']}":'-',
                'extra_score' => isset($item['scores']['home']) && isset($item['scores']['away']) ? "{$item['scores']['home']['over_time']}-{$item['scores']['away']['over_time']}":'-',
                'league_id' => $item['league']['id'],
                'league_en' => $item['league']['name'],
                'league_data' => json_encode($item['league']),
                'scores' => json_encode($item['scores']),
                'state' => $status[$item['status']['short']],//比赛状态：0未开始1进行中2已完场3延期4取消
                'game_time' => $item['timestamp'],
                'updated_at' => now(),
                'is_send' => 0,
            ];
            $info = SportModel::where('type', 2)->where('data_id', $data_id)->first();
        
            $sport_data['score'] = $sport_data['score'] == '-' ? '' : $sport_data['score'];
            $sport_data['extra_score'] = $sport_data['extra_score'] == '-' ? '' : $sport_data['extra_score'];
            
            //如果赛事取消、延期等，标记需要退款
            if ($sport_data['state'] > 2) {
                $sport_data['refund_status'] = 1;
            }
            if (empty($info['league'])) {
                $sport_data['league'] = SportLeague::getLeagueName($sport_data['league_id'], 2);
            }
            if (empty($info['home_team'])) {
                $sport_data['home_team'] = SportTeam::getTeamName($sport_data['home_team_id'], 2);
            }
            if (empty($info['guest_team'])) {
                $sport_data['guest_team'] = SportTeam::getTeamName($sport_data['guest_team_id'], 2);
            }

            if (!$info) {
                $sport_data['created_at'] = date('Y-m-d H:i:s');
                $sport_data['status'] = 1;
                $tableData[] = $sport_data;
            } else {
                SportModel::where('type', 2)->where('data_id', $data_id)->update($sport_data);
            }
            //更新或创建球队和联赛信息
            SportModel::addSportTeam($sport_data);
            SportModel::addSportLeague($item['league']);

            //比赛结束，插入比赛事件
            if (isset($sport_data['state']) && $sport_data['state'] == 2 ) {
                
            }
        }
        if ($tableData) {
            SportModel::insert($tableData);
        }
        return true;
    }
    
    /**
     * 获取指定日期的所有赛事
     *
     * @return array
     */
    public function fixtures()
    {
        //根据配置拉取多少天的赛事信息
        $days = Config::where('field', 'sport_days')->first()->val ?? 1;
        for($i=0;$i<$days;$i++) {
            $date = Carbon::today()->addDay($i)->toDateString();
            $data = SportClientService::basketballGames(['date' => $date]);
            $this->updateOrCreateSport($data);
        }
        
        return true;
    }

    //比赛开始后，超过3个小时,并且更新时间超过10分钟，还是进行中的数据，更新成已完成
    public function updateOvertimeFixtures()
    { 
        // 比赛开始后，状态还是未开始的数据检测
        $end_time = date("Y-m-d H:i:s", time() - 600);
        SportModel::where('type', 2)->where('status', 1)->where('state', 1)->where('game_time', '<=', time() - 60*60*3)->where('updated_at', '<=', $end_time)->update(['state' =>2]);
        return true;
    }

    
}
