<?php

declare(strict_types=1);

namespace Kylin\Manufacturing\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Kylin\Manufacturing\Enums\WorkOrderStatus;
use Kylin\Manufacturing\Enums\Priority;

/**
 * 工单
 */
class WorkOrder extends Model
{
    protected $table = 'kylin_mfg_work_orders';

    protected $fillable = [
        'work_order_no',
        'title',
        'bom_id',
        'process_route_id',
        'planned_quantity',
        'actual_quantity',
        'qualified_quantity',
        'scrap_quantity',
        'status',
        'priority',
        'production_line_id',
        'planned_start_at',
        'planned_end_at',
        'actual_start_at',
        'actual_end_at',
        'creator_id',
        'assignee_id',
    ];

    protected function casts(): array
    {
        return [
            'status' => WorkOrderStatus::class,
            'priority' => Priority::class,
            'planned_quantity' => 'integer',
            'actual_quantity' => 'integer',
            'qualified_quantity' => 'integer',
            'scrap_quantity' => 'integer',
            'planned_start_at' => 'datetime',
            'planned_end_at' => 'datetime',
            'actual_start_at' => 'datetime',
            'actual_end_at' => 'datetime',
        ];
    }

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

    public function creator(): BelongsTo
    {
        return $this->belongsTo(\App\Models\User::class, 'creator_id');
    }

    public function assignee(): BelongsTo
    {
        return $this->belongsTo(\App\Models\User::class, 'assignee_id');
    }

    public function inspectionRecords(): HasMany
    {
        return $this->hasMany(InspectionRecord::class);
    }

    public function abnormalRecords(): HasMany
    {
        return $this->hasMany(AbnormalRecord::class);
    }

    public function completionRate(): float
    {
        if ($this->planned_quantity === 0) {
            return 0.0;
        }

        return round($this->actual_quantity / $this->planned_quantity * 100, 2);
    }

    public function qualificationRate(): float
    {
        if ($this->actual_quantity === 0) {
            return 0.0;
        }

        return round($this->qualified_quantity / $this->actual_quantity * 100, 2);
    }
}
