<?php

namespace App\Http\Controllers\admin;

use App\Constants\HttpStatus;
use App\Http\Controllers\Controller;
use App\Services\PcIssueService;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Exception;
use App\Models\PcIssue as PcIssueModel;

class PcIssue extends Controller
{
    /**
     * @api {get} /admin/pcIssue 列表
     * @apiGroup 极速28
     *
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     * @apiParam {int} [page=1]
     * @apiParam {int} [limit=10]
     * @apiParam {string} [issue_no] 期号
     *
     * @apiSuccess (data) {Object} data
     * @apiSuccess (data) {int} data.total 数量
     * @apiSuccess (data) {Object[]} data.data 列表
     * @apiSuccess (data) {int} data.data.id
     * @apiSuccess (data) {String} data.data.issue_no 期号
     * @apiSuccess (data) {String} data.data.combo 组合
     * @apiSuccess (data) {int} data.data.status 状态
     * - 1-投注中,2-封盘,3-开奖
     * @apiSuccess (data) {int[]} data.data.winning_array 开奖结果
     * - 如果已开奖会有4个值  分别为第一个开奖号码，第二个开奖号码，第三个开奖号码，总和
     * @apiSuccess (data) {int} data.data.advance_code 预开奖号码
     *
     */
    public function index()
    {
        try {
            $search = request()->validate([
                'page' => ['nullable', 'integer', 'min:1'],
                'limit' => ['nullable', 'integer', 'min:1'],
                'issue_no' => ['nullable', 'string'],
            ]);
            $page = request()->input('page', 1);
            $limit = request()->input('limit', 15);
            $result['total'] = PcIssueModel::where(PcIssueModel::getWhere($search))->count();
            $result['data'] = PcIssueModel::where(PcIssueModel::getWhere($search))
                ->orderByDesc('id')->forPage($page, $limit)->get();
        } catch (ValidationException $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error(intval($e->getCode()));
        }
        return $this->success($result);
    }

    /**
     * @api {post} /admin/pcIssue/preDraw 预开奖
     * @apiGroup 极速28
     *
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     * @apiParam {string} issue_no 期号
     * @apiParam {int} he 预开奖号码
     * - 开奖号码取值范围：0-27
     *
     */
    public function preDraw()
    {
        DB::beginTransaction();
        try {
            request()->validate([
                'issue_no' => ['required', 'string'],
                'he' => ['required', 'integer', 'min:0', 'max:27'],
            ]);
            $issueNo = request()->input('issue_no');
            $he = request()->input('he');
            $he = intval($he);
            $pcIssue = PcIssueModel::where('issue_no', $issueNo)->first();
            if (!$pcIssue) throw new Exception('期号错误', HttpStatus::CUSTOM_ERROR);
            if (!in_array($pcIssue->status, [PcIssueModel::STATUS_BETTING, PcIssueModel::STATUS_CLOSE])) {
                throw new Exception('预开奖失败；状态不正确', HttpStatus::CUSTOM_ERROR);
            }
            $keno = PcIssueService::getMatchingNumbers($he);
            sort($keno);
            $pcIssue->advance_keno = json_encode($keno);
            $pcIssue->advance_code = $he;
            $pcIssue->save();
            $winningNumbers = PcIssueService::getWinningNumbers($keno);
            DB::commit();
        } catch (ValidationException $e) {
            DB::rollBack();
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            DB::rollBack();
            if ($e->getCode() == HttpStatus::CUSTOM_ERROR) {
                return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
            }
            return $this->error(intval($e->getCode()));
        }
        return $this->success($winningNumbers);

    }
}