<?php

namespace App\Models;

class Prediction extends BaseModel
{
    protected $table = 'prediction';
    protected $fillable = ['issue_no', 'size','updated_at','created_at', 'odd_or_even', 'is_valid', 'winning_numbers'];

    const SIZE_BIG = 1;//预测大小:大
    const SIZE_SMALL = 0;//预测大小:小
    const ODD = 0;//预测单双:单
    const EVEN = 1;//预测单双:双
    const VALID_CORRECT = 1;//预测结果：正确
    const VALID_ERROR = 0;//预测结果：错误


    //预测
    static function prediction($issueNo): Prediction
    {
        $size = mt_rand(Prediction::SIZE_SMALL, Prediction::SIZE_BIG);
        $oddOrEven = mt_rand(Prediction::ODD, Prediction::EVEN);
        return static::create([
            'issue_no' => $issueNo,
            'size' => $size,
            'odd_or_even' => $oddOrEven
        ]);
    }

    //预测结果
    static function result($issueNo, $size, $oddOrEven, $winningNumbers): void
    {
        $data = static::where('issue_no', $issueNo)->first();
        if (!$data) $data = static::prediction($issueNo);
        $size = $size == '大' ? Prediction::SIZE_BIG : Prediction::SIZE_SMALL;
        $oddOrEven = $oddOrEven == '双' ? Prediction::EVEN : Prediction::ODD;
        $data->is_valid = Prediction::VALID_ERROR;
        if ($data->size == $size || $data->odd_or_even == $oddOrEven) {
            $data->is_valid = Prediction::VALID_CORRECT;
        }
        $data->winning_numbers = $winningNumbers;
        $data->save();

    }


    function getWinningNumbersAttribute($value)
    {
        if (!empty($value)) {
            $value = explode(',', $value);
            $value = array_map('intval', $value);
            $value[] = array_sum($value);
            return $value;
        }
        return [];
    }


}