<?php

namespace App\Models;
use App\Models\SportLeague;
use App\Models\SportTeam;
use Illuminate\Support\Facades\Cache;


class Sport extends BaseModel
{
    protected $table = 'sport';
    protected $fillable = ['data_id', 'home_team_id', 'home_team_en', 'home_team', 'home_team_logo', 'guest_team_id', 'guest_team_en', 'guest_team', 'guest_team_logo', 'half_score', 'rbt', 
    'is_roll', 'score', 'league_en','league','odds','state','game_time','status','handicap_limit','over_under_limit','duying_limit','correct_core_limit','odd_even_limit','total_goal_limit',
    'is_handicap', 'is_over_under','is_duying','is_correct_core','is_odd_even','is_total_goal','is_locked','fixture_status','is_send','odd_ids_locked','refund_status','odd_fixture_status',
    'error','odd_values_locked','remark','is_rec'];
    protected $hidden = [];
    
    public static function getLongStatus($status){
        $long_status = [
            'Time To Be Defined' => '时间待定',
            'Not Started' => '未开赛',
            'First Half' => '上半场',
            'First Half, Kick Off' => '上半场，开球',
            'Halftime' => '中场休息',
            'Second Half' => '下半场',
            'Second Half, 2nd Half Started' => '下半场，已开球',
            'Extra Time' => '加时赛',
            'Break Time' => '休息时间（常规赛与加时赛之间）',
            'Penalty In Progress' => '点球大战进行中',
            'Match Suspended' => '比赛暂停',
            'Match Interrupted' => '比赛中断',
            'Match Finished' => '比赛结束',
            'Match Postponed' => '比赛延期',
            'Match Cancelled' => '比赛取消',
            'Match Abandoned' => '比赛腰斩（废弃）',
            'Technical Loss' => '技术性判负',
            'WalkOver' => '弃权/退赛（对手直接晋级）',
            'In Progress' => '进行中',
        ];
        return $long_status[$status] ?? $status;
    }

    public static function addSportTeam($sport_data){
        if (!empty($sport_data['home_team_id'])) {
            $info = SportTeam::where('team_id', $sport_data['home_team_id'])->first();
            if (!$info) { 
                SportTeam::create([
                    'team_id' => $sport_data['home_team_id'],
                    'team_name_en' => $sport_data['home_team_en'],
                    'logo' => $sport_data['home_team_logo'],
                ]);
            }
        } 
        if (!empty($sport_data['guest_team_id'])) {
            $info = SportTeam::where('team_id', $sport_data['guest_team_id'])->first();
            if (!$info) { 
                SportTeam::create([
                    'team_id' => $sport_data['guest_team_id'],
                    'team_name_en' => $sport_data['guest_team_en'],
                    'logo' => $sport_data['guest_team_logo'],
                ]);
            }
        }
        return true;
    }

    public static function addSportLeague($league){
        if (!empty($league['name'])) {
            $info = SportLeague::where('league_id', $league['id'])->first();
            if (!$info) {
                $info = SportLeague::where('league_en', $league['name'])->first();
                if ($info) {
                    $info->league_id = $league['id'] ?? '';
                    $info->logo = $league['logo'] ?? '';
                    $info->country = $league['country'] ?? '';
                    $info->season = $league['season'] ?? '';
                    $info->round = $league['round'] ?? '';
                    $info->standings = !empty($league['standings']) ? 1 : (isset($league['standings']) ? 0 : null);
                    $info->save();
                }
            }
            if (!$info) { 
                SportLeague::create([
                    'league_en' => $league['name'],
                    'logo' => $league['logo'] ?? '',
                    'league_id' => $league['id'] ?? '',
                    'country' => $league['country'] ?? '',
                    'season' => $league['season'] ?? '',
                    'round' => $league['round'] ?? '',
                    'standings' => !empty($league['standings']) ? 1 : (isset($league['standings']) ? 0 : null),
                ]);
            }
        } 
        return true;
    }

    //翻译赔率
    public static function doOdds($odds, $odd_values_locked = []) {
        // 1. 获取赔率，缓存数据
        $sport_odds = cache('sport_odds');
        if (!$sport_odds) {
            $sport_odds = SportOdds::where('function_name', '<>', null)->get()->toArray();
            Cache::set('sport_odds', $sport_odds, 300); //有效期5分钟
        }

        $sport_odds = array_column($sport_odds, null,'odd_name_en');
        $new_odds = [];
        foreach($odds as $k => $item) {
            foreach($item['values'] as &$values) {
                if ($values['value'] == 'Over 1.5') {
                    $values['value'] = '1.5 or more';
                }
                $special_str = self::isSpecialStr($values['value']);
                if ($special_str) {
                    $values['value_text'] = lang($special_str, [str_replace($special_str,'', $values['value'])]);
                } else {
                    $values['value_text'] = lang($values['value']);
                }

                //判断下注项是否加锁
                $odd_id = $item['id'];
                $handicap = isset($values['handicap']) ? $values['handicap'] : "";
                $vh = $values['value']."_".$handicap;
                if ($odd_values_locked && isset($odd_values_locked[$odd_id]) && array_search($vh, $odd_values_locked[$odd_id]) !== false) {
                    $values['is_locked'] = 1;
                } else {
                    $values['is_locked'] = 0;
                }
            }
            $item['name_en'] = $item['name'];
            $item['name'] = isset($sport_odds[$item['name']]) ? $sport_odds[$item['name']]['odd_name'] : $item['name'];
            $item['maxinum'] = $sport_odds[$item['name']]['maxinum'] ?? 50000;
            $item['mininum'] = $sport_odds[$item['name']]['mininum'] ?? 10;
            $new_odds[] = $item;
        }
        return $new_odds;
    }

    //翻译赔率名称
    public static function doOddName($odd_name) {
        // 1. 获取赔率，缓存数据
        $sport_odds = cache('sport_odds');
        if (!$sport_odds) {
            $sport_odds = SportOdds::where('function_name', '<>', null)->get()->toArray();
            Cache::set('sport_odds', $sport_odds, 300); //有效期5分钟
        }

        $sport_odds = array_column($sport_odds, null,'odd_name_en');

        if (isset($sport_odds[$odd_name])) {
            return $sport_odds[$odd_name]['odd_name'];
        }
        return $odd_name;
    }

    //翻译下注项
    public static function doOddValue($odd_value) {
        if (empty($odd_value)) {
            return $odd_value;
        }
        $special_str = self::isSpecialStr($odd_value);
        if ($special_str) {
            $odd_value = lang($special_str, [str_replace($special_str,'', $odd_value)]);
        } else {
            $odd_value = lang($odd_value);
        }
        return $odd_value;
    }
    
    public static function isSpecialStr($value) {
        if ($value === null)
            return '';
        if (stripos($value, 'u/yes ') !== false) {
            return 'u/yes ';
        } elseif (stripos($value, 'u/no ') !== false) {
            return 'u/no ';
        } elseif (stripos($value, 'o/yes ') !== false) {
            return 'o/yes ';
        } elseif (stripos($value, 'o/no ') !== false) {
            return 'o/no ';
        } elseif (stripos($value, ' or more') !== false) {
            return ' or more';
        } elseif (stripos($value, 'more ') !== false) {
            return 'more ';
        } elseif (stripos($value, 'Draw/Over ') !== false) {
            return 'Draw/Over ';
        } elseif (stripos($value, 'Away/Over ') !== false) {
            return 'Away/Over ';
        } elseif (stripos($value, 'Home/Over ') !== false) {
            return 'Home/Over ';
        } elseif (stripos($value, 'Draw/Under ') !== false) {
            return 'Draw/Under ';
        } elseif (stripos($value, 'Away/Under ') !== false) {
            return 'Away/Under ';
        } elseif (stripos($value, 'Home/Under ') !== false) {
            return 'Home/Under ';
        } elseif (stripos($value, 'Over ') !== false) {
            return 'Over ';
        } elseif (stripos($value, 'Under ') !== false) {
            return 'Under ';
        } elseif (stripos($value, 'Home +') !== false) {
            return 'Home +';
        } elseif (stripos($value, 'Away +') !== false) {
            return 'Away +';
        } elseif (stripos($value, 'Draw +') !== false) {
            return 'Draw +';
        } elseif (stripos($value, 'Home -') !== false) {
            return 'Home -';
        } elseif (stripos($value, 'Away -') !== false) {
            return 'Away -';
        } elseif (stripos($value, 'Draw -') !== false) {
            return 'Draw -';
        } elseif (stripos($value, 'Exactly ') !== false) {
            return 'Exactly ';
        }
        return '';
    }

    public static function getFixtureStatus($fixture_status) {
        $fixture_status['long'] = $fixture_status['long'] ? lang($fixture_status['long']) : $fixture_status['long'];
        return $fixture_status;
    }

    protected function getOddValuesLockedAttribute($value)
    {
        return $value ? json_decode($value, true) : [];
    }
    protected function getOddIdsLockedAttribute($value)
    {
        return $value ? json_decode($value, true) : [];
    }

    protected function getLeagueDataAttribute($value)
    {
        return $value ? json_decode($value, true) : [];
    }
}
