2024-04-05 02:48:52 +04:00
using Microsoft.Extensions.Logging ;
using RouteGuideBusinessLogics.BusinessLogics ;
using RouteGuideContracts.BindingModels ;
using RouteGuideContracts.BusinessLogicsContracts ;
using RouteGuideContracts.SearchModels ;
using RouteGuideDataModels.Models ;
using System ;
using System.Collections.Generic ;
using System.ComponentModel ;
using System.Data ;
using System.Drawing ;
using System.Linq ;
using System.Text ;
using System.Threading.Tasks ;
using System.Windows.Forms ;
namespace RouteGuideView
{
/// <summary>
/// Форма для создания/редактирования маршрутов
/// </summary>
public partial class FormRoute : Form
{
/// <summary>
/// Логгер
/// </summary>
private readonly ILogger _logger ;
/// <summary>
2024-04-08 21:05:52 +04:00
/// Бизнес-логика маршрутов
2024-04-05 02:48:52 +04:00
/// </summary>
private readonly IRouteLogic _routeLogic ;
2024-04-08 21:05:52 +04:00
/// <summary>
/// Бизнес-логика транспорта
/// </summary>
private readonly ITransportLogic _transportLogic ;
2024-04-05 02:48:52 +04:00
/// <summary>
/// Идентификатор
/// </summary>
private int? _id ;
/// <summary>
/// Идентификатор
/// </summary>
public int Id { set { _id = value ; } }
/// <summary>
/// Список остановок в маршруте
/// </summary>
private Dictionary < int , ( IStopModel , int ) > _routeStops ;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="logger"></param>
/// <param name="routeLogic"></param>
2024-04-08 21:05:52 +04:00
public FormRoute ( ILogger < FormRoute > logger , IRouteLogic routeLogic , ITransportLogic transportLogic )
2024-04-05 02:48:52 +04:00
{
InitializeComponent ( ) ;
_logger = logger ;
_routeLogic = routeLogic ;
2024-04-08 21:05:52 +04:00
_transportLogic = transportLogic ;
2024-04-05 02:48:52 +04:00
_routeStops = new Dictionary < int , ( IStopModel , int ) > ( ) ;
}
/// <summary>
/// Загрузка данных
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FormRoute_Load ( object sender , EventArgs e )
{
2024-04-08 21:05:52 +04:00
try
{
// Загрузка маршрутов для ComboBoxTransport
_logger . LogInformation ( "Загрузка списка транспорта" ) ;
var list = _transportLogic . ReadList ( null ) ;
if ( list ! = null )
{
comboBoxTransport . DisplayMember = "License" ;
comboBoxTransport . ValueMember = "Id" ;
comboBoxTransport . DataSource = list ;
comboBoxTransport . SelectedItem = null ;
}
}
catch ( Exception ex )
{
_logger . LogError ( ex , "Ошибка загрузки списка транспорта" ) ;
MessageBox . Show ( ex . Message , "Ошибка" , MessageBoxButtons . OK , MessageBoxIcon . Error ) ;
}
2024-04-05 02:48:52 +04:00
if ( ! _id . HasValue )
{
return ;
}
try
{
_logger . LogInformation ( "Получение сущности 'Маршрут'" ) ;
var view = _routeLogic . ReadElement ( new RouteSearchModel
{
Id = _id . Value
} ) ;
if ( view ! = null )
{
textBoxName . Text = view . Name ;
2024-04-08 21:05:52 +04:00
comboBoxTransport . SelectedValue = view . TransportId ;
2024-04-05 02:48:52 +04:00
_routeStops = view . RouteStops ? ? new Dictionary < int , ( IStopModel , int ) > ( ) ;
LoadData ( ) ;
}
}
catch ( Exception ex )
{
_logger . LogError ( ex , "Ошибка получения сущности 'Маршрут'" ) ;
MessageBox . Show ( ex . Message , "Ошибка" , MessageBoxButtons . OK , MessageBoxIcon . Error ) ;
}
}
/// <summary>
/// Кнопка "Добавить"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreate_Click ( object sender , EventArgs e )
{
var service = Program . ServiceProvider ? . GetService ( typeof ( FormRouteStop ) ) ;
if ( service is FormRouteStop form )
{
if ( form . ShowDialog ( ) = = DialogResult . OK )
{
if ( form . StopModel = = null )
{
return ;
}
_logger . LogInformation ( "Добавление остановки.{Id}: {StopName} в маршрут на позицию {Number}" , form . Id , form . StopModel . Name , form . Number ) ;
if ( _routeStops . ContainsKey ( form . Id ) )
{
_routeStops [ form . Id ] = ( form . StopModel , form . Number ) ;
}
else
{
_routeStops . Add ( form . Id , ( form . StopModel , form . Number ) ) ;
}
LoadData ( ) ;
}
}
}
/// <summary>
/// Кнопка "Изменить"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonUpdate_Click ( object sender , EventArgs e )
{
if ( dataGridView . SelectedRows . Count = = 1 )
{
var service = Program . ServiceProvider ? . GetService ( typeof ( FormRouteStop ) ) ;
if ( service is FormRouteStop form )
{
int id = Convert . ToInt32 ( dataGridView . SelectedRows [ 0 ] . Cells [ 0 ] . Value ) ;
form . Id = id ;
form . Number = _routeStops [ id ] . Item2 ;
if ( form . ShowDialog ( ) = = DialogResult . OK )
{
if ( form . StopModel = = null )
{
return ;
}
_logger . LogInformation ( "Изменение остановки.{Id}: {StopName} в маршруте на позиции {Number}" , form . Id , form . StopModel . Name , form . Number ) ;
_routeStops [ form . Id ] = ( form . StopModel , form . Number ) ;
LoadData ( ) ;
}
}
}
}
/// <summary>
/// Кнопка "Удалить"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonDelete_Click ( object sender , EventArgs e )
{
if ( dataGridView . SelectedRows . Count = = 1 )
{
if ( MessageBox . Show ( "Удалить запись?" , "Вопрос" , MessageBoxButtons . YesNo , MessageBoxIcon . Question ) = = DialogResult . Yes )
{
try
{
_logger . LogInformation ( "Удаление остановки.{Id}: {StopName} с позиции в маршруте {Number}" , dataGridView . SelectedRows [ 0 ] . Cells [ 0 ] . Value , dataGridView . SelectedRows [ 0 ] . Cells [ 1 ] . Value , dataGridView . SelectedRows [ 0 ] . Cells [ 2 ] . Value ) ;
_routeStops . Remove ( Convert . ToInt32 ( dataGridView . SelectedRows [ 0 ] . Cells [ 0 ] . Value ) ) ;
}
catch ( Exception ex )
{
_logger . LogError ( ex , "Ошибка удаления остановки.{Id}: {StopName} с позиции в маршруте {Number}" , dataGridView . SelectedRows [ 0 ] . Cells [ 0 ] . Value , dataGridView . SelectedRows [ 0 ] . Cells [ 1 ] . Value , dataGridView . SelectedRows [ 0 ] . Cells [ 2 ] . Value ) ;
MessageBox . Show ( ex . Message , "Ошибка" , MessageBoxButtons . OK , MessageBoxIcon . Error ) ;
}
LoadData ( ) ;
}
}
}
/// <summary>
/// Кнопка "Обновить"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRefresh_Click ( object sender , EventArgs e )
{
LoadData ( ) ;
}
/// <summary>
/// Кнопка "Сохранить"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSave_Click ( object sender , EventArgs e )
{
if ( string . IsNullOrEmpty ( textBoxName . Text ) )
{
MessageBox . Show ( "Заполните название маршрута" , "Ошибка" , MessageBoxButtons . OK , MessageBoxIcon . Error ) ;
return ;
}
2024-04-08 21:05:52 +04:00
if ( comboBoxTransport . SelectedValue = = null )
{
MessageBox . Show ( "Выберите транспорт" , "Ошибка" , MessageBoxButtons . OK , MessageBoxIcon . Error ) ;
return ;
}
2024-04-05 02:48:52 +04:00
_logger . LogInformation ( "Сохранение сущности 'Маршрут'" ) ;
try
{
var model = new RouteBindingModel
{
Id = _id ? ? 0 ,
Name = textBoxName . Text ,
2024-04-08 21:05:52 +04:00
TransportId = Convert . ToInt32 ( comboBoxTransport . SelectedValue ) ,
2024-04-05 02:48:52 +04:00
RouteStops = _routeStops
} ;
var operationResult = _id . HasValue ? _routeLogic . Update ( model ) : _routeLogic . Create ( model ) ;
if ( ! operationResult )
{
throw new Exception ( "Ошибка при сохранении сущности 'Маршрут'. Дополнительная информация в логах." ) ;
}
MessageBox . Show ( "Сохранение сущности 'Маршрут' прошло успешно" , "Сообщение" , MessageBoxButtons . OK , MessageBoxIcon . Information ) ;
DialogResult = DialogResult . OK ;
Close ( ) ;
}
catch ( Exception ex )
{
_logger . LogError ( ex , "Ошибка сохранения сущности 'Маршрут'" ) ;
MessageBox . Show ( ex . Message , "Ошибка" , MessageBoxButtons . OK , MessageBoxIcon . Error ) ;
}
}
/// <summary>
/// Кнопка "Отмена"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCancel_Click ( object sender , EventArgs e )
{
DialogResult = DialogResult . Cancel ;
Close ( ) ;
}
/// <summary>
/// Загрузка данных
/// </summary>
private void LoadData ( )
{
_logger . LogInformation ( "Загрузка списка остановок в маршруте" ) ;
try
{
if ( _routeStops ! = null )
{
dataGridView . Rows . Clear ( ) ;
foreach ( var rs in _routeStops )
{
dataGridView . Rows . Add ( new object [ ]
{
rs . Key ,
rs . Value . Item1 . Name ,
rs . Value . Item2
} ) ;
}
}
}
catch ( Exception ex )
{
_logger . LogError ( ex , "Ошибка загрузки списка остановок в маршруте" ) ;
MessageBox . Show ( ex . Message , "Ошибка" , MessageBoxButtons . OK , MessageBoxIcon . Error ) ;
}
}
}
}