DepartmentProject/DepartmentPortal/Common/DesktopTools/Controls/AbstractGenerticControlEntityList.cs

334 lines
9.2 KiB
C#
Raw Normal View History

using DesktopTools.Models;
using ModuleTools.Attributes;
using ModuleTools.BindingModels;
using ModuleTools.BusinessLogics;
using ModuleTools.Extensions;
using ModuleTools.ViewModels;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Windows.Forms;
namespace DesktopTools.Controls
{
public partial class AbstractGenerticControlEntityList<G, S, L, E, BL> : ControlViewEntityList
where G : GetBindingModel
where S : SetBindingModel
where L: ListViewModel<E>
where E : ElementViewModel
where BL : BusinessLogicCore<G, S, L, E>
{
/// <summary>
/// Объект бизнес-логики для получения данных
/// </summary>
protected BL _businessLogic;
/// <summary>
/// Констркутор
/// </summary>
public AbstractGenerticControlEntityList()
{
InitializeComponent();
InitEvents();
_businessLogic = DependencyManager.Instance.Resolve<BL>();
}
public override void Open()
{
base.Open();
if (dataGridViewList.Columns.Count == 0)
{
Configurate(GetConfig());
}
LoadList();
}
public override void Close()
{
base.Close();
}
/// <summary>
/// Конфигуратор контрола
/// </summary>
/// <param name="model">Настройки</param>
private void Configurate(ControlViewEntityListConfiguration config)
{
if(config == null)
{
return;
}
// формирование таблицы на основе модели
dataGridViewList.Columns.Clear();
var properties = typeof(E).GetProperties();
foreach (var property in properties)
{
var attr = property.GetCustomAttribute<ViewModelOnListPropertyAttribute>();
if (attr != null)
{
dataGridViewList.Columns.Add(new DataGridViewTextBoxColumn
{
HeaderText = attr.DisplayName,
Name = string.Format("Column{0}", property.Name),
ReadOnly = true,
Visible = !attr.IsHide,
Width = attr.ColumnWidth ?? 0,
AutoSizeMode = attr.ColumnWidth.HasValue ? DataGridViewAutoSizeColumnMode.None : DataGridViewAutoSizeColumnMode.Fill
});
}
}
// настройка отображения основных кнопок
if (config.ShowToolStripButton != null)
{
foreach (ToolStripItem button in toolStripMenu.Items)
{
if (config.ShowToolStripButton.Contains(button.Name))
{
button.Visible = false;
switch (button.Name)
{
case "toolStripButtonUpd":
toolStripSeparator1.Visible = false;
break;
case "toolStripButtonDel":
toolStripSeparator2.Visible = false;
break;
case "toolStripButtonRef":
toolStripSeparator3.Visible = false;
break;
case "toolStripButtonSearch":
toolStripSeparator4.Visible = false;
break;
}
}
}
}
// Загрузка подпунктов в контекстное меню и в пункт меню "Действие"
if (config.ControlOnMoveElem != null)
{
foreach (var elem in config.ControlOnMoveElem)
{
ToolStripMenuItem item = new() { Text = elem.Value.Title, Name = elem.Key };
item.Click += elem.Value.Event;
toolStripSplitButtonActions.DropDownItems.Add(item);
contextMenuStripDataGrid.Items.Add(item);
}
}
// либо скрытие пункта, если не предусмотренно подпунктов
else
{
toolStripSplitButtonActions.Visible = false;
toolStripSeparator3.Visible = false;
}
// Пагинация
if (config.PaginationOn)
{
if (config.CountElementsOnPage.HasValue)
{
toolStripTextBoxPage.Tag = config.CountElementsOnPage.Value;
}
// пагинация по названиям
if (config.PageNamesForPagination != null)
{
toolStripButtonPrev.Visible = toolStripLabelPage.Visible = toolStripTextBoxPage.Visible = toolStripLabelCountPages.Visible =
toolStripButtonNext.Visible = false;
toolStripComboBoxPageNames.Items.AddRange(config.PageNamesForPagination.ToArray());
toolStripComboBoxPageNames.SelectedIndex = 0;
}
// пагинация по страницам
else
{
toolStripLabelPageName.Visible = toolStripComboBoxPageNames.Visible = false;
}
}
// нет пагинации
else
{
toolStripFooter.Visible = false;
}
}
/// <summary>
/// Инициализация событий к контролам
/// </summary>
private void InitEvents()
{
toolStripButtonAdd.Click += (object sender, EventArgs e) => { CallAddElementEvent(); };
toolStripButtonUpd.Click += (object sender, EventArgs e) => { CallUpdElementEvent(); };
toolStripButtonDel.Click += (object sender, EventArgs e) => { CallDelElementEvent(); };
toolStripButtonSearch.Click += (object sender, EventArgs e) => { panelSearch.Visible = !panelSearch.Visible; };
toolStripButtonRef.Click += (object sender, EventArgs e) => { LoadList(); };
toolStripButtonClose.Click += (object sender, EventArgs e) => { Close(); };
buttonSearch.Click += (object sender, EventArgs e) => { LoadList(); };
buttonCancelSearch.Click += (object sender, EventArgs e) => { panelSearch.Visible = false; };
dataGridViewList.KeyDown += (object sender, KeyEventArgs e) =>
{
switch (e.KeyCode)
{
case Keys.Insert:
CallAddElementEvent();
break;
case Keys.Enter:
CallUpdElementEvent();
break;
case Keys.Delete:
CallDelElementEvent();
break;
}
};
dataGridViewList.CellDoubleClick += (object sender, DataGridViewCellEventArgs e) =>
{
CallUpdElementEvent();
};
toolStripButtonPrev.Click += (object sender, EventArgs e) =>
{
if (int.TryParse(toolStripTextBoxPage.Text, out int page))
{
toolStripTextBoxPage.Text = (page - 1).ToString();
LoadList();
}
};
toolStripButtonNext.Click += (object sender, EventArgs e) =>
{
if (int.TryParse(toolStripTextBoxPage.Text, out int page))
{
toolStripTextBoxPage.Text = (page + 1).ToString();
LoadList();
}
};
toolStripTextBoxPage.KeyDown += (object sender, KeyEventArgs e) =>
{
if (e.KeyData == Keys.Enter)
{
LoadList();
}
};
toolStripComboBoxPageNames.SelectedIndexChanged += (object sender, EventArgs e) => { LoadList(); };
}
/// <summary>
/// Вызов события загрузки данных на datagrid
/// </summary>
private void LoadList()
{
var cursor = Cursor.Current;
L data = null;
try
{
Cursor.Current = Cursors.WaitCursor;
// если включена пагинация
if (toolStripFooter.Visible)
{
// постраничная
if (toolStripTextBoxPage.Visible)
{
if (int.TryParse(toolStripTextBoxPage.Text, out int page) && int.TryParse(toolStripTextBoxPage.Tag.ToString(), out int count))
{
data = GetDataWithPageNumber(page, count);
}
}
// поименная
else if (toolStripComboBoxPageNames.Visible)
{
var key = toolStripComboBoxPageNames.Text;
if (key.IsNotEmpty())
{
data = GetDataWithPageName(key);
}
}
}
else
{
data = GetData();
}
if (data == null)
{
// TODO вывод сообщения об ощибок
return;
}
toolStripLabelCountPages.Text = $"из {data.MaxCount}";
FillDataOnGrid(data.List);
}
finally
{
Cursor.Current = cursor;
}
}
/// <summary>
/// Заполнение таблицы
/// </summary>
/// <param name="data"></param>
private void FillDataOnGrid(List<E> data)
{
if (data == null)
{
return;
}
dataGridViewList.Rows.Clear();
foreach (var elem in data)
{
var mas = new List<object>();
foreach (DataGridViewColumn column in dataGridViewList.Columns)
{
mas.Add(elem.GetType().GetProperty(column.Name["Column".Length..])?.GetValue(elem));
}
dataGridViewList.Rows.Add(mas.ToArray());
}
}
/// <summary>
/// Вызов события при добавлении элемента
/// </summary>
private void CallAddElementEvent() => AddElement();
/// <summary>
/// Вызов события при изменении элемента
/// </summary>
private void CallUpdElementEvent()
{
foreach (DataGridViewRow selected in dataGridViewList.SelectedRows)
{
var id = new Guid(selected.Cells[0].Value.ToString());
UpdElement(id);
}
}
/// <summary>
/// Вызов события при удалении элемента
/// </summary>
private void CallDelElementEvent()
{
if (MessageBox.Show("Удалить выбранные записи?", "Подтверждение", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
foreach (DataGridViewRow selected in dataGridViewList.SelectedRows)
{
var id = new Guid(selected.Cells[0].Value.ToString());
DelElement(id);
}
}
}
protected virtual void AddElement() { }
protected virtual void UpdElement(Guid id) { }
protected virtual void DelElement(Guid id) { }
protected virtual ControlViewEntityListConfiguration GetConfig() { return null; }
protected virtual L GetData() { return null; }
protected virtual L GetDataWithPageName(string key) { return null; }
protected virtual L GetDataWithPageNumber(int page, int count) { return null; }
}
}