<?php

namespace App\Http\Controllers\api;

use App\Models\Cao;
use App\Models\CaoHistory;
use App\Models\Issue as IssueModel;
use App\Models\Prediction;
use App\Services\IssueService;
use Illuminate\Validation\ValidationException;
use Exception;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;

class Issue extends BaseController
{

    /**
     * @api {get} /issue/yuanTou 源头
     * @apiGroup Issue
     * @apiVersion 1.0.0
     * @apiSuccess {int} code
     * @apiSuccess {int} timestamp
     * @apiSuccess {String} msg
     * @apiSuccess {Object[]} data
     *
     */
    function yuanTou(): JsonResponse
    {
        $page = max(1, (int)request()->input('page', 1));
        $limit = min(max(1, (int)request()->input('limit', 20)), 100);

        $issues = IssueModel::where('status', IssueModel::STATUS_DRAW)
            ->whereNotNull('keno')
            ->where('keno', '!=', '')
            ->orderByDesc('issue_no')
            ->forPage($page, $limit)
            ->get();

        $data = [];
        foreach ($issues as $issue) {
            $keno = $this->formatYuanTouKeno($issue->keno);
            if (empty($keno)) {
                continue;
            }

            $winningNumbers = array_map('intval', explode(',', $issue->winning_numbers));
            $item = [
                'section' => (string)$issue->issue_no,
                'openTime' => empty($issue->start_time) ? '' : date('m-d H:i', strtotime($issue->start_time)),
                'keno' => $keno,
                'keno_html' => '',
            ];

            for ($index = 1; $index <= 10; $index++) {
                $item['openCode' . $index] = (string)($winningNumbers[$index - 1] ?? 0);
            }

            $data[] = $item;
        }

        return $this->success($data);
    }

    private function formatYuanTouKeno($keno): array
    {
        if (is_string($keno)) {
            $decoded = json_decode($keno, true);
            $keno = is_array($decoded) ? $decoded : explode(',', $keno);
        }

        if (!is_array($keno)) {
            return [];
        }

        $numbers = [];
        foreach ($keno as $number) {
            $value = filter_var($number, FILTER_VALIDATE_INT, [
                'options' => [
                    'min_range' => 1,
                    'max_range' => 80,
                ],
            ]);

            if ($value !== false) {
                $numbers[] = (int)$value;
            }
        }

        $numbers = array_values(array_unique($numbers));
        sort($numbers, SORT_NUMERIC);

        return array_map('strval', $numbers);
    }


