<?php

namespace App\Http\Controllers\admin;

use App\Services\LotteryImageService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\IssueService;

class Lottery extends Controller
{
    public function generate(Request $request, LotteryImageService $service)
    {

        $list = IssueService::model()::where(IssueService::getWhere(['status' => IssueService::model()::STATUS_DRAW]))->take(20)->orderBy('issue_no','desc')->get();
        $records = $list->toArray();

        foreach($records as $k => $v){
            $winning_numbers = explode(',',$v['winning_numbers']);
            $v['winning_numbers'] = $winning_numbers;

            // 组合
            $sum = array_sum($winning_numbers);

            $v['sum'] = $sum;
            $sumOddEven = IssueService::calculateOddEven($sum); // 总和单双

            $sumSize = IssueService::calculateSumSize($sum);  // 总和大小
            $v['combo'] = $sumSize . ' ' . $sumOddEven;

            $sumExtremeSize = IssueService::calculateSumExtremeSize($sum);  // 总和极值
            if(!$sumExtremeSize){
                $sumExtremeSize = '-';
            }
            $v['extreme'] = $sumExtremeSize;

            $tail = IssueService::getLastDigit($sum); // 总和尾数
            if($tail === 0){
                $tailStr = '-';
            }else{
                $tailStr = '尾' . $tail;
            }
            $v['tail'] = $tailStr;

            $records[$k] = $v;
        }
        
        // // 这里可以从接口传入数据，也可以先写死测试
        // $records = $request->input('records', [
        //     ['period' => '3350007', 'numbers' => [5, 2, 0], 'sum' => 7, 'combo' => '小 单', 'extreme' => '-', 'tail' => '尾7'],
        //     ['period' => '3350006', 'numbers' => [8, 9, 3], 'sum' => 20, 'combo' => '大 双', 'extreme' => '-', 'tail' => '尾0'],
        //     ['period' => '3350005', 'numbers' => [2, 6, 1], 'sum' => 9, 'combo' => '小 单', 'extreme' => '-', 'tail' => '尾9'],
        // ]);

        try {
            $url = $service->generate($records);
            // return response()->json(['code' => 0, 'url' => asset($url)]);
            return $this->success(['url' => $url]);
        } catch (\Throwable $e) {
            return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }
}
