<?php

namespace BYDAuto\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

/**
 * 经销商门店 class.
 *
 * @property int $id
 * @property string $sn
 * @property string $region
 * @property string $province
 * @property string $city
 * @property string $county
 * @property string $district
 * @property string $type
 * @property string $erp
 * @property string $name
 * @property string $alias
 * @property string $group
 * @property string $address
 */
class Dealer extends Model
{
    public $timestamps = false;

    protected $table = 'bydauto_dealers';

    protected $fillable = ['sn', 'region', 'province', 'city', 'county', 'district', 'type', 'erp', 'name', 'alias', 'group', 'address', 'lat', 'lng'];

    public function vehicles()
    {
        return $this->belongsToMany(Vehicle::class, 'bydauto_dealer_vehicles', 'dealer_id', 'vehicle_id');
    }

    public static function cachedItems()
    {
        return Cache::remember('BYDAuto:dealers', 120, fn () => static::query()->get());
    }

    public static function findByAlias($alias)
    {
        $items = self::cachedItems();
        return $items->first(fn ($d) => $d->alias === $alias);
    }

    public static function findByName($name)
    {
        $items = self::cachedItems();
        return $items->first(fn ($d) => $d->name === $name);
    }
}
