<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Models\Sport as SportModel;
use App\Models\SportEvent;
use App\Models\SportOdds;
use App\Models\SportTeam;
use App\Models\SportLeague;
use App\Models\SportStatistics;
use Exception;
use App\Constants\HttpStatus;
use App\Services\SportClientService;


class Sport extends Controller
{

    /**
     * 赛事玩法列表
     */
    public function oddsList()
    {
        try {
            $params = request()->validate([
                'page' => ['nullable', 'integer', 'min:1'],
                'limit' => ['nullable', 'integer', 'min:1'],
                'odd_name' => ['nullable'],
            ]);
            $page = request()->input('page', 1);
            $limit = request()->input('limit', 15);

            $query = new SportOdds();
            $query = $query->whereNotNull('function_name');
            if (!empty($params['odd_name'])) {
                $odd_name = $params['odd_name'];
                $query = $query->where(function ($query) use ($odd_name) {
                    $query->where('odd_name', 'like', "%{$odd_name}%")
                    ->orWhere('odd_name_en', 'like', "%{$odd_name}%");
                });
            }

            $count = $query->count();
            $list = $query
                ->forPage($page, $limit)
                ->get();
        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR,$e->getMessage());
        }
        return $this->success(['total' => $count, 'data' => $list]);
    }

    //设置赛事玩法的下注限额
    public function setOdds()
    {
        try {
            $params = request()->validate([
                'id' => ['required'],
                'maxinum' => ['required', 'numeric'],
                'mininum' => ['required', 'numeric', 'min:1'],
            ]);
            
            // 验证金额逻辑
            if ($params['maxinum'] <= $params['mininum']) {
                throw new Exception('最高下注限额必须大于最低下注限额');
            }
            
            $id = $params['id'];
            
            // 构建查询
            $query = SportOdds::query();
            
            if (is_array($id)) {
                if (empty($id)) {
                    throw new Exception('ID列表不能为空');
                }
                $query->whereIn('id', array_map('intval', $id));
            } else {
                if (!is_numeric($id) || $id <= 0) {
                    throw new Exception('ID必须是有效的正整数');
                }
                $query->where('id', (int)$id);
            }
            
            // 检查玩法是否存在
            if (!$query->exists()) {
                throw new Exception('玩法不存在');
            }
            
            // 执行更新
            $updated = $query->update([
                'maxinum' => $params['maxinum'],
                'mininum' => $params['mininum'],
            ]);
        
            return $this->success();
        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR,$e->getMessage());
        }
    }
    
    /**
     * 列表
     */
    public function list()
    {
        try {
            $params = request()->validate([
                'page' => ['nullable', 'integer', 'min:1'],
                'limit' => ['nullable', 'integer', 'min:1'],
                'data_id' => ['nullable'],
                'team_name' => ['nullable'],
                'league' => ['nullable'],
                'state' => ['nullable', 'integer'],
                'status' => ['nullable', 'integer'],
                'is_locked' => ['nullable', 'integer'],
                'start_time' => ['nullable', 'string'],
                'end_time' => ['nullable', 'string'],
                'error' => ['nullable', 'integer'],
                'odds' => ['nullable', 'integer'],
                'is_rec' => ['nullable', 'integer'],
            ]);
            $page = request()->input('page', 1);
            $limit = request()->input('limit', 15);
            $order = 'asc';

            $query = new SportModel();
            if (!empty($params['data_id'])) {
                $query = $query->where('data_id', $params['data_id']);
            }
            if (!empty($params['team_name'])) {
                $team_name = $params['team_name'];
                $query = $query->where(function ($query) use ($team_name) {
                    $query->where('home_team', 'like', "%{$team_name}%")
                    ->orWhere('home_team_en', 'like', "%{$team_name}%")
                    ->orWhere('guest_team', 'like', "%{$team_name}%")
                    ->orWhere('guest_team_en', 'like', "%{$team_name}%");
                });
            }
            if (isset($params['league']) && $params['league'] !== null) {
                $league = $params['league'];
                $query = $query->where(function ($query) use ($league) {
                    $query->where('league', 'like', "%{$league}%")
                    ->orWhere('league_en', 'like', "%{$league}%");
                });
            }
            if (isset($params['state']) && $params['state'] !== null) {
                $query = $query->where('state', $params['state']);
                if ($params['state'] >= 2) {
                    $order = 'desc';
                }
            }
            if (isset($params['status']) && $params['status'] !== null) {
                $query = $query->where('status', $params['status']);
            }
            if (isset($params['is_locked']) && $params['is_locked'] !== null) {
                $query = $query->where('is_locked', $params['is_locked']);
            }
            if (!empty($params['start_time'])) {
                $query = $query->where('game_time', '>=', strtotime($params['start_time'].' 00:00:00'));
            }
            if (!empty($params['end_time'])) {
                $query = $query->where('game_time', '<', strtotime($params['end_time'].' 23:59:59'));
            }
            if (isset($params['error']) && $params['error'] !== null) {
                $query = $query->where('error', $params['error']);
                $order = 'desc';
            }
            if (isset($params['odds'])) {
                if ($params['odds'] == 1) {
                    $query = $query->whereNotNull('odds');
                } elseif ($params['odds'] == 0) {
                    $query = $query->whereNull('odds');
                }
            }
            if (isset($params['is_rec']) && $params['is_rec'] !== null) {
                $query = $query->where('is_rec', $params['is_rec']);
            }

            $count = $query->count();
            $list = $query
                ->forPage($page, $limit)
                ->orderBy('game_time', $order)
                ->orderBy('is_roll', 'desc')
                ->get();
            foreach($list as &$item) {
                $item['game_time'] = date('Y-m-d H:i:s', $item['game_time']);
                $item['rbt'] = date('Y-m-d H:i:s', $item['rbt']);
                $item['fixture_status'] = json_decode($item['fixture_status'], true);
                
                $item['home_team'] = SportTeam::getTeamName($item['home_team_id']) ?? $item['home_team_en'];
                $item['guest_team'] = SportTeam::getTeamName($item['guest_team_id']) ?? $item['guest_team_en'];
                $item['league'] = SportLeague::getLeagueName($item['league_id']) ?? $item['league_en'];
            }
        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR,$e->getMessage());
        }
        return $this->success(['total' => $count, 'data' => $list]);

    }

    //详情
    public function info()
    {
        try {
            request()->validate([
                'id' => ['required', 'integer'],
            ]);
            $id = request()->input('id');
            $info = SportModel::where('id', $id)->first();
            if (!$info) throw new Exception('赛事不存在');
            $info = $info->toArray();
            $info['date'] = date('Y-m-d',$info['game_time']);
            $info['time'] = date('H:i',$info['game_time']);
            $info['game_time'] = date('Y-m-d H:i:s', $info['game_time']);
            $info['rbt'] = date('Y-m-d H:i:s', $info['rbt']);
            $info['fixture_status'] = json_decode($info['fixture_status'], true);
            if (!empty($info['fixture_status']['long'])) {
                $info['fixture_status']['long'] = lang($info['fixture_status']['long']);
            }
            $info['odds'] = $info['odds'] ? json_decode($info['odds'], true) : null;
            $info['odds'] = $info['odds'] ? SportModel::doOdds($info['odds'], $info['odd_values_locked']) : null;
            $info['event'] = SportEvent::where('data_id', $info['data_id'])->get();
            foreach($info['event'] as &$event) {
                if (stripos($event['detail'], 'Substitution') !== false) {
                    $event['detail'] = str_replace('Substitution', lang('Substitution'), $event['detail']); 
                } else {
                    $event['detail'] = lang($event['detail']);
                }
                $event['type'] = lang($event['type']);
            }
            $info['home_team'] = $info['home_team'] ?? SportTeam::getTeamName($info['home_team_id']);
            $info['guest_team'] = $info['guest_team'] ?? SportTeam::getTeamName($info['guest_team_id']);
            $info['league'] = $info['league'] ?? SportLeague::getLeagueName($info['league_id']);

            //赛事统计数据
            $info['statistics'] = SportStatistics::where('data_id', $info['data_id'])->get()->toArray();

        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR,$e->getMessage());
        }
        return $this->success($info);
    }

    public function setStatus()
    {
        try {
            $params = request()->validate([
                'id' => ['required','array'],
                'status' => ['nullable', 'integer'],
                'state' => ['nullable', 'integer'],
                'is_locked' => ['nullable', 'integer'],
                'is_rec' => ['nullable', 'integer'],
            ]);
            $id = $params['id'];
            if (isset($params['state']) && $params['state'] !== null) {
                $update_data = ['state' => $params['state'], 'is_send' => 0];
                if ($params['state'] > 2) {
                    $update_data['refund_status'] = 1;
                }
                SportModel::whereIn('id', $id)->update($update_data);
            }
            if (isset($params['is_locked']) && $params['is_locked'] !== null) {
                SportModel::whereIn('id', $id)->update(['is_locked' => $params['is_locked'], 'is_send' => 0]);
            }
            if (isset($params['status']) && $params['status'] !== null) {
                SportModel::whereIn('id', $id)->update(['status' => $params['status'], 'is_send' => 0]);
            }
            if (isset($params['is_rec']) && $params['is_rec'] !== null) {
                SportModel::whereIn('id', $id)->update(['is_rec' => $params['is_rec']]);
            }
            return $this->success();
        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR,$e->getMessage());
        }
    }

    //设置赔率玩法是否加锁
    public function setOddsLocked()
    {
        try {
            $params = request()->validate([
                'id' => ['required','integer'],
                'odd_id' => ['nullable','integer'],
            ]);
            $id = $params['id'];
            $info = SportModel::where('id', $id)->first();
            if (!$info) throw new Exception('赛事不存在');

            $odd_ids_locked = $info->odd_ids_locked;
            if (empty($params['odd_id'])) {
                if (empty($odd_ids_locked) && !empty($info->odds)) {
                    $odds = json_decode($info->odds, true);
                    foreach ($odds as $odd) {
                        $odd_ids_locked[] = $odd['id'];
                    }
                } else {
                    $odd_ids_locked = [];
                }
            } else {
                if (in_array($params['odd_id'], $odd_ids_locked)) {
                    $odd_ids_locked = array_diff($odd_ids_locked, [$params['odd_id']]);
                    $odd_ids_locked = array_values($odd_ids_locked);
                } else {
                    $odd_ids_locked[] = $params['odd_id'];
                }
            }
            $info->odd_ids_locked = json_encode($odd_ids_locked);
            $info->is_send = 0;
            $info->save();
            return $this->success();
        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR,$e->getMessage());
        }
    }

    //设置下注项是否加锁
    public function setValuesLocked()
    {
        try {
            $params = request()->validate([
                'id' => ['required','integer'],
                'odd_id' => ['required','integer'],
                'value' => ['required'],
                'handicap' => ['nullable'],
            ]);
            $id = $params['id'];
            $odd_id = $params['odd_id'];
            $value = $params['value'];
            $handicap = $params['handicap'] ?? "";
            $info = SportModel::where('id', $id)->first();
            if (!$info) throw new Exception('赛事不存在');

            $odd_values_locked = $info->odd_values_locked;

            $vh = $value."_".$handicap;
            if (isset($odd_values_locked[$odd_id]) && ($key = array_search($vh, $odd_values_locked[$odd_id])) !== false) {
                //查找数组是否存在这个值，存在则删除这个数据
                unset($odd_values_locked[$odd_id][$key]);
            } else {
                $odd_values_locked[$odd_id][] = $vh;
            }
            $info->odd_values_locked = json_encode($odd_values_locked);
            $info->is_send = 0;
            $info->save();
            return $this->success();
        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR,$e->getMessage());
        }
    }

    public function getFixtures()
    {
        $params = request()->validate([
            'data_id' => ['required'],
        ]);
        $data_id = $params['data_id'];
        $info = SportModel::where('data_id', $data_id)->first();
        if (!$info) throw new Exception('赛事不存在');

        $data = SportClientService::fixtures([
            'id' => $data_id,
        ]);
        $data = !empty($data['response'][0]) ? $data['response'][0] : [];
        $result = [];
        if (!empty($data['fixture'])) {
            $result['fixture'] = $data['fixture'];
            if (!empty($result['fixture']['periods']['first'])) {
                $result['fixture']['periods']['first'] = date('Y-m-d H:i:s', $result['fixture']['periods']['first']);
            }
            if (!empty($result['fixture']['periods']['second'])) {
                $result['fixture']['periods']['second'] = date('Y-m-d H:i:s', $result['fixture']['periods']['second']);
            }
            if (!empty($result['fixture']['status']['long'])) {
                $result['fixture']['status']['long'] = SportModel::getLongStatus($result['fixture']['status']['long']);
            }
        }
        if (!empty($data['goals'])) {
            $result['goals'] = $data['goals'];
        }
        if (!empty($data['score'])) {
            $result['score'] = $data['score'];
        }
        if (!empty($data['events'])) {
            $result['events'] = $data['events'];
            $result['events'] = $this->doEvent($result['events'], $data_id);
        }
        
        $result['info'] = $info->toArray();
        $result['info']['game_time'] = date('Y-m-d H:i:s', $info->game_time);
        return $this->success($result);
    }

    private function doEvent($events, $data_id) {
        if (empty($events)) return [];
        $result = [];
        foreach($events as $event) {
            $result[] = [
                'data_id' => $data_id,
                'type' => $event['type'],
                'time_elapsed' => $event['time']['elapsed'],
                'time' => $event['time'],
                'detail' => $event['detail'],
                'player' => $event['player'],
                'team_id' => $event['team']['id'],
                'comments' => $event['comments'],
                'assist' => $event['assist'],
            ];
        }
        return $result;
    }

}