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>
2024-04-23 19:38:25 +04:00
private object? _id ;
2024-04-05 02:48:52 +04:00
/// <summary>
/// Идентификатор
/// </summary>
2024-04-23 19:38:25 +04:00
public object Id { set { _id = value ; } }
2024-04-05 02:48:52 +04:00
/// <summary>
/// Список остановок в маршруте
/// </summary>
2024-04-23 19:38:25 +04:00
private Dictionary < object , ( IStopModel < object > , int ) > _routeStops ;
2024-04-05 02:48:52 +04:00
/// <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-23 19:38:25 +04:00
_routeStops = new Dictionary < object , ( IStopModel < object > , int ) > ( ) ;
2024-04-05 02:48:52 +04:00
}
/// <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-23 19:38:25 +04:00
if ( _id = = null )
2024-04-05 02:48:52 +04:00
{
return ;
}
try
{
_logger . LogInformation ( "Получение сущности 'Маршрут'" ) ;
var view = _routeLogic . ReadElement ( new RouteSearchModel
{
2024-04-23 19:38:25 +04:00
Id = _id
2024-04-05 02:48:52 +04:00
} ) ;
if ( view ! = null )
{
textBoxName . Text = view . Name ;
2024-04-08 21:05:52 +04:00
comboBoxTransport . SelectedValue = view . TransportId ;
2024-04-23 19:38:25 +04:00
_routeStops = view . RouteStops ? ? new Dictionary < object , ( IStopModel < object > , int ) > ( ) ;
2024-04-05 02:48:52 +04:00
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 )
{
2024-04-23 19:38:25 +04:00
object id = dataGridView . SelectedRows [ 0 ] . Cells [ 0 ] . Value ;
2024-04-05 02:48:52 +04:00
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 ) ;
2024-04-23 19:38:25 +04:00
_routeStops . Remove ( dataGridView . SelectedRows [ 0 ] . Cells [ 0 ] . Value ) ;
2024-04-05 02:48:52 +04:00
}
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-23 19:38:25 +04:00
TransportId = comboBoxTransport . SelectedValue ,
2024-04-05 02:48:52 +04:00
RouteStops = _routeStops
} ;
2024-04-23 19:38:25 +04:00
var operationResult = _id ! = null ? _routeLogic . Update ( model ) : _routeLogic . Create ( model ) ;
2024-04-05 02:48:52 +04:00
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 ) ;
}
}
}
}