using Microsoft.Extensions.Logging;
using RenovationWorkBusinessLogic.BusinessLogic;
using RenovationWorkContracts.BindingModels;
using RenovationWorkContracts.BusinessLogicsContracts;
using RenovationWorkDataModels.Enums;
using RenovationWorkView;
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 PrecastConcretePlantView
{
    public partial class FormMain : Form
    {

        private readonly ILogger _logger;

        private readonly IOrderLogic _orderLogic;

        private readonly IReportLogic _reportLogic;

        private readonly IWorkProcess _workProcess;

        public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess)
        {
            InitializeComponent();
            _logger = logger;
            _orderLogic = orderLogic;
            _reportLogic = reportLogic;
            _workProcess = workProcess;
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            LoadData();
        }

        private void LoadData()
        {
            _logger.LogInformation("Загрузка заказов");
            try
            {
                var list = _orderLogic.ReadList(null);
                if (list != null)
                {
                    DataGridView.DataSource = list;
                    DataGridView.Columns["RepairId"].Visible = false;
                    DataGridView.Columns["ClientId"].Visible = false;
                    DataGridView.Columns["ImplementerId"].Visible = false;
                    DataGridView.Columns["RepairName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                }
                _logger.LogInformation("Загрузка заказов");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Ошибка загрузки заказов");
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var service = Program.ServiceProvider?.GetService(typeof(FormComponents));

            if (service is FormComponents form)
            {
                form.ShowDialog();
            }
        }

        private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var service = Program.ServiceProvider?.GetService(typeof(FormRepairs));

            if (service is FormRepairs form)
            {
                form.ShowDialog();
            }
        }

        private void CreateOrderButton_Click(object sender, EventArgs e)
        {
            var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));

            if (service is FormCreateOrder form)
            {
                form.ShowDialog();
                LoadData();
            }
        }
        private void ClientsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var service = Program.ServiceProvider?.GetService(typeof(FormClients));
            if (service is FormClients form)
            {
                form.ShowDialog();
            }
        }
        private void ImplementersToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
            if (service is FormImplementers form)
            {
                form.ShowDialog();
            }
        }
        
        private void TakeOrderInWorkButton_Click(object sender, EventArgs e)
        {
            if (DataGridView.SelectedRows.Count == 1)
            {
                int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
                _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id);

                try
                {
                    var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel
                    { 
                        Id = id,
                        RepairId = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["RepairId"].Value),
                        RepairName = DataGridView.SelectedRows[0].Cells["RepairName"].Value.ToString(),
                        Status = Enum.Parse<OrderStatus>(DataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
                        Count = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Count"].Value),
                        Sum = double.Parse(DataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
                        DateCreate = DateTime.Parse(DataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
                    });

                    if (!operationResult)
                    {
                        throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
                    }

                    LoadData();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Ошибка передачи заказа в работу");
                    MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void IssuedOrderButton_Click(object sender, EventArgs e)
        {
            if (DataGridView.SelectedRows.Count == 1)
            {
                int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
                _logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id);

                try
                {
                    var operationResult = _orderLogic.FinishOrder(new OrderBindingModel
                    { 
                        Id = id,
                        RepairId = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["RepairId"].Value),
                        RepairName = DataGridView.SelectedRows[0].Cells["RepairName"].Value.ToString(),
                        Status = Enum.Parse<OrderStatus>(DataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
                        Count = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Count"].Value),
                        Sum = double.Parse(DataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
                        DateCreate = DateTime.Parse(DataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
                    });

                    if (!operationResult)
                    {
                        throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
                    }

                    LoadData();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Ошибка отметки о готовности заказа");
                    MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void OrderReadyButton_Click(object sender, EventArgs e)
        {
            if (DataGridView.SelectedRows.Count == 1)
            {
                int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
                _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);

                try
                {
                    var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel
                    { 
                        Id = id,
                        RepairId = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["RepairId"].Value),
                        RepairName = DataGridView.SelectedRows[0].Cells["RepairName"].Value.ToString(),
                        Status = Enum.Parse<OrderStatus>(DataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
                        Count = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Count"].Value),
                        Sum = double.Parse(DataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
                        DateCreate = DateTime.Parse(DataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
                    });

                    if (!operationResult)
                    {
                        throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
                    }

                    _logger.LogInformation("Заказ №{id} выдан", id);
                    LoadData();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Ошибка отметки о выдачи заказа");
                    MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                _reportLogic.SaveRepairsToWordFile(new ReportBindingModel { FileName = dialog.FileName });
                MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void ComponentProductsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var service = Program.ServiceProvider?.GetService(typeof(FormReportRepairComponents));
            if (service is FormReportRepairComponents form)
            {
                form.ShowDialog();
            }
        }

        private void OrdersToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders));
            if (service is FormReportOrders form)
            {
                form.ShowDialog();
            }
        }
        private void UpdateListButton_Click(object sender, EventArgs e)
        {
            LoadData();
        }
        private void DataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void запускРаботыToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic);
            MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void письмаToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var service = Program.ServiceProvider?.GetService(typeof(FormMail));
            if (service is FormMail form)
            {
                form.ShowDialog();
            }
        }
    }
}