    /**
     * @api {get} /issue/history 天机
     * @apiGroup Issue
     * @apiVersion 1.0.0
     *
     * @apiParam {int} [date] 日期 默认0
     * - 前1天  则date=1 前2天则date=2
     *
     * @apiSuccess {int} code
     * @apiSuccess {int} timestamp
     * @apiSuccess {String} msg
     * @apiSuccess {Object[]} data
     * @apiSuccess {String} data.date
     * @apiSuccess {int} data.total 总数
     * @apiSuccess {int} data.big 大
     * @apiSuccess {int} data.small 小
     * @apiSuccess {int} data.odd 单
     * @apiSuccess {int} data.even 双
     * @apiSuccess {int} data.big_odd 大单
     * @apiSuccess {int} data.big_even 大双
     * @apiSuccess {int} data.small_odd 小单
     * @apiSuccess {int} data.small_even 小双
     * @apiSuccess {int} data.max 极大
     * @apiSuccess {int} data.min 极小
     * @apiSuccess {int} data.pair 对子
     * @apiSuccess {int} data.sequence 顺子
     * @apiSuccess {int} data.leopard 豹子
     * @apiSuccess {int} data.num_0 00号
     * @apiSuccess {int} data.num_1 01号
     *
     */
    function history()
    {
        try {
            request()->validate([
                'date' => ['required', 'integer', 'min:0', 'max:30']
            ]);
            $date = request()->input('date');
            $date = Carbon::now()->subDays($date)->toDateString();
            $list = CaoHistory::where('date', $date)->get()->toArray();
            if (count($list) > 0) {
                $list = $list[0];
            } else {
                $list = null;
            }
        } catch (ValidationException $e) {
            return $this->error($e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success($list);
    }

    /**
     * @api {get} /issue/prediction 预测
     * @apiGroup Issue
     * @apiVersion 1.0.0
     *
     * @apiSuccess {int} code
     * @apiSuccess {int} timestamp
     * @apiSuccess {String} msg
     * @apiSuccess {Object} data
     *
     * @apiParam {int} [page=1]
     * @apiParam {int} [limit=10]
     *
     * @apiSuccess {int} code
     * @apiSuccess {int} timestamp
     * @apiSuccess {String} msg
     * @apiSuccess {Object[]} data
     * @apiSuccess {int} data.id
     * @apiSuccess {String} data.issue_no 期号
     * @apiSuccess {int} data.size 预测大小：0小，1大
     * @apiSuccess {int} data.odd_or_even 预测单双:0单，1双
     * @apiSuccess {int} data.is_valid 结果：0错误，1正确
     * @apiSuccess {int[]} data.winning_numbers 开奖结果
     */
    function prediction()
    {
        try {
            request()->validate([
                'page' => ['nullable', 'integer', 'min:1'],
                'limit' => ['nullable', 'integer', 'min:1']
            ]);
            $page = request()->input('page', 1);
            $limit = request()->input('limit', 10);
            $list = Prediction::forPage($page, $limit)
                ->orderByDesc('issue_no')
                ->get();
            foreach ($list as &$item) {
                $item['day'] = date("m-d H:i", strtotime($item['updated_at']));
            }


        } catch (ValidationException $e) {
            return $this->error($e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success($list);
    }

    /**
     * @api {get} /issue/countdown 倒计时
     * @apiGroup Issue
     * @apiVersion 1.0.0
     *
     * @apiSuccess {int} code
     * @apiSuccess {int} timestamp
     * @apiSuccess {String} msg
     * @apiSuccess {Object} data
     * @apiSuccess {String} data.issue_no 期号
     * @apiSuccess {int} data.current_time 当前时间
     * @apiSuccess {int} data.end_time 结束时间
     * @apiSuccess {Object} data.winnings 开奖结果
     *
     */
    public function countdown(): JsonResponse
    {
        //获取最新一期已开奖的数据
        $data2 = \App\Models\Issue::where('status', \App\Models\Issue::STATUS_DRAW)->orderByDesc('issue_no')->first();

        $issue_no2 = $data2->issue_no + 1;
        $issue_no2 .= '';
        $data1 = \App\Models\Issue::where('issue_no', $issue_no2)->first();
        $end_time = $data1 ? strtotime($data1->end_time) : (bcadd(strtotime($data2->end_time), 210, 0));

        $winnings = explode(',', $data2->winning_numbers);
        $winnings = array_map('intval', $winnings);
        $award = IssueService::award($winnings);
        $arr['sum'] = array_sum($winnings);
        $arr['a'] = $winnings[0];
        $arr['b'] = $winnings[1];
        $arr['c'] = $winnings[2];

        $arr['size'] = in_array('大', $award) ? '大' : "小";
        $arr['size'] = lang($arr['size']);
        $arr['odd_or_even'] = in_array('单', $award) ? '单' : "双";
        $arr['odd_or_even'] = lang($arr['odd_or_even']);
        $arr['issue_no'] = $data2->issue_no;
        $data = [
            'issue_no' => $issue_no2,
            'current_time' => time(),
            'end_time' => $end_time,
//            'winnings' => $arr,
        ];
        if ($data['end_time'] < $data['current_time']) {
            $data['end_time'] += 210;
        }
        $data['aa'] = $data['end_time'] - $data['current_time'];
        $data['winnings'] = $arr;
        return $this->success($data);
    }


    /**
     * @api {get} /issue 结果，走势
     * @apiGroup Issue
     * @apiVersion 1.0.0
     *
     * @apiParam {int} [page=1]
     * @apiParam {int} [limit=10]
     *
     * @apiSuccess {int} code
     * @apiSuccess {int} timestamp
     * @apiSuccess {String} msg
     * @apiSuccess {Object[]} data
     * @apiSuccess {int} data.id
     * @apiSuccess {String} data.issue_no 期号
     * @apiSuccess {String} data.start_time 开始时间
     * @apiSuccess {String} data.end_time 结束时间
     * @apiSuccess {String[]} data.award 开奖结果
     * @apiSuccess {String[]} data.winning_array 开奖结果
     * @apiSuccess {int} data.end_timestamp 结束时间 时间戳
     *
     */
    public function index()
    {
        try {
            $page = request()->input('page', 1);
            $limit = request()->input('limit', 10);
            $params = [
                'page' => $page,
                'limit' => $limit
//            'status'=>3
            ];
            $res = IssueService::paginate($params);
            foreach ($res['data'] as &$item) {
                $item['day'] = date("m-d H:i", strtotime($item['end_time']));
                if ($item['combo']) {
                    $combo = explode(" ", $item['combo']);
                    foreach($combo as &$v) {
                        if (stripos($v, '尾') !== false) {
                            $v = str_replace('尾', lang('尾'), $v);
                        } elseif (stripos($v, '头') !== false) {
                            $v = str_replace('头', lang('头'), $v);
                        } elseif (stripos($v, '操') !== false) {
                            $v = str_replace('操', lang('操'), $v);
                        } else {
                            $v = lang($v);
                        }
                    }
                    $item['combo'] = $combo;
                } else {
                    $item['combo'] = [];
                }
            }
        } catch (ValidationException $e) {
            return $this->error($e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success($res);
    }

    /**
     * @api {get} /issue/cao 统计，历史
     * @apiGroup Issue
     * @apiVersion 1.0.0
     *
     * @apiSuccess {int} code
     * @apiSuccess {int} timestamp
     * @apiSuccess {String} msg
     * @apiSuccess {Object} data
     * @apiSuccess {int} data.total 总期数
     * @apiSuccess {Object[]} data.list 列表
     *
     */
    public function cao()
    {
        $type = [1, 2, 3, 4];
        $list = [];
        $list['dxds'] = Cao::whereIn('id', $type)->get();
        $type = [5, 6, 7, 8];
        $list['zh'] = Cao::whereIn('id', $type)->get();
        $type = [9, 10];
        $list['jz'] = Cao::whereIn('id', $type)->get();
        $list['hb'] = [
            ['field' => '2.8回本', 'val' => 0],
            ['field' => '3.2回本', 'val' => 0],
        ];
        $type = [11, 12, 13];
        $list['bsd'] = Cao::whereIn('id', $type)->get();
        $list['ddsz'] = Cao::where('id', '>=', 14)
            ->where('id', '<=', 41)
            ->orderBy('id')
            ->get();
        $list['tslx'] = [
            ['field' => '龙', 'val' => 0],
            ['field' => '虎', 'val' => 0],
            ['field' => '合', 'val' => 0],
            ['field' => '鸡', 'val' => 0],
            ['field' => '鸭', 'val' => 0],
            ['field' => '狗', 'val' => 0],
        ];
        $list['zbtj'] = [
            ['field' => '中', 'val' => 0],
            ['field' => '边', 'val' => 0],
            ['field' => '大边', 'val' => 0],
            ['field' => '小边', 'val' => 0],
        ];
        $list['wei_shu'] = Cao::where('id', '>=', 42)
            ->where('id', '<=', 49)
            ->get();
        $list['san_jun'] = [
            ['field' => '三军0点', 'val' => 0],
            ['field' => '三军1点', 'val' => 0],
            ['field' => '三军2点', 'val' => 0],
            ['field' => '三军3点', 'val' => 0],
            ['field' => '三军4点', 'val' => 0],
            ['field' => '三军5点', 'val' => 0],
            ['field' => '三军6点', 'val' => 0],
            ['field' => '三军7点', 'val' => 0],
            ['field' => '三军8点', 'val' => 0],
            ['field' => '三军9点', 'val' => 0],
        ];
        $list['qu_a'] = Cao::where('id', '>=', 50)
            ->where('id', '<=', 63)
            ->get();
        $list["qu_b"] = Cao::where('id', '>=', 64)
            ->where('id', '<=', 77)
            ->get();
        $list["qu_c"] = Cao::where('id', '>=', 78)
            ->where('id', '<=', 91)
            ->get();

        $count = Cao::whereIn('id', [1, 2])->sum('val');
        $data = [
            'total' => intval($count),
            'list' => $list
        ];

        return $this->success($data);
    }

}