<?php

declare(strict_types=1);

namespace Kylin\Manufacturing\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * OEE 记录
 */
class OeeRecord extends Model
{
    protected $table = 'kylin_mfg_oee_records';

    protected $fillable = [
        'equipment_id',
        'date',
        'planned_time',
        'run_time',
        'actual_output',
        'qualified_output',
        'availability',
        'performance',
        'quality',
        'oee',
    ];

    protected function casts(): array
    {
        return [
            'date' => 'date',
            'planned_time' => 'integer',
            'run_time' => 'integer',
            'actual_output' => 'integer',
            'qualified_output' => 'integer',
            'availability' => 'decimal:2',
            'performance' => 'decimal:2',
            'quality' => 'decimal:2',
            'oee' => 'decimal:2',
        ];
    }

    public function equipment(): BelongsTo
    {
        return $this->belongsTo(Equipment::class);
    }

    /**
     * 按 ISO 22400-2 标准计算 OEE
     */
    public static function calculate(int $plannedTime, int $runTime, int $actualOutput, int $qualifiedOutput, int $theoreticalOutputPerHour): array
    {
        $availability = $plannedTime > 0 ? round($runTime / $plannedTime * 100, 2) : 0;
        $runHours = $runTime / 60;
        $performance = ($runHours > 0 && $theoreticalOutputPerHour > 0)
            ? round($actualOutput / ($theoreticalOutputPerHour * $runHours) * 100, 2) : 0;
        $quality = $actualOutput > 0 ? round($qualifiedOutput / $actualOutput * 100, 2) : 0;
        $oee = round($availability * $performance * $quality / 10000, 2);

        return compact('availability', 'performance', 'quality', 'oee');
    }
}
