<?php

namespace App\Http\Controllers\admin;

use App\Constants\HttpStatus;
use App\Http\Controllers\Controller;
use App\Services\BaseService;
use App\Services\IssueService;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Exception;

class Issue extends Controller
{
    public function fakeLotteryDraw()
    {
        IssueService::fakeLotteryDraw();
        return $this->success();
    }

    /**
     * @description: 分页数据
     * @return {*}
     */
    function index()
    {
        try {
            request()->validate([
                'issue_no' => ['nullable', 'string'],
                'id' => ['nullable', 'string'],
                'status' => ['nullable', 'string'],
            ]);
            $search = request()->all();
            $result = IssueService::paginate($search);
        } catch (ValidationException $e) {
            return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error(intval($e->getCode()));
        }
        return $this->success($result);
    }

    /**
     * @description: 异常分页数据
     * @return {*}
     */
    function abnormal()
    {
        try {
            request()->validate([
                'issue_no' => ['nullable', 'string'],
                'id' => ['nullable', 'string'],
                'status' => ['nullable', 'string'],
            ]);
            $search = request()->all();
            $search['abnormal'] = 1;
            $result = IssueService::paginate($search);
        } catch (ValidationException $e) {
            return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error(intval($e->getCode()));
        }
        return $this->success($result);
    }

    /**
     * @description: 修改|新增
     * @return {*}
     */
    public function store()
    {
        return $this->error(HttpStatus::CUSTOM_ERROR, '禁止编辑');
        // try {
        $params = request()->all();

        $validator = [
            'issue_no' => 'required|string|max:50|alpha_dash|unique:issues,issue_no',
            'winning_numbers' => 'nullable|string|max:100',
            'status' => 'nullable|string',
        ];

        request()->validate($validator);

        $ret = IssueService::submit($params);
        if ($ret['code'] == IssueService::NOT) {
            return $this->error($ret['code'], $ret['msg']);
        }
        // } catch (ValidationException $e) {
        //     return $this->error(HttpStatus::VALIDATION_FAILED, '', $e->errors());
        // } catch (Exception $e) {
        //     return $this->error(intval($e->getCode()));
        // }
        return $this->success([], $ret['msg']);

    }

    // 开奖失败
    public function failure()
    {
        $id = request()->input('id');
        if (!$id) {
            return $this->error(HttpStatus::VALIDATION_FAILED, '参数错误');
        }
        $ret = IssueService::lotteryDrawFail($id);
        if ($ret['code'] == IssueService::NOT) {
            return $this->error($ret['code'], $ret['msg']);
        }
        return $this->success([], $ret['msg']);
    }

    /**
     * @description: 开始
     * @return {*}
     */
    public function betting()
    {
        $id = request()->input('id');
        if (!$id) {
            return $this->error(HttpStatus::VALIDATION_FAILED, '参数错误');
        }
        $ret = IssueService::betting($id);
        if ($ret['code'] == IssueService::NOT) {
            return $this->error($ret['code'], $ret['msg']);
        }
        return $this->success([], $ret['msg']);
    }

    /**
     * @description: 关闭
     * @return {*}
     */
    public function close()
    {
        $id = request()->input('id');
        if (!$id) {
            return $this->error(HttpStatus::VALIDATION_FAILED, '参数错误');
        }
        $ret = IssueService::closeBetting($id);
        if ($ret['code'] == IssueService::NOT) {
            return $this->error($ret['code'], $ret['msg']);
        }
        return $this->success([], $ret['msg']);
    }

    /**
     * @description: 开奖
     * @return {*}
     */
    public function lotteryDraw()
    {
        $id = request()->input('id');
        $winning_numbers = request()->input('winning_numbers');
        $keno = null;

        if (!$id) {
            return $this->error(HttpStatus::CUSTOM_ERROR, '参数错误');
        }
        if (empty($winning_numbers)) {
            $issue = IssueService::findOne(['id' => $id]);
            if (!$issue) {
                return $this->error(HttpStatus::CUSTOM_ERROR, '期号不存在');
            }

            $playNowInfo = IssueService::getPlayNowWinningInfo($issue->issue_no);
            if ($playNowInfo['code'] == IssueService::NOT) {
                return $this->error(HttpStatus::CUSTOM_ERROR, $playNowInfo['msg']);
            }

            $winning_numbers = $playNowInfo['winning_numbers'];
            $keno = $playNowInfo['source_numbers'] ?? null;
        }
        $winningNumberList = array_map('trim', explode(',', $winning_numbers));
        if (count($winningNumberList) !== 3) {
            return $this->error(HttpStatus::CUSTOM_ERROR, '开奖号码格式错误');
        }

        $winArr = [];
        foreach ($winningNumberList as $number) {
            $value = filter_var($number, FILTER_VALIDATE_INT, [
                'options' => [
                    'min_range' => 0,
                    'max_range' => 9,
                ],
            ]);
            if ($value === false) {
                return $this->error(HttpStatus::CUSTOM_ERROR, '开奖号码格式错误');
            }
            $winArr[] = (int)$value;
        }
        $winning_numbers = implode(',', $winArr);
        $combo = IssueService::getCombo($winArr);
        $ret = IssueService::lotteryDraw($id, $winning_numbers, $combo, "", $keno);
        if ($ret['code'] == BaseService::NOT) {
            return $this->error($ret['code'], $ret['error'] ?? $ret['msg']);
        }
        return $this->success([], $ret['msg']);
    }

    /**
     * @description: 删除
     */
    public function destroy()
    {
        return $this->error(HttpStatus::CUSTOM_ERROR, '禁止删除');
        $id = request()->post('id');
        // 示例：通过 ID 删除
        $info = IssueService::findOne(['id' => $id]);
        if (!$info) {
            return $this->error(0, '期数不存在');
        }

        $info->delete();

        return $this->success([], '删除成功');
    }
}