<?php

namespace App\Http\Controllers\admin;

use App\Constants\HttpStatus;
use App\Http\Controllers\Controller;
use App\Services\BetService;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Exception;
use App\Models\Bet as BetModel;

class Bet extends Controller
{
    function index()
    {
        try {
            $params = request()->validate([
                'page' => ['nullable', 'integer', 'min:1'],
                'limit' => ['nullable', 'integer', 'min:1'],
                'member_id' => ['nullable', 'string'],
                'first_name' => ['nullable'],
                'keywords' => ['nullable', 'string', 'min:1'],
                'issue_no' => ['nullable', 'string'],
                'id' => ['nullable', 'string'],
                'status' => ['nullable', 'integer', 'in:1,2'],
                'username' => ['nullable', 'string', 'min:1'],
                'start_time' => ['nullable', 'date', 'date_format:Y-m-d', 'required_with:end_time'],
                'end_time' => ['nullable', 'date', 'date_format:Y-m-d', 'required_with:start_time'],
                'is_winner' => ['nullable', 'integer', 'in:0,1'],
            ]);

            $page = request()->input('page', 1);
            $limit = request()->input('limit', 10);

            $query = BetModel::where(BetService::getWhere($params));


            if (isset($params['username']) && !empty($params['username'])) {
                $username = $params['username'];
                $query = $query->whereHas('user', function ($query) use ($username) {
                    $query->where('username', $username);
                });
            }
            $first_name = $params['first_name'] ?? '';
            $query = $query->with(['user', 'issue', 'pcIssue'])
            ->when($first_name, function ($query) use ($first_name) {
                $query->whereHas('user', function ($q) use ($first_name) {
                    $q->where('first_name', 'like', "%{$first_name}%");
                });
            });

            $count = $query->count();
            $totalAmount = '--';
            //如果有指定用户和 时间区间，则统计投注额(时间区间需在30天内)
            if ((isset($params['member_id']) || isset($params['username'])) && isset($params['start_time'])) {
                $start = Carbon::parse($params['start_time']);
                $end = Carbon::parse($params['end_time']);
                if ($end->diffInDays($start) < 30) $totalAmount = $query->sum('amount');

            }

            $query->orderByDesc('id');
            $list = $query->forPage($page, $limit)->get()->toArray();


            foreach ($list as &$item) {
                $item['is_winner'] = null;
                $item['created_at'] = date('Y-m-d H:i', strtotime($item['created_at']));
                $issue = $item['issue'] ?: $item['pc_issue'];
                $item['winning_array'] = $issue['winning_array'];
                unset($item['issue'], $item['pc_issue']);
                if ($item['status'] == 2) {
                    $item['is_winner'] = $item['profit'] > 0;
                }
            }
            $result = ['total' => $count, 'total_amount' => $totalAmount, 'data' => $list];
        } catch (ValidationException $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error($e->getCode(), $e->getMessage());
        }
        return $this->success($result);
    }

    // 模拟下注
    public function fake()
    {
        BetService::randomVirtualBetting(3);
        return 'success';
    }
}