<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Models\SportGame as SportGameModel;
use App\Models\SportGameplay;
use App\Models\SportGameLog;
use Exception;
use App\Constants\HttpStatus;

class SportGame extends Controller
{
    /**
     * 足球游戏列表，树形结构
     */
    public function list()
    {
        try {
            $list = SportGameModel::with(['children'])->select(['id','name','name_en','end_time','is_locked'])->get()->toArray();
        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR,$e->getMessage());
        }
        return $this->success([ 'data' => $list]);

    }

    //设置赔率
    public function setOdds()
    {
        try {
            $params = request()->validate([
                'id' => ['nullable','integer'],
                'game_id' => ['nullable','integer'],
                'odds' => ['required','numeric'],
                'maxinum' => ['required','numeric'],
                'mininum' => ['required','numeric'],
            ]);
            $id = $params['id'] ?? 0;
            if ($id) {
                $info = SportGameplay::where('id', $id)->first();
                if (!$info) throw new Exception('数据不存在');
                $info->odds = $params['odds'];
                $info->maxinum = $params['maxinum'];
                $info->mininum = $params['mininum'];
                $info->save();
            } else if (!empty($params['game_id']) ) {
                $where[] = ['game_id', $params['game_id']];
                SportGameplay::where($where)->update(['odds' => $params['odds'], 'maxinum' => $params['maxinum'], 'mininum' => $params['mininum']]);
            } else {
                throw new Exception('参数错误');
            }
            
            return $this->success();
        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR,$e->getMessage());
        }
    }

    //开奖
    public function openCode() { 
        try {
            $params = request()->validate([
                'id' => ['required','integer'],
            ]);
            $id = $params['id'];
            $info = SportGameModel::find($id);
            if (!$info) {
                return $this->error(HttpStatus::NOT_FOUND,'数据不存在');
            }
            //记录开奖日志
            $log = new SportGameLog();
            $log->game_id = $info->game_id;
            $log->gameplay_id = $info->id;
            $log->name = $info->name;
            $log->name_en = $info->name_en;
            $log->save();
            
            //订单结算
            return $this->success();
        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR,$e->getMessage());
        }
    }

}