uchet_techniki/Form1.cs

328 lines
12 KiB
C#
Raw Permalink Normal View History

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using MetroFramework;
using MetroFramework.Forms;
namespace Учетещей
{
public partial class Form1 : MetroForm
{
private User _currentUser;
private Device _selectedDevice;
public Form1()
{
InitializeComponent();
this.Theme = MetroFramework.MetroThemeStyle.Light;
this.Style = MetroFramework.MetroColorStyle.Blue;
this.BorderStyle = MetroFormBorderStyle.FixedSingle;
this.ShadowType = MetroFormShadowType.AeroShadow;
this.Text = "Учет оборудования";
}
private void Form1_Load(object sender, EventArgs e)
{
// Показываем форму логина
using (var loginForm = new LoginForm())
{
if (loginForm.ShowDialog() == DialogResult.OK)
{
_currentUser = loginForm.CurrentUser;
ConfigureFormForUser();
RefreshDevicesGrid();
}
else
{
Close(); // Выход, если пользователь отменил вход
}
}
// Настройка ComboBox для типов устройств и состояний
cmbFilterType.Items.Add("Все типы");
foreach (DeviceType type in Enum.GetValues(typeof(DeviceType)))
{
cmbFilterType.Items.Add(type.ToString());
cmbDeviceType.Items.Add(type.ToString());
}
cmbFilterType.SelectedIndex = 0;
cmbFilterState.Items.Add("Все состояния");
foreach (DeviceState state in Enum.GetValues(typeof(DeviceState)))
{
cmbFilterState.Items.Add(state.ToString());
cmbDeviceState.Items.Add(state.ToString());
}
cmbFilterState.SelectedIndex = 0;
// Текущая дата для нового устройства
dtpRegistrationDate.Value = DateTime.Today;
// Обработчик выбора строки в DataGridView
dgvDevices.SelectionChanged += DgvDevices_SelectionChanged;
}
private void ConfigureFormForUser()
{
Text = $"Учёт техники в организации - {_currentUser.Username} ({_currentUser.Role})";
bool isAdmin = _currentUser.Role == UserRole.Admin;
btnAdd.Enabled = isAdmin;
btnEdit.Enabled = isAdmin;
btnDelete.Enabled = isAdmin;
btnSave.Enabled = isAdmin;
panelDeviceDetails.Enabled = isAdmin;
}
private void RefreshDevicesGrid(List<Device> devices = null)
{
devices = devices ?? DbManager.GetAllDevices();
dgvDevices.DataSource = null;
dgvDevices.DataSource = devices;
// Настройка столбцов
if (dgvDevices.Columns.Count > 0)
{
dgvDevices.Columns["Id"].HeaderText = "ID";
dgvDevices.Columns["Id"].Width = 40;
dgvDevices.Columns["Name"].HeaderText = "Наименование";
dgvDevices.Columns["Name"].Width = 150;
dgvDevices.Columns["InventoryNumber"].HeaderText = "Инв. номер";
dgvDevices.Columns["InventoryNumber"].Width = 80;
dgvDevices.Columns["TypeString"].HeaderText = "Тип";
dgvDevices.Columns["Type"].Visible = false;
dgvDevices.Columns["Location"].HeaderText = "Местоположение";
dgvDevices.Columns["ResponsiblePerson"].HeaderText = "Отв. лицо";
dgvDevices.Columns["StateString"].HeaderText = "Состояние";
dgvDevices.Columns["State"].Visible = false;
dgvDevices.Columns["RegistrationDate"].HeaderText = "Дата регистрации";
dgvDevices.Columns["RegistrationDate"].DefaultCellStyle.Format = "dd.MM.yyyy";
}
// Обновляем статистику
UpdateStatistics();
}
private void UpdateStatistics()
{
Dictionary<DeviceType, int> stats = DbManager.GetDeviceTypeStats();
lvStatistics.Items.Clear();
foreach (var item in stats)
{
ListViewItem lvi = new ListViewItem(item.Key.ToString());
lvi.SubItems.Add(item.Value.ToString());
lvStatistics.Items.Add(lvi);
}
// Общее количество устройств
int totalDevices = stats.Values.Sum();
ListViewItem totalItem = new ListViewItem("ВСЕГО");
totalItem.SubItems.Add(totalDevices.ToString());
totalItem.Font = new Font(lvStatistics.Font, FontStyle.Bold);
lvStatistics.Items.Add(totalItem);
}
private void ClearDeviceForm()
{
txtDeviceName.Text = "";
txtInventoryNumber.Text = "";
txtLocation.Text = "";
txtResponsiblePerson.Text = "";
cmbDeviceType.SelectedIndex = -1;
cmbDeviceState.SelectedIndex = -1;
dtpRegistrationDate.Value = DateTime.Today;
_selectedDevice = null;
}
private void FillDeviceForm(Device device)
{
if (device == null) return;
txtDeviceName.Text = device.Name;
txtInventoryNumber.Text = device.InventoryNumber;
txtLocation.Text = device.Location;
txtResponsiblePerson.Text = device.ResponsiblePerson;
cmbDeviceType.SelectedItem = device.Type.ToString();
cmbDeviceState.SelectedItem = device.State.ToString();
dtpRegistrationDate.Value = device.RegistrationDate;
_selectedDevice = device;
}
private Device GetDeviceFromForm()
{
if (string.IsNullOrEmpty(txtDeviceName.Text) ||
string.IsNullOrEmpty(txtInventoryNumber.Text) ||
cmbDeviceType.SelectedIndex == -1 ||
cmbDeviceState.SelectedIndex == -1)
{
MetroMessageBox.Show(this,
"Пожалуйста, заполните все обязательные поля",
"Ошибка",
MessageBoxButtons.OK,
MessageBoxIcon.Warning);
return null;
}
Device device = new Device
{
Name = txtDeviceName.Text,
InventoryNumber = txtInventoryNumber.Text,
Type = (DeviceType)Enum.Parse(typeof(DeviceType), cmbDeviceType.SelectedItem.ToString()),
Location = txtLocation.Text,
ResponsiblePerson = txtResponsiblePerson.Text,
State = (DeviceState)Enum.Parse(typeof(DeviceState), cmbDeviceState.SelectedItem.ToString()),
RegistrationDate = dtpRegistrationDate.Value
};
if (_selectedDevice != null)
device.Id = _selectedDevice.Id;
return device;
}
private void DgvDevices_SelectionChanged(object sender, EventArgs e)
{
if (dgvDevices.SelectedRows.Count > 0 && dgvDevices.SelectedRows[0].DataBoundItem is Device selectedDevice)
{
FillDeviceForm(selectedDevice);
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
ClearDeviceForm();
}
private void btnEdit_Click(object sender, EventArgs e)
{
if (dgvDevices.SelectedRows.Count == 0)
{
MetroMessageBox.Show(this,
"Выберите устройство для редактирования",
"Информация",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
return;
}
if (dgvDevices.SelectedRows[0].DataBoundItem is Device selectedDevice)
{
FillDeviceForm(selectedDevice);
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (dgvDevices.SelectedRows.Count == 0)
{
MetroMessageBox.Show(this,
"Выберите устройство для удаления",
"Информация",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
return;
}
if (dgvDevices.SelectedRows[0].DataBoundItem is Device selectedDevice)
{
if (MetroMessageBox.Show(this,
$"Вы действительно хотите удалить устройство \"{selectedDevice.Name}\"?",
"Подтверждение удаления",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
DbManager.DeleteDevice(selectedDevice.Id);
RefreshDevicesGrid();
ClearDeviceForm();
}
}
}
private void btnSave_Click(object sender, EventArgs e)
{
Device device = GetDeviceFromForm();
if (device == null) return;
if (_selectedDevice == null)
{
// Добавление нового устройства
DbManager.AddDevice(device);
}
else
{
// Обновление существующего устройства
DbManager.UpdateDevice(device);
}
RefreshDevicesGrid();
ClearDeviceForm();
}
private void btnFilter_Click(object sender, EventArgs e)
{
DeviceType? filterType = null;
if (cmbFilterType.SelectedIndex > 0)
{
filterType = (DeviceType)Enum.Parse(typeof(DeviceType), cmbFilterType.SelectedItem.ToString());
}
DeviceState? filterState = null;
if (cmbFilterState.SelectedIndex > 0)
{
filterState = (DeviceState)Enum.Parse(typeof(DeviceState), cmbFilterState.SelectedItem.ToString());
}
string location = txtFilterLocation.Text;
string searchText = txtSearch.Text;
var filteredDevices = DbManager.FilterDevices(filterType, filterState, location, searchText);
RefreshDevicesGrid(filteredDevices);
}
private void btnResetFilter_Click(object sender, EventArgs e)
{
cmbFilterType.SelectedIndex = 0;
cmbFilterState.SelectedIndex = 0;
txtFilterLocation.Text = "";
txtSearch.Text = "";
RefreshDevicesGrid();
}
private void btnExport_Click(object sender, EventArgs e)
{
try
{
SaveFileDialog saveDialog = new SaveFileDialog
{
Filter = "CSV файлы (*.csv)|*.csv|Текстовые файлы (*.txt)|*.txt|Все файлы (*.*)|*.*",
Title = "Экспорт данных",
FileName = "Учет_техники_" + DateTime.Now.ToString("dd_MM_yyyy")
};
if (saveDialog.ShowDialog() == DialogResult.OK)
{
DbManager.ExportToCsv(saveDialog.FileName);
MetroMessageBox.Show(this,
"Данные успешно экспортированы",
"Экспорт",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MetroMessageBox.Show(this,
"Ошибка при экспорте данных: " + ex.Message,
"Ошибка",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
}