using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using RobotNet.MapManager.Data; using RobotNet.MapManager.Services; using RobotNet.MapShares; using RobotNet.MapShares.Dtos; using RobotNet.Shares; namespace RobotNet.MapManager.Controllers; [Route("api/[controller]")] [ApiController] [Authorize] public class ZonesController(MapEditorDbContext MapDb, LoggerController Logger) : ControllerBase { [HttpPost] [Route("")] public async Task> Create([FromBody] ZoneCreateModel zone) { try { var map = await MapDb.Maps.FindAsync(zone.MapId); if (map == null) return new(false, $"Không tồn tại map id = {zone.MapId}"); if (MapEditorHelper.CalculateQuadrilateralArea(zone.X1, zone.Y1, zone.X2, zone.Y2, zone.X3, zone.Y3, zone.X4, zone.Y4) < map.ZoneMinSquareDefault) return new(false, "Kích thước Zone quá nhỏ"); var entity = await MapDb.Zones.AddAsync(new() { MapId = zone.MapId, Type = zone.Type, Name = "", X1 = zone.X1, X2 = zone.X2, X3 = zone.X3, X4 = zone.X4, Y1 = zone.Y1, Y2 = zone.Y2, Y3 = zone.Y3, Y4 = zone.Y4, }); await MapDb.SaveChangesAsync(); return new(true) { Data = new ZoneDto() { Id = entity.Entity.Id, MapId = entity.Entity.MapId, Type = entity.Entity.Type, X1 = entity.Entity.X1, X2 = entity.Entity.X2, X3 = entity.Entity.X3, X4 = entity.Entity.X4, Y1 = entity.Entity.Y1, Y2 = entity.Entity.Y2, Y3 = entity.Entity.Y3, Y4 = entity.Entity.Y4 } }; } catch (Exception ex) { Logger.Warning($"Create: Hệ thống có lỗi xảy ra - {ex.Message}"); return new(false, "Hệ thống có lỗi xảy ra"); } } [HttpDelete] [Route("{id}")] public async Task Delete(Guid id) { try { var zoneExisted = await MapDb.Zones.FindAsync(id); if (zoneExisted is not null) { MapDb.Zones.Remove(zoneExisted); await MapDb.SaveChangesAsync(); return new(true); } return new(false, "Hệ thống không tìm thấy khu vực Zone này"); } catch (Exception ex) { Logger.Warning($"Delete {id}: Hệ thống có lỗi xảy ra - {ex.Message}"); return new(false, "Hệ thống có lỗi xảy ra"); } } [HttpPut] [Route("")] public async Task Update([FromBody] ZoneUpdateModel zone) { try { var zoneExisted = await MapDb.Zones.FindAsync(zone.Id); if (zoneExisted is not null) { if (zoneExisted.Name != zone.Name && !string.IsNullOrWhiteSpace(zone.Name) && await MapDb.Zones.AnyAsync(z => z.Name == zone.Name && z.MapId == zoneExisted.MapId)) { return new(false, $"Tên zone {zone.Name} đã tồn tại trong map"); } zoneExisted.Type = zone.Type; zoneExisted.Name = zone.Name; zoneExisted.X1 = zone.X1; zoneExisted.X2 = zone.X2; zoneExisted.X3 = zone.X3; zoneExisted.X4 = zone.X4; zoneExisted.Y1 = zone.Y1; zoneExisted.Y2 = zone.Y2; zoneExisted.Y3 = zone.Y3; zoneExisted.Y4 = zone.Y4; MapDb.Zones.Update(zoneExisted); await MapDb.SaveChangesAsync(); return new(true); } return new(false, "Hệ thống không tìm thấy khu vực Zone này"); } catch (Exception ex) { Logger.Warning($"Update: Hệ thống có lỗi xảy ra - {ex.Message}"); return new(false, $"Update: Hệ thống có lỗi xảy ra - {ex.Message}"); } } }