<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Models;

use App\Business\Product\DberpDocumentLineUnitService;
use App\Business\Product\ProductBusinessSnapshot;
use App\Models\Concerns\HasDberpDocumentLineUnitRelations;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class DberpSalesOutboundOrderItem extends Model
{
    use HasDberpDocumentLineUnitRelations;

    protected $table = 'dberp_sales_outbound_order_items';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'order_id',
        'sales_order_item_id',
        'product_id',
        'product_sku_id',
        'product_code',
        'product_name',
        'sku_code',
        'spec_text',
        'unit_id',
        'unit_name',
        'base_unit_id',
        'auxiliary_unit_id',
        'is_auxiliary_unit',
        'auxiliary_unit_quantity',
        'base_unit_quantity',
        'source_batch_id',
        'batch_no',
        'production_date',
        'expiry_date',
        'shelf_life_days',
        'batch_allocations',
        'serial_numbers',
        'ship_quantity',
        'unit_price',
        'line_amount',
        'returned_quantity',
        'base_ship_quantity',
        'base_returned_quantity',
        'sort_order',
        'remark',
    ];

    protected static function booted(): void
    {
        static::saving(function (self $item): void {
            $salesOrderItemId = (int) ($item->sales_order_item_id ?? 0);
            if ($salesOrderItemId > 0) {
                $soLine = $item->relationLoaded('salesOrderItem')
                    ? $item->salesOrderItem
                    : DberpSalesOrderItem::query()->find($salesOrderItemId);

                if ($soLine instanceof DberpSalesOrderItem) {
                    $item->setAttribute('product_id', $soLine->product_id);
                    if ($soLine->product_sku_id !== null) {
                        $sku = DberpProductSku::query()->with(['product.unit'])->find($soLine->product_sku_id);
                        if ($sku instanceof DberpProductSku) {
                            $snap = ProductBusinessSnapshot::identityFromSku($sku);
                            $item->forceFill([
                                'product_sku_id' => $snap['product_sku_id'],
                                'product_code' => $snap['product_code'],
                                'product_name' => $snap['product_name'],
                                'sku_code' => $snap['sku_code'],
                                'spec_text' => $snap['spec_text'],
                            ]);
                        }
                    }
                }
            }

            DberpDocumentLineUnitService::applySnapshotsToLine($item);

            $shipQuantity = (float) ($item->ship_quantity ?? 0);
            $unitPrice = (float) ($item->unit_price ?? 0);

            $item->setAttribute('line_amount', number_format($shipQuantity * $unitPrice, 4, '.', ''));
        });

        static::saved(function (self $item): void {
            $item->order?->forceFill([
                'total_shipped_quantity' => (string) $item->order->items()->sum('ship_quantity'),
                'total_amount' => (string) $item->order->items()->sum('line_amount'),
            ])->save();
        });

        static::deleted(function (self $item): void {
            $item->order?->forceFill([
                'total_shipped_quantity' => (string) $item->order->items()->sum('ship_quantity'),
                'total_amount' => (string) $item->order->items()->sum('line_amount'),
            ])->save();
        });
    }

    protected function casts(): array
    {
        return [
            'order_id' => 'integer',
            'sales_order_item_id' => 'integer',
            'product_id' => 'integer',
            'product_sku_id' => 'integer',
            'unit_id' => 'integer',
            'base_unit_id' => 'integer',
            'auxiliary_unit_id' => 'integer',
            'is_auxiliary_unit' => 'boolean',
            'auxiliary_unit_quantity' => 'decimal:6',
            'base_unit_quantity' => 'decimal:6',
            'source_batch_id' => 'integer',
            'production_date' => 'date',
            'expiry_date' => 'date',
            'shelf_life_days' => 'integer',
            'batch_allocations' => 'array',
            'serial_numbers' => 'array',
            'ship_quantity' => 'decimal:4',
            'unit_price' => 'decimal:4',
            'line_amount' => 'decimal:4',
            'returned_quantity' => 'decimal:4',
            'base_ship_quantity' => 'decimal:4',
            'base_returned_quantity' => 'decimal:4',
            'sort_order' => 'integer',
        ];
    }

    public function order(): BelongsTo
    {
        return $this->belongsTo(DberpSalesOutboundOrder::class, 'order_id');
    }

    public function salesOrderItem(): BelongsTo
    {
        return $this->belongsTo(DberpSalesOrderItem::class, 'sales_order_item_id');
    }

    public function product(): BelongsTo
    {
        return $this->belongsTo(DberpProduct::class, 'product_id');
    }

    public function productSku(): BelongsTo
    {
        return $this->belongsTo(DberpProductSku::class, 'product_sku_id');
    }

    public function sourceBatch(): BelongsTo
    {
        return $this->belongsTo(DberpInventoryBatch::class, 'source_batch_id');
    }
}
