<?php

namespace App\Models;

class PcPrediction extends BaseModel
{
    protected $table = 'pc_prediction';
    protected $fillable = ['issue_no', 'size', 'odd_or_even', 'is_valid', 'winning_numbers', 'time'];
    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): PcPrediction
    {
        $issue = PcIssue::where('issue_no', $issueNo)->first();
        $size = mt_rand(static::SIZE_SMALL, static::SIZE_BIG);
        $oddOrEven = mt_rand(static::ODD, static::EVEN);
        return static::create([
            'issue_no' => $issueNo,
            'size' => $size,
            'odd_or_even' => $oddOrEven,
            'time' => $issue->end_time
        ]);
    }

    //预测结果
    static function result($issueNo, $winningNumbers, $awards): void
    {


        $data = static::where('issue_no', $issueNo)->first();
        if (!$data) $data = static::prediction($issueNo);


        $size = in_array("大", $awards) ? "大" : "小";
        $oddOrEven = in_array("双", $awards) ? "双" : "单";
        $size = $size == '大' ? static::SIZE_BIG : static::SIZE_SMALL;
        $oddOrEven = $oddOrEven == '双' ? static::EVEN : static::ODD;
        $data->is_valid = static::VALID_ERROR;
        if ($data->size == $size || $data->odd_or_even == $oddOrEven) {
            $data->is_valid = static::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 [];
    }
}