<?php

namespace Kylin\Logistics\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Kylin\Logistics\Enums\CargoType;
use Kylin\Logistics\Enums\SettlementType;
use Kylin\Logistics\Enums\WaybillStatus;

/**
 * 运单模型
 *
 * 物流运单，记录货物运输的完整信息：
 *  - 发货方/收货方
 *  - 货物类型与重量
 *  - 车辆与司机分配
 *  - 运单状态追踪
 *
 * @property int          $id
 * @property string       $waybill_no    运单号
 * @property WaybillStatus $status       运单状态
 * @property CargoType    $cargo_type    货物类型
 */
class Waybill extends Model
{
    protected $table = 'kylin_log_waybills';

    protected $fillable = [
        'waybill_no', 'shipper_name', 'shipper_phone',
        'shipper_address', 'consignee_name', 'consignee_phone',
        'consignee_address', 'cargo_name', 'cargo_type',
        'cargo_weight', 'cargo_volume', 'cargo_quantity',
        'package_type', 'freight_amount', 'settlement_type',
        'required_arrival', 'remark', 'status', 'creator_id',
    ];

    protected $casts = [
        'cargo_type' => CargoType::class,
        'settlement_type' => SettlementType::class,
        'status' => WaybillStatus::class,
        'cargo_weight' => 'decimal:2',
        'cargo_volume' => 'decimal:2',
        'freight_amount' => 'decimal:2',
        'required_arrival' => 'datetime',
    ];

    public function dispatch(): HasOne
    {
        return $this->hasOne(Dispatch::class);
    }

    public function signRecord(): HasOne
    {
        return $this->hasOne(SignRecord::class);
    }

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

    public function creator(): BelongsTo
    {
        return $this->belongsTo(config('auth.providers.users.model'), 'creator_id');
    }

    /**
     * 生成运单编号 - WB+YYYYMMDD+4位流水
     */
    public static function generateWaybillNo(): string
    {
        $prefix = config('kylin-logistics.waybill_prefix', 'WB') . now()->format('Ymd');
        $lastNo = static::where('waybill_no', 'like', $prefix . '%')
            ->orderByDesc('waybill_no')
            ->value('waybill_no');
        $seq = $lastNo ? (int) substr($lastNo, -4) + 1 : 1;
        return $prefix . str_pad((string) $seq, 4, '0', STR_PAD_LEFT);
    }
}
