using System.Collections.Generic;
using UnityEngine;
///
/// Ноутбук гаража [K]: вкладка «Магазин запчастей и жидкостей» (выдача на стол в гараже или на кассе АЗС)
/// и вкладка «Склад запчастей / Продажа на Куфар» со снятыми деталями, их состоянием, зарядкой АКБ и продажей.
///
public class GarageWarehouseUI : MonoBehaviour
{
private enum Tab { Shop, Warehouse }
private class ShopItem
{
public string title;
public string category;
public float price;
public System.Action spawn;
}
[SerializeField] private KeyCode openKey = KeyCode.K;
[SerializeField] private float wheelPrice = 85f;
[SerializeField] private float chargePrice = 8f;
public static GarageWarehouseUI Instance { get; private set; }
private bool isOpen;
private Tab tab = Tab.Shop;
private Vector2 scroll;
private int deliveryIndex;
private Transform customDelivery;
private string statusLine;
private readonly List items = new List();
private Transform player;
private void Awake() => Instance = this;
private void OnDestroy() { if (Instance == this) Instance = null; }
private void Update()
{
if (isOpen)
{
if (Input.GetKeyDown(KeyCode.Escape) || Input.GetKeyDown(openKey)) Close();
return;
}
if (!Input.GetKeyDown(openKey) || GameInputLock.IsLocked || VehicleInteraction.Current != null) return;
MainMenuAndBootManager menu = MainMenuAndBootManager.Instance;
if (menu != null && !menu.IsPlaying) return;
GameEconomyManager eco = GameEconomyManager.Instance;
if (eco != null && !eco.DiplomaFeatures)
{
GameHUD.Notify("Магазин и склад «Куфар» доступны в Дипломной версии", GameUI.Muted);
return;
}
if (ShopCounter.PlayerNearby != null)
{
Open(ShopCounter.PlayerNearby.DeliveryPoint);
return;
}
if (PlayerPos(out Vector3 p) && eco != null && !eco.IsInGarage(p))
{
GameHUD.Notify("Ноутбук магазина и склада находится в гараже (или на кассе АЗС)", GameUI.Accent);
return;
}
Open(null);
}
private bool PlayerPos(out Vector3 pos)
{
if (player == null)
{
PlayerMovement pm = FindAnyObjectByType();
if (pm != null) player = pm.transform;
}
pos = player != null ? player.position : Vector3.zero;
return player != null;
}
public void Open(Transform deliveryOverride)
{
customDelivery = deliveryOverride;
isOpen = true;
statusLine = deliveryOverride != null ? "Заказы выдаются на кассе магазина автохимии" : "Заказы выдаются на стол выдачи в гараже";
GameInputLock.Lock(this);
ProceduralAudioManager.Instance?.Play(SfxId.Notification);
}
private void Close()
{
isOpen = false;
GameInputLock.Unlock(this);
}
private Vector3 NextDeliveryPos()
{
int i = deliveryIndex++;
if (customDelivery != null)
{
int slot = i % 5;
return customDelivery.position + customDelivery.right * ((slot - 2) * 0.45f) + Vector3.up * (0.3f + (i / 5 % 3) * 0.35f);
}
GameEconomyManager eco = GameEconomyManager.Instance;
return eco != null ? eco.GetDeliveryPosition(i % 15) : Vector3.up;
}
// ===================== МАГАЗИН =====================
private void BuildShop()
{
items.Clear();
foreach (EnginePartType t in new[] { EnginePartType.Battery, EnginePartType.SparkPlugs, EnginePartType.AirFilter, EnginePartType.OilFilter, EnginePartType.Radiator, EnginePartType.Alternator })
{
EnginePartType type = t;
CarPartData d = PartCatalog.Instance.GetEngineData(type);
float price = d != null && d.basePrice > 0f ? d.basePrice : EnginePart.GetDefaultPrice(type);
items.Add(new ShopItem
{
title = EnginePart.GetDisplayName(type) + " (новый)",
category = "Подкапотные агрегаты",
price = price,
spawn = pos => EnginePartFactory.CreatePart(type, null, pos, Quaternion.identity, 0.6f, true)
});
}
foreach (FluidType t in new[] { FluidType.EngineOil, FluidType.Coolant, FluidType.BrakeFluid, FluidType.WasherFluid })
{
FluidType type = t;
items.Add(new ShopItem
{
title = FluidCanister.GetDefaultTitle(type),
category = "Автохимия и жидкости",
price = CanisterPrice(type),
spawn = pos => SpawnCanister(type, pos)
});
}
// Колеса и кузовные детали для машин игрока в гараже
foreach (CarOwnership car in CarOwnership.All)
{
if (car == null || !car.isOwned) continue;
CarPart wheelTemplate = null;
foreach (CarPart p in car.GetComponentsInChildren(true))
{
if (!p.IsWheel) continue;
if (wheelTemplate == null || (p.State == PartState.Installed && p.gameObject.activeInHierarchy)) wheelTemplate = p;
}
if (wheelTemplate != null)
{
CarPart template = wheelTemplate;
items.Add(new ShopItem
{
title = $"Колесо в сборе — {car.carTitle}",
category = "Колеса",
price = wheelPrice,
spawn = pos => CarWheelCondition.CreateSpareFrom(template, pos)
});
}
foreach (CarPartMountZone z in car.GetComponentsInChildren(true))
{
CarPart target = z.TargetPart;
if (target == null || target.IsWheel || target.GetComponent() != null) continue;
if (target.gameObject.activeInHierarchy) continue; // Снятая деталь лежит рядом — её можно поставить обратно
CarPart t2 = target;
items.Add(new ShopItem
{
title = $"{t2.DisplayName} — {car.carTitle}",
category = "Кузовные панели",
price = t2.Data != null ? t2.Data.basePrice : 150f,
spawn = pos => t2.SpawnAsNewPart(pos)
});
}
}
}
private static float CanisterPrice(FluidType t)
{
switch (t)
{
case FluidType.EngineOil: return 38f;
case FluidType.Coolant: return 22f;
case FluidType.BrakeFluid: return 12f;
default: return 6f;
}
}
public static FluidCanister SpawnCanister(FluidType type, Vector3 pos)
{
GameObject prefab = PartCatalog.Instance.GetCanister(type);
GameObject go;
if (prefab != null)
{
go = Instantiate(prefab, pos, Quaternion.identity);
}
else
{
go = new GameObject("Canister_" + type);
go.transform.position = pos;
EnginePartFactory.Prim(PrimitiveType.Cube, go.transform, "Body", Vector3.zero, new Vector3(0.2f, 0.28f, 0.12f),
PartCatalog.Instance.GetMaterial("canister_" + type, FluidCanister.GetDefaultColor(type)));
BoxCollider bc = go.AddComponent();
bc.size = new Vector3(0.2f, 0.3f, 0.12f);
go.AddComponent();
}
go.layer = EnginePartFactory.InteractLayer;
FluidCanister can = go.GetComponent();
if (can == null) can = go.AddComponent();
can.Configure(type, FluidCanister.GetDefaultTitle(type), FluidCanister.GetDefaultLiters(type), FluidCanister.GetDefaultColor(type));
Rigidbody rb = go.GetComponent();
if (rb == null) rb = go.AddComponent();
rb.mass = 4f;
rb.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative;
return can;
}
private void BuyItem(ShopItem item)
{
GameEconomyManager eco = GameEconomyManager.Instance;
if (eco != null && !eco.TrySpend(item.price, item.title)) return;
item.spawn?.Invoke(NextDeliveryPos());
statusLine = $"Куплено: {item.title}. Заберите заказ на столе выдачи.";
GameHUD.Notify($"Куплено: {item.title} — {GameUI.Money(item.price)}", GameUI.Green);
}
// ===================== СКЛАД =====================
private List CollectWarehouse()
{
List list = new List();
GameEconomyManager eco = GameEconomyManager.Instance;
Vector3 center = customDelivery != null ? customDelivery.position : (eco != null && eco.garageCenter != null ? eco.garageCenter.position : Vector3.zero);
float radius = customDelivery != null ? 15f : (eco != null ? eco.garageRadius : 30f);
foreach (CarPart p in FindObjectsByType(FindObjectsSortMode.None))
{
if (p.State != PartState.Dropped || !p.gameObject.activeInHierarchy) continue;
if (Vector3.Distance(p.transform.position, center) > radius) continue;
list.Add(p);
}
foreach (FluidCanister c in FindObjectsByType(FindObjectsSortMode.None))
{
if (c.State != FluidCanister.CanisterState.OnGround) continue;
if (Vector3.Distance(c.transform.position, center) > radius) continue;
list.Add(c);
}
return list;
}
private static float KufarPrice(CarPart p)
{
float basePrice = p.Data != null && p.Data.basePrice > 0f ? p.Data.basePrice : 40f;
EnginePart ep = p.GetComponent();
if (ep != null) basePrice = ep.BasePrice;
if (p.IsWheel) basePrice = 85f;
return Mathf.Max(3f, Mathf.Round(basePrice * (p.ConditionPercent / 100f) * 0.5f));
}
// ===================== ОТРИСОВКА =====================
private void OnGUI()
{
if (!isOpen) return;
GameUI.Begin(-10);
float w = GameUI.VirtualWidth;
float h = GameUI.VirtualHeight;
GameUI.DrawRect(new Rect(0, 0, w, h), GameUI.Bg.WithAlpha(0.55f));
Rect r = new Rect(w * 0.5f - 640, h * 0.5f - 440, 1280, 880);
GUI.Box(r, GUIContent.none, GameUI.PanelSolid);
GUI.Label(new Rect(r.x + 30, r.y + 16, 700, 44), "НОУТБУК ГАРАЖА", GameUI.Header);
GameEconomyManager eco = GameEconomyManager.Instance;
if (eco != null)
GUI.Label(new Rect(r.xMax - 560, r.y + 22, 530, 34), eco.Unlimited ? "Свободный режим: деньги не ограничены" : $"На счету: {eco.FormatMoney(eco.Money)}", GameUI.Label);
if (GameUI.Btn(new Rect(r.x + 30, r.y + 70, 400, 50), "Магазин запчастей и жидкостей", tab == Tab.Shop ? GameUI.ButtonTabActive : GameUI.ButtonTab)) { tab = Tab.Shop; scroll = Vector2.zero; }
if (GameUI.Btn(new Rect(r.x + 440, r.y + 70, 400, 50), "Склад запчастей / Продажа на Куфар", tab == Tab.Warehouse ? GameUI.ButtonTabActive : GameUI.ButtonTab)) { tab = Tab.Warehouse; scroll = Vector2.zero; }
Rect view = new Rect(r.x + 30, r.y + 136, r.width - 60, r.height - 240);
if (tab == Tab.Shop) DrawShop(view);
else DrawWarehouse(view);
GUI.Label(new Rect(r.x + 30, r.yMax - 84, r.width - 300, 60), statusLine, GameUI.Small);
if (GameUI.Btn(new Rect(r.xMax - 240, r.yMax - 80, 210, 54), "ЗАКРЫТЬ [K]")) Close();
}
private void DrawShop(Rect view)
{
BuildShop();
float rowH = 50f;
int categories = 0;
string last = null;
foreach (ShopItem i in items) if (i.category != last) { categories++; last = i.category; }
float contentH = items.Count * rowH + categories * 42f + 10f;
scroll = GUI.BeginScrollView(view, scroll, new Rect(0, 0, view.width - 24, contentH));
float y = 0f;
last = null;
foreach (ShopItem item in items)
{
if (item.category != last)
{
last = item.category;
GUI.Label(new Rect(0, y + 6, view.width, 32), $"{item.category}", GameUI.Label);
y += 42f;
}
GameUI.DrawRect(new Rect(0, y, view.width - 30, rowH - 6), GameUI.PanelLight.WithAlpha(0.5f));
GUI.Label(new Rect(14, y + 10, view.width - 420, 32), item.title, GameUI.Label);
GUI.Label(new Rect(view.width - 400, y + 10, 160, 32), GameUI.Money(item.price).Split(' ')[0], GameUI.Label);
if (GameUI.Btn(new Rect(view.width - 220, y + 4, 180, rowH - 14), "Купить", GameUI.ButtonAccent))
BuyItem(item);
y += rowH;
}
GUI.EndScrollView();
}
private void DrawWarehouse(Rect view)
{
List stock = CollectWarehouse();
float rowH = 52f;
GUI.Label(new Rect(view.x + 14, view.y - 4, 500, 30), "Наименование детали", GameUI.Small);
GUI.Label(new Rect(view.x + view.width - 760, view.y - 4, 180, 30), "Состояние (%)", GameUI.Small);
Rect inner = new Rect(view.x, view.y + 30, view.width, view.height - 30);
scroll = GUI.BeginScrollView(inner, scroll, new Rect(0, 0, inner.width - 24, Mathf.Max(inner.height, stock.Count * rowH + 10)));
float y = 0f;
if (stock.Count == 0)
GUI.Label(new Rect(10, 10, inner.width - 40, 60), "Склад пуст. Снятые детали, колеса и канистры, лежащие в гараже, появятся здесь.", GameUI.Small);
foreach (Component c in stock)
{
if (c == null) continue;
GameUI.DrawRect(new Rect(0, y, inner.width - 30, rowH - 6), GameUI.PanelLight.WithAlpha(0.5f));
if (c is CarPart part)
{
EnginePart ep = part.GetComponent();
GUI.Label(new Rect(14, y + 11, inner.width - 800, 32), part.DisplayName, GameUI.Label);
string cond = ep != null ? ep.ShortStatus : $"{Mathf.RoundToInt(part.ConditionPercent)}%";
GUI.Label(new Rect(inner.width - 760, y + 11, 220, 32), cond, GameUI.Label);
if (ep != null && ep.partType == EnginePartType.Battery && ep.charge < 99f)
{
if (GameUI.Btn(new Rect(inner.width - 520, y + 4, 220, rowH - 14), $"Зарядить (${chargePrice:F0})"))
{
if (GameEconomyManager.Instance == null || GameEconomyManager.Instance.TrySpend(chargePrice, "Зарядка АКБ"))
{
ep.charge = 100f;
statusLine = "Аккумулятор заряжен зарядным устройством до 100%";
}
}
}
else if (ep != null && ep.partType == EnginePartType.AirFilter && ep.condition < 70f)
{
if (GameUI.Btn(new Rect(inner.width - 520, y + 4, 220, rowH - 14), "Очистить (продуть)"))
{
ep.condition = 70f;
statusLine = "Воздушный фильтр продут компрессором: 70%";
}
}
float price = KufarPrice(part);
if (GameUI.Btn(new Rect(inner.width - 280, y + 4, 240, rowH - 14), $"Продать на Куфар ${price:F0}", GameUI.ButtonAccent))
{
GameEconomyManager.Instance?.Earn(price, $"Куфар: {part.DisplayName}");
statusLine = $"Продано на Куфар: {part.DisplayName} за ${price:F0}";
part.HideAsSold();
}
}
else if (c is FluidCanister can)
{
GUI.Label(new Rect(14, y + 11, inner.width - 800, 32), can.FluidName, GameUI.Label);
GUI.Label(new Rect(inner.width - 760, y + 11, 220, 32), $"{can.CurrentLiters:F1} л ({Mathf.RoundToInt(can.Fill01 * 100f)}%)", GameUI.Label);
float price = Mathf.Max(1f, Mathf.Round(CanisterPrice(can.Type) * can.Fill01 * 0.5f));
if (GameUI.Btn(new Rect(inner.width - 280, y + 4, 240, rowH - 14), $"Продать на Куфар ${price:F0}", GameUI.ButtonAccent))
{
GameEconomyManager.Instance?.Earn(price, $"Куфар: {can.FluidName}");
Destroy(can.gameObject);
}
}
y += rowH;
}
GUI.EndScrollView();
}
}