using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Elfisa.UI.Controls;
using Электронная_Фармация.Classes;
using Электронная_Фармация.HelpForms;

namespace Электронная_Фармация.UserControls
{
    public partial class FOrders : Form
    {
        public FOrders()
        {
            InitializeComponent();
        }

        BindingSource bsOrder = new BindingSource();

        string currentSelectOrderType = "tabPageAllOrders";

        string filter = string.Empty;

        private void FOrders_Load(object sender, EventArgs e)
        {
            UiThemeHelper.ApplyToControlTree(this);
            Tag = "chrome-child";
            panelToolbar.Tag = "toolbar";
            panelOrdersHeader.Padding = new Padding(8, 14, 8, 6);

            dtpDateFrom.Value = DateTime.Now.AddDays(-3);
            dtpDateTo.Value = DateTime.Now;

            LoadOrders(dtpDateFrom.Value.ToString("yyyy-MM-dd"), dtpDateTo.Value.ToString("yyyy-MM-dd"), string.Empty);

            loadSuppliers();
            comboSuppliers.Visible = true;
            InitOrderToolbar();
            loadConsignees();
            ApplyToolbarLayout();
            ModernButtonStyles.ApplyClear(btnClearGoodSearch);
            ModernButtonStyles.ApplyClear(btnClearOrderNumberFilter);
            InitializeOrderContextMenu();
            label3.BringToFront();
            panelToolbar.Resize += (_, __) => ApplyToolbarLayout();
        }

        private void InitializeOrderContextMenu()
        {
            if (_ordersMenu != null)
            {
                return;
            }

            _getInvoiceMenuItem = new ToolStripMenuItem("Получить накладную");
            _getInvoiceMenuItem.Click += (_, __) => RequestInvoiceForSelectedOrder();

            _ordersMenu = new ContextMenuStrip();
            _ordersMenu.Items.Add(_getInvoiceMenuItem);
            _ordersMenu.Opening += OrdersMenu_Opening;

            DGVOrders.ContextMenuStrip = _ordersMenu;
        }

        private void OrdersMenu_Opening(object sender, CancelEventArgs e)
        {
            var pt = DGVOrders.PointToClient(Cursor.Position);
            var hit = DGVOrders.HitTest(pt.X, pt.Y);
            if (hit.RowIndex < 0 || hit.RowIndex >= DGVOrders.Rows.Count)
            {
                e.Cancel = true;
                return;
            }

            DGVOrders.ClearSelection();
            DGVOrders.Rows[hit.RowIndex].Selected = true;
            if (hit.ColumnIndex >= 0)
            {
                DGVOrders.CurrentCell = DGVOrders.Rows[hit.RowIndex].Cells[hit.ColumnIndex];
            }

            var status = DGVOrders.Rows[hit.RowIndex].Cells["Статус"]?.Value?.ToString();
            _getInvoiceMenuItem.Enabled = string.Equals(status, "ОТПРАВЛЕН", StringComparison.OrdinalIgnoreCase);
        }

        private ModernComboBox _comboOrderStatus;
        private ModernComboBox _comboConsignees;
        private ModernButton _btnSendOrder;
        private ContextMenuStrip _ordersMenu;
        private ToolStripMenuItem _getInvoiceMenuItem;

        private void InitOrderToolbar()
        {
            _comboOrderStatus = new ModernComboBox
            {
                Font = new Font("Segoe UI", 11.25f),
                Name = "comboOrderStatus"
            };
            _comboOrderStatus.Items.AddRange(new object[] { "Все статусы", "НОВЫЙ", "ОТПРАВЛЕН" });
            _comboOrderStatus.SelectedIndex = 0;
            _comboOrderStatus.SelectionChangeCommitted += (_, __) => ApplyOrderFilters();
            panelToolbar.Controls.Add(_comboOrderStatus);

            _comboConsignees = new ModernComboBox
            {
                Font = new Font("Segoe UI", 11.25f),
                Name = "comboConsigneesFilter"
            };
            _comboConsignees.SelectionChangeCommitted += (_, __) => ApplyOrderFilters();
            panelToolbar.Controls.Add(_comboConsignees);

            _btnSendOrder = new ModernButton
            {
                Text = "ОТПРАВИТЬ",
                Name = "btnSendOrder"
            };
            _btnSendOrder.Click += async (_, __) => await SendSelectedOrderAsync();
            panelToolbar.Controls.Add(_btnSendOrder);

            UiThemeHelper.ApplyToControlTree(_comboOrderStatus);
            UiThemeHelper.ApplyToControlTree(_comboConsignees);
            UiThemeHelper.ApplyToControlTree(_btnSendOrder);
        }

        private static int FitControlWidth(int preferred, int minimum, int available)
        {
            return Math.Max(minimum, Math.Min(preferred, available));
        }

        private void ApplyToolbarLayout()
        {
            const int pad = 12;
            const int gap = 8;
            const int controlHeight = 32;
            const int filterHeight = 33;
            const int buttonHeight = 34;
            const int rowGap = 10;
            const int dateWidth = 112;
            const int deleteWidth = 138;
            const int sendWidth = 158;
            const int clearSize = 32;
            const int commentMaxWidth = 200;
            const int commentMinWidth = 132;
            const int textMinWidth = 108;
            const int textPreferredWidth = 220;
            const int statusPreferredWidth = 150;
            const int supplierPreferredWidth = 170;
            const int consigneePreferredWidth = 190;

            var panelWidth = Math.Max(panelToolbar.ClientSize.Width, 320);
            int y = 10;

            int x = pad;
            label2.Location = new Point(x, y + 5);
            x = label2.Right + 6;
            dtpDateFrom.SetBounds(x, y, dateWidth, controlHeight);
            x = dtpDateFrom.Right + 6;
            label1.Location = new Point(x, y + 4);
            x = label1.Right + 6;
            dtpDateTo.SetBounds(x, y, dateWidth, controlHeight);
            int datesRight = dtpDateTo.Right;

            int deleteLeft = panelWidth - pad - deleteWidth;
            btnDeleteOrder.SetBounds(deleteLeft, y, deleteWidth, buttonHeight);
            int sendLeft = btnDeleteOrder.Left - gap - sendWidth;
            _btnSendOrder.SetBounds(sendLeft, y, sendWidth, buttonHeight);
            int actionsLeft = _btnSendOrder.Left;

            int middleAvailable = actionsLeft - datesRight - gap;
            int statusMin = 108;
            int supplierMin = 118;
            int consigneeMin = 128;
            int combosMin = statusMin + supplierMin + consigneeMin + gap * 2;
            int combosPreferred = statusPreferredWidth + supplierPreferredWidth + consigneePreferredWidth + gap * 2;
            bool wrapCombos = middleAvailable < combosMin;

            comboSuppliers.Visible = true;
            _comboOrderStatus.Visible = true;
            _comboConsignees.Visible = true;

            if (wrapCombos)
            {
                y += buttonHeight + rowGap;
                int filterY = y + (buttonHeight - filterHeight) / 2;
                int comboRowWidth = panelWidth - pad * 2;
                int statusWidth;
                int supplierWidth;
                int consigneeWidth;

                if (comboRowWidth >= combosPreferred)
                {
                    statusWidth = statusPreferredWidth;
                    supplierWidth = supplierPreferredWidth;
                    consigneeWidth = consigneePreferredWidth;
                }
                else
                {
                    float scale = (comboRowWidth - gap * 2) / (float)(statusPreferredWidth + supplierPreferredWidth + consigneePreferredWidth);
                    statusWidth = Math.Max(statusMin, (int)(statusPreferredWidth * scale));
                    supplierWidth = Math.Max(supplierMin, (int)(supplierPreferredWidth * scale));
                    consigneeWidth = Math.Max(consigneeMin, comboRowWidth - statusWidth - supplierWidth - gap * 2);
                }

                x = pad;
                _comboOrderStatus.SetBounds(x, filterY, statusWidth, filterHeight);
                x = _comboOrderStatus.Right + gap;
                comboSuppliers.SetBounds(x, filterY, supplierWidth, filterHeight);
                x = comboSuppliers.Right + gap;
                _comboConsignees.SetBounds(x, filterY, consigneeWidth, filterHeight);

                y += buttonHeight + rowGap;
            }
            else
            {
                int filterY = y + (buttonHeight - filterHeight) / 2;
                int statusWidth = statusPreferredWidth;
                int supplierWidth = supplierPreferredWidth;
                int consigneeWidth = consigneePreferredWidth;

                if (middleAvailable < combosPreferred)
                {
                    float scale = middleAvailable / (float)combosPreferred;
                    statusWidth = Math.Max(statusMin, (int)(statusPreferredWidth * scale));
                    supplierWidth = Math.Max(supplierMin, (int)(supplierPreferredWidth * scale));
                    consigneeWidth = Math.Max(consigneeMin, middleAvailable - statusWidth - supplierWidth - gap * 2);
                }

                int comboRight = actionsLeft - gap;
                _comboConsignees.SetBounds(comboRight - consigneeWidth, filterY, consigneeWidth, filterHeight);
                comboRight = _comboConsignees.Left - gap;
                comboSuppliers.SetBounds(comboRight - supplierWidth, filterY, supplierWidth, filterHeight);
                comboRight = comboSuppliers.Left - gap;
                _comboOrderStatus.SetBounds(comboRight - statusWidth, filterY, statusWidth, filterHeight);

                y += buttonHeight + rowGap;
            }

            int searchY = y;
            int contentWidth = panelWidth - pad * 2;
            int fixedControlsWidth = clearSize * 2 + gap * 4 + commentMinWidth;
            int textAreaWidth = contentWidth - fixedControlsWidth;
            bool wrapComment = textAreaWidth < textMinWidth * 2;

            int textWidth;
            if (wrapComment)
            {
                int narrowTextArea = contentWidth - clearSize * 2 - gap * 2;
                textWidth = FitControlWidth(textPreferredWidth, textMinWidth, narrowTextArea / 2);
            }
            else
            {
                textWidth = textPreferredWidth;
            }

            int commentWidth = wrapComment
                ? Math.Min(commentMaxWidth, contentWidth)
                : commentMaxWidth;

            x = pad;
            txtGoodFromOrders.SetBounds(x, searchY, textWidth, controlHeight);
            x = txtGoodFromOrders.Right + gap;
            btnClearGoodSearch.SetBounds(x, searchY, clearSize, controlHeight);
            x = btnClearGoodSearch.Right + gap;
            txtOrderNumberFilter.SetBounds(x, searchY, textWidth, controlHeight);
            x = txtOrderNumberFilter.Right + gap;
            btnClearOrderNumberFilter.SetBounds(x, searchY, clearSize, controlHeight);
            x = btnClearOrderNumberFilter.Right + gap;

            if (wrapComment)
            {
                searchY += controlHeight + rowGap;
                btnAddComment.SetBounds(pad, searchY, commentWidth, buttonHeight);
                y = searchY + buttonHeight;
            }
            else
            {
                btnAddComment.SetBounds(x, searchY, commentWidth, buttonHeight);
                ModernButtonStyles.FitToText(btnAddComment, buttonHeight);
                y = searchY + buttonHeight;
            }

            ModernButtonStyles.ApplyClear(btnClearGoodSearch);
            ModernButtonStyles.ApplyClear(btnClearOrderNumberFilter);

            btnClearSuppliers.Visible = false;

            panelToolbar.Height = y + pad + 8;
            panelToolbar.Padding = new Padding(pad, 10, pad, 14);
        }

        private void ApplyOrderFilters()
        {
            var parts = new List<string>();
            if (!string.IsNullOrWhiteSpace(filter))
            {
                parts.Add(filter.Trim());
            }

            if (comboSuppliers.Visible &&
                comboSuppliers.SelectedItem != null &&
                comboSuppliers.Text != "Поставщик" &&
                !string.IsNullOrWhiteSpace(comboSuppliers.Text))
            {
                var supplier = comboSuppliers.Text.Replace("'", "''");
                parts.Add($"SupplierName = '{supplier}'");
            }

            if (_comboOrderStatus != null && _comboOrderStatus.SelectedIndex > 0)
            {
                parts.Add($"OrderState = '{_comboOrderStatus.SelectedItem}'");
            }

            if (_comboConsignees != null &&
                _comboConsignees.SelectedIndex > 0 &&
                !string.IsNullOrWhiteSpace(_comboConsignees.Text))
            {
                var consignee = _comboConsignees.Text.Replace("'", "''");
                parts.Add($"ConsigneeName = '{consignee}'");
            }

            if (_comboConsignees != null &&
                _comboConsignees.SelectedIndex > 0 &&
                !string.IsNullOrWhiteSpace(_comboConsignees.Text))
            {
                var consignee = _comboConsignees.Text.Replace("'", "''");
                parts.Add($"ConsigneeName = '{consignee}'");
            }

            var addon = parts.Count == 0 ? string.Empty : " and " + string.Join(" and ", parts);
            LoadOrders(
                dtpDateFrom.Value.ToString("yyyy-MM-dd"),
                dtpDateTo.Value.ToString("yyyy-MM-dd"),
                addon);
        }

        private async Task SendSelectedOrderAsync()
        {
            if (DGVOrders.Rows.Count == 0 || DGVOrders.SelectedRows.Count == 0)
            {
                ToastNotification.ShowCustom("Выберите заказ для отправки.", Color.DarkOrange, Color.White);
                return;
            }

            var status = DGVOrders.SelectedRows[0].Cells["Статус"]?.Value?.ToString();
            if (status != "НОВЫЙ")
            {
                ToastNotification.ShowCustom("Отправить можно только заказ со статусом НОВЫЙ.", Color.DarkOrange, Color.White);
                return;
            }

            var orderId = DGVOrders.SelectedRows[0].Cells["ИД заказа"].Value.ToString();
            try
            {
                var sender = new DataSender();
                await sender.SendSingleOrderAsync(orderId);
            }
            catch (Exception ex)
            {
                AppDebugLog.Error("Orders", $"Не удалось отправить заказ {orderId}", ex);
                ToastNotification.ShowError($"Не удалось отправить заказ: {ex.Message}");
            }

            ApplyOrderFilters();
        }

        private void RequestInvoiceForSelectedOrder()
        {
            if (DGVOrders.SelectedRows.Count == 0)
            {
                ToastNotification.ShowCustom("Выберите отправленный заказ.", Color.DarkOrange, Color.White);
                return;
            }

            var selectedRow = DGVOrders.SelectedRows[0];
            var status = selectedRow.Cells["Статус"]?.Value?.ToString();
            if (!string.Equals(status, "ОТПРАВЛЕН", StringComparison.OrdinalIgnoreCase))
            {
                ToastNotification.ShowCustom("Накладную можно получить только для отправленного заказа.", Color.DarkOrange, Color.White);
                return;
            }

            var orderId = selectedRow.Cells["ИД заказа"]?.Value?.ToString();
            if (string.IsNullOrWhiteSpace(orderId))
            {
                ToastNotification.ShowError("Не удалось определить идентификатор заказа.");
                return;
            }

            try
            {
                var service = new InvoiceSyncService();
                service.SyncFromServerAsync().GetAwaiter().GetResult();
                ToastNotification.ShowSuccess("Накладные обновлены с сервера.");

                var shell = FindForm() as ElectroPharmacy;
                shell?.OpenInvoicesTab(orderId);
            }
            catch (Exception ex)
            {
                ToastNotification.ShowError($"Не удалось получить накладную: {ex.Message}");
            }
        }

        void LoadOrders(string dateFrom, string dateTo, string filters)
        {
            string connectionStringToLocalDB = AppConfig.SqliteConnectionString;

            // OrderDate в БД исторически dd.MM.yyyy — сравниваем как даты, не как строки,
            // иначе «03.08» не попадает в диапазон «с 31.07» (лексикографически).
            const string orderDateIso = @"CASE
 WHEN length(OrderDate)=10 AND substr(OrderDate,3,1)='.' THEN
  substr(OrderDate,7,4)||'-'||substr(OrderDate,4,2)||'-'||substr(OrderDate,1,2)
 ELSE OrderDate
END";

            string qShowMeOrders = $@"
select 
[Id_Order],
[OrderNumber],
[OrderDate],
[Id_Supplier],
[SupplierName],
[OrderedCountItems],
[SummaZakaza],
[OrderState],
[Comment],
[ConsigneeName]
from Orders
where
({orderDateIso}) >= '{dateFrom}'
and ({orderDateIso}) <= '{dateTo}'
{filters}
";


            using (SQLiteConnection conOrders = new SQLiteConnection(connectionStringToLocalDB))
            {
                try
                {
                    conOrders.Open();
                    SQLiteCommand cmdShowMeOrders = new SQLiteCommand(qShowMeOrders, conOrders);
                    DataTable tableOrders = new DataTable();
                    SQLiteDataAdapter daOrders = new SQLiteDataAdapter(cmdShowMeOrders);
                    daOrders.Fill(tableOrders);

                    tableOrders.Columns[0].ColumnName = "ИД заказа";
                    tableOrders.Columns[1].ColumnName = "Номер заказа";
                    tableOrders.Columns[2].ColumnName = "Дата заказа";
                    tableOrders.Columns[3].ColumnName = "ИД поставщика";
                    tableOrders.Columns[4].ColumnName = "Поставщик";
                    tableOrders.Columns[5].ColumnName = "Кол-во наименований";
                    tableOrders.Columns[6].ColumnName = "Сумма заказа";
                    tableOrders.Columns[7].ColumnName = "Статус";
                    tableOrders.Columns[8].ColumnName = "Примечание";
                    if (tableOrders.Columns.Count > 9)
                    {
                        tableOrders.Columns[9].ColumnName = "Грузополучатель";
                    }
                    if (tableOrders.Columns.Count > 9)
                    {
                        tableOrders.Columns[9].ColumnName = "Грузополучатель";
                    }

                    //DGVOrders.DataSource = tableOrders;

                    bsOrder.DataSource = tableOrders;
                    DGVOrders.DataSource = bsOrder;

                    DGVOrders.Font = new Font("Segoe UI", 10f, FontStyle.Regular);
                    DGVOrders.ColumnHeadersDefaultCellStyle.Font = new Font("Segoe UI Semibold", 10f, FontStyle.Bold);
                    DGVOrders.DefaultCellStyle.Font = new Font("Segoe UI", 10f, FontStyle.Regular);

                    DGVOrders.Columns[0].Visible = false;
                    DGVOrders.Columns[3].Visible = false;

                    if (DGVOrders.Rows.Count > 0 && DGVOrders.SelectedRows.Count > 0)
                    {
                        int rowIndex = DGVOrders.SelectedRows[0].Index;
                        string idPriceList = DGVOrders.Rows[rowIndex].Cells[0].Value.ToString();
                        LoadOrderItem(idPriceList);
                    }
                    else
                    {
                        dgvOrderItems.DataSource = null;
                    }
                }
                catch (Exception ex)
                {
                    ToastNotification.ShowError($"Возникла ошибка при загрузке заказов.");
                    //MessageBox.Show($"Возникла ошибка при загрузке заказов. Текст ошибки:\n{ex.ToString()}", "Ошибка загрузки данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    conOrders.Close();
                }
            }
        }


        void getDatesFromCalendar()
        {
            string dateFrom = dtpDateFrom.Value.ToString("dd.MM.yyyy");
            string dateTo = dtpDateTo.Value.ToString("dd.MM.yyyy");

            string dateFromYear = dtpDateFrom.Value.ToString("yyyy");

            //loadInvoicesList(dateFrom, dateTo, dateFromYear);
        }

        void loadConsignees()
        {
            string connectionStringToLocalDB = AppConfig.SqliteConnectionString;
            string qShowMeConsigneesList = @"
select distinct ConsigneeName
from Orders
where trim(ifnull(ConsigneeName, '')) <> ''
order by ConsigneeName";

            using (SQLiteConnection conConsignees = new SQLiteConnection(connectionStringToLocalDB))
            {
                try
                {
                    conConsignees.Open();
                    SQLiteCommand cmdShowMeConsigneesList = new SQLiteCommand(qShowMeConsigneesList, conConsignees);
                    SQLiteDataAdapter daConsigneesList = new SQLiteDataAdapter(cmdShowMeConsigneesList);
                    DataTable tableConsignees = new DataTable();
                    daConsigneesList.Fill(tableConsignees);

                    if (_comboConsignees == null)
                    {
                        return;
                    }

                    var items = new List<string> { "Грузополучатель" };
                    items.AddRange(tableConsignees.Rows.Cast<DataRow>()
                        .Select(r => r["ConsigneeName"]?.ToString())
                        .Where(n => !string.IsNullOrWhiteSpace(n)));
                    _comboConsignees.DataSource = items;
                    _comboConsignees.SelectedIndex = 0;
                }
                catch (Exception)
                {
                    ToastNotification.ShowError("Ошибка получения списка грузополучателей.");
                }
                finally
                {
                    conConsignees.Close();
                }
            }
        }

        void loadSuppliers()
        {
            string connectionStringToLocalDB = AppConfig.SqliteConnectionString;

            string qShowMeSuppliersList = @"
select distinct SupplierName
from Orders
where trim(ifnull(SupplierName, '')) <> ''
order by SupplierName asc";

            using (SQLiteConnection conSuppliers = new SQLiteConnection(connectionStringToLocalDB))
            {
                try
                {
                    conSuppliers.Open();
                    SQLiteCommand cmdShowMeSuppliersList = new SQLiteCommand(qShowMeSuppliersList, conSuppliers);
                    SQLiteDataAdapter daSuppliersList = new SQLiteDataAdapter(cmdShowMeSuppliersList);
                    DataTable tableSuppliers = new DataTable();
                    daSuppliersList.Fill(tableSuppliers);
                    comboSuppliers.DataSource = tableSuppliers;
                    comboSuppliers.DisplayMember = "SupplierName";
                    comboSuppliers.Text = "Поставщик";
                }
                catch (Exception ex)
                {
                    ToastNotification.ShowError($"Ошибка получения списка поставщиков.");
                    //MessageBox.Show($"Возникла ошибка при списка поставщиков. Пожалуйста, обратитесь в службу технической поддержки.\nТекст ошибки:\n{ex.ToString()}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    conSuppliers.Close();
                }
            }
        }

        #region старые фильтры
        //public void ConstructFiltersForOrder()
        //{
        //    string dateFrom = dtpDateFrom.Value.ToString("yyyy-MM-dd");
        //    string dateTo = dtpDateTo.Value.ToString("yyyy-MM-dd");
        //    //string goodName = txtGoodFromOrders.Text;


        //    string filterAddons = $" and o.[OrderDate] between (select strftime('%Y-%m-%d','{dateFrom}')) and (select strftime('%Y-%m-%d','{dateTo}'))";

        //    //if (goodName!= "" & goodName != "Товар")
        //    //{
        //    //    filterAddons += $" and i.InvoiceNumber like '%{txtInvoiceNumber.Text}%'";
        //    //}

        //    if (comboSuppliers.Text != "" & comboSuppliers.Text != "Поставщик")
        //    {
        //        filterAddons += $" and supp.SuppliersName like '%{comboSuppliers.Text}%'";
        //    }

        //    if (comboConsignees.Text != "" & comboConsignees.Text != "Грузополучатель")
        //    {
        //        filterAddons += $" and consign.ConsigneesName like '%{comboConsignees.Text}%'";
        //    }


        //    //selectedTabPage(filterAddons);
        //}
        #endregion

        #region Старая загрузка позиций прайс-листа
//        public void loadOrderItems(string OrderNumber)
//        {

//            string qShowMeOrderItems = $@"
//select
//oi.[GoodCode] as [Код товара],
//oi.[GoodName] as [Наименование],
//oi.[OrderedCountItems] as [Заказно],
//oi.[SupplierPrice] as [Цена],
//oi.[SumOrderedItems] as [Сумма],
//oi.[RefuseItemsCount] as [Отказано],
//oi.[BestBefore] as [Срок годности],
//oi.[ProducerName] as [Производитель]
//from OrderItems oi
//";
//            string connectionStringToLocalDB = AppConfig.SqliteConnectionString;

//            if (OrderNumber != "" | OrderNumber != string.Empty)
//            {

//                qShowMeOrderItems += $@"
//inner join Orders on Orders.idOrder = oi.idOrder
//where Orders.OrderNumber = '{OrderNumber}'
//";
//            }
//            else
//            {
//                qShowMeOrderItems += " limit 0;";
//            }
//            using (SQLiteConnection conOrderItems = new SQLiteConnection(connectionStringToLocalDB))
//                {
//                    try
//                    {
//                        conOrderItems.Open();
//                        SQLiteCommand cmdShowMeOrderItems = new SQLiteCommand(qShowMeOrderItems, conOrderItems);
//                        SQLiteDataAdapter daOrderItems = new SQLiteDataAdapter(cmdShowMeOrderItems);
//                        DataTable tableOrderItems = new DataTable();
//                        daOrderItems.Fill(tableOrderItems);
//                        dgvOrderItem.DataSource = tableOrderItems;


//                    dgvOrderItem.DefaultCellStyle.Font = new Font("Segoe UI", 10, FontStyle.Regular);


//                    dgvOrderItem.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;

//                    dgvOrderItem.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;


//                    dgvOrderItem.Columns["Наименование"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
//                }
//                    catch (Exception ex)
//                    {
//                        MessageBox.Show(ex.ToString());
//                    }
//                    finally
//                    {
//                        conOrderItems.Close();
//                    }
//                }
//        }
        #endregion

        private void tabOrders_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        private void btnClearGoodSearch_Click(object sender, EventArgs e)
        {
            txtGoodFromOrders.Text = "Товар";
            filter = string.Empty;
            LoadOrders(dtpDateFrom.Value.ToString("yyyy-MM-dd"), dtpDateTo.Value.ToString("yyyy-MM-dd"), filter);
        }

        private void dtpDateFrom_ValueChanged(object sender, EventArgs e)
        {

            LoadOrders(dtpDateFrom.Value.ToString("yyyy-MM-dd"), dtpDateTo.Value.ToString("yyyy-MM-dd"), filter);
        }

        private void dtpDateTo_ValueChanged(object sender, EventArgs e)
        {
            LoadOrders(dtpDateFrom.Value.ToString("yyyy-MM-dd"), dtpDateTo.Value.ToString("yyyy-MM-dd"), filter);
        }

        private void dtpDateTo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (Char)Keys.Enter)
            {
                LoadOrders(dtpDateFrom.Value.ToString("yyyy-MM-dd"), dtpDateTo.Value.ToString("yyyy-MM-dd"), filter);
            }
        }

        private void dtpDateFrom_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (Char)Keys.Enter)
            {
                LoadOrders(dtpDateFrom.Value.ToString("yyyy-MM-dd"), dtpDateTo.Value.ToString("yyyy-MM-dd"), filter);
            }
        }

        private void comboSuppliers_SelectionChangeCommitted(object sender, EventArgs e)
        {
            ApplyOrderFilters();
        }

        private void comboConsignees_SelectionChangeCommitted(object sender, EventArgs e)
        {
            ApplyOrderFilters();
        }

        private void txtGoodFromOrders_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (Char)Keys.Enter)
            {
                if(txtGoodFromOrders.Text != string.Empty & txtGoodFromOrders.Text != "Товар")
                {
                    filter += $@"
and Id_Order in (select Id_Order from OrderItems where DrugName like '%{txtGoodFromOrders.Text}%')
";

                    LoadOrders(dtpDateFrom.Value.ToString("yyyy-MM-dd"), dtpDateTo.Value.ToString("yyyy-MM-dd"), filter);
                }
            }
        }

        private void txtGoodFromOrders_Enter(object sender, EventArgs e)
        {
            if (txtGoodFromOrders.Text == "Товар")
            {
                txtGoodFromOrders.Text = string.Empty;
            }
        }

        private void txtGoodFromOrders_Leave(object sender, EventArgs e)
        {
            if (txtGoodFromOrders.Text == "")
            {
                txtGoodFromOrders.Text = "Товар";
            }
        }

        private void btnClearSuppliers_Click(object sender, EventArgs e)
        {
            loadSuppliers();
            //ConstructFiltersForOrder();
        }

        private void btnClearConsignees_Click(object sender, EventArgs e)
        {
            //loadConsignees();
            //ConstructFiltersForOrder();
        }

        private void comboSuppliers_SelectedIndexChanged(object sender, EventArgs e)
        {
            ApplyOrderFilters();
        }

        private void comboConsignees_SelectedIndexChanged(object sender, EventArgs e)
        {
            //ConstructFiltersForOrder();
        }

        private void DGVOrders_SelectionChanged(object sender, EventArgs e)
        {
            if(DGVOrders.Rows.Count > 0)
            {
                try
                {
                    int rowIndex = DGVOrders.SelectedRows[0].Index;
                    string idPriceList = DGVOrders.Rows[rowIndex].Cells[0].Value.ToString();

                    LoadOrderItem(idPriceList);
                }
                catch
                {

                }
            }
        }

        void LoadOrderItem(string idPriceList)
        {
            string connectionStringToLocalDB = AppConfig.SqliteConnectionString;
            string qShowMeOrderItems = $@"
select 
[Id_Order_Item],
[Id_Order],
[guid_es],
[es_code],
[DrugName],
[Price],
[Zakaz],
[SummaZakaza],
[ExpiryPeriod],
[RefuseItemsCount],
[supplier_price_id]
from OrderItems
where [id_order] = '{idPriceList}'
";

            string countOrderItems = $"select count(*) from OrderItems where id_order = '{idPriceList}'";

            using (SQLiteConnection conOrderItem = new SQLiteConnection(connectionStringToLocalDB))
            {
                try
                {
                    conOrderItem.Open();

                    SQLiteCommand cmdShowMeCountData = new SQLiteCommand(countOrderItems, conOrderItem);

                    SQLiteCommand cmdShowMeOrderItems = new SQLiteCommand(qShowMeOrderItems, conOrderItem);
                    SQLiteDataAdapter daOrderItems = new SQLiteDataAdapter(cmdShowMeOrderItems);
                    DataTable tableOrderItems = new DataTable();
                    daOrderItems.Fill(tableOrderItems);

                    tableOrderItems.Columns[0].ColumnName = "ИД позиц. п-л";
                    tableOrderItems.Columns[1].ColumnName = "ИД прайс-листа";
                    tableOrderItems.Columns[2].ColumnName = "ИД товара";
                    tableOrderItems.Columns[3].ColumnName = "Код товара";
                    tableOrderItems.Columns[4].ColumnName = "Наименование";
                    tableOrderItems.Columns[5].ColumnName = "Цена";
                    tableOrderItems.Columns[6].ColumnName = "Заказано";
                    tableOrderItems.Columns[7].ColumnName = "Сумма заказа";
                    tableOrderItems.Columns[8].ColumnName = "Срок годности";
                    tableOrderItems.Columns[9].ColumnName = "Кол-во отказано";

                    dataGridView1.DataSource = tableOrderItems;

                    dataGridView1.Font = new Font("Segoe UI", 10f, FontStyle.Regular);
                    dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font("Segoe UI Semibold", 10f, FontStyle.Bold);

                    dataGridView1.Columns[0].Visible = false;
                    dataGridView1.Columns[1].Visible = false;
                    dataGridView1.Columns[2].Visible = false;
                    dataGridView1.Columns[10].Visible = false;

                    dataGridView1.Columns[3].Width = 140;
                    dataGridView1.Columns[4].Width = 750;
                    dataGridView1.Columns[5].Width = 90;
                    dataGridView1.Columns[6].Width = 140;
                    dataGridView1.Columns[7].Width = 90;
                    dataGridView1.Columns[8].Width = 140;
                    dataGridView1.Columns[9].Width = 140;
                }
                catch(Exception ex)
                {
                    ToastNotification.ShowError($"Не удалось загрузить данные заказа");
                    //MessageBox.Show($"При загрузке данных о позициях заказа возникла ошибка. Текст ошибки:{ex.ToString()}", "Ошибка загрузки данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    conOrderItem.Close();
                }
            }
        }

        private void txtOrderNumberFilter_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (Char)Keys.Enter)
            {
                if (txtOrderNumberFilter.Text != string.Empty & txtOrderNumberFilter.Text != "Номер заказа")
                {
                    filter += $@"
and OrderNumber like '%{txtOrderNumberFilter.Text}%'
";

                    LoadOrders(dtpDateFrom.Value.ToString("yyyy-MM-dd"), dtpDateTo.Value.ToString("yyyy-MM-dd"), filter);
                }
            }
        }

        private void txtOrderNumberFilter_Leave(object sender, EventArgs e)
        {
            if (txtOrderNumberFilter.Text == "")
            {
                txtOrderNumberFilter.Text = "Номер заказа";
            }
        }

        private void txtOrderNumberFilter_Enter(object sender, EventArgs e)
        {
            if (txtOrderNumberFilter.Text == "Номер заказа")
            {
                txtOrderNumberFilter.Text = string.Empty;
            }
        }

        private void btnClearOrderNumberFilter_Click(object sender, EventArgs e)
        {
            txtOrderNumberFilter.Text = "Номер заказа";
            filter = string.Empty;
            LoadOrders(dtpDateFrom.Value.ToString("yyyy-MM-dd"), dtpDateTo.Value.ToString("yyyy-MM-dd"), filter);
        }

        private void btnAddComment_Click(object sender, EventArgs e)
        {
            if (DGVOrders.Rows.Count > 0)
            {
                int rowIndex = DGVOrders.SelectedRows[0].Index;
                string Id_Order = DGVOrders.Rows[rowIndex].Cells[0].Value.ToString();
                string OrderNumber = DGVOrders.Rows[rowIndex].Cells[1].Value.ToString();

                HF_Comment hf_comment = new HF_Comment(OrderNumber, Id_Order);
                hf_comment.ShowDialog();
                LoadOrders(dtpDateFrom.Value.ToString("yyyy-MM-dd"), dtpDateTo.Value.ToString("yyyy-MM-dd"), string.Empty);
            }
        }

        private void btnDeleteOrder_Click(object sender, EventArgs e)
        {
            if (DGVOrders.Rows.Count > 0)
            {
                int rowIndex = DGVOrders.SelectedRows[0].Index;
                string Id_Order = DGVOrders.Rows[rowIndex].Cells[0].Value.ToString();
                string OrderNumber = DGVOrders.Rows[rowIndex].Cells[1].Value.ToString();
                string OrderStatus = DGVOrders.Rows[rowIndex].Cells[7].Value.ToString();

                if (OrderStatus == "НОВЫЙ")
                {
                    DialogResult drDeleteOrder = UiDialogs.ConfirmYesNoCancel($"Вы действительно хотите удалить заказ {OrderNumber}?", "Удаление", FindForm());

                    if (drDeleteOrder == DialogResult.Yes)
                    {
                        string connectionStringToLocalDB = AppConfig.SqliteConnectionString;
                        string qDeleteOrderItems = $@"
    delete from OrderItems where [id_order] = '{Id_Order}'";
                        string qDeleteOrder = $@"
    delete from Orders where [Id_Order] = '{Id_Order}'";
                    
                        using(SQLiteConnection conDeleteOrder = new SQLiteConnection(connectionStringToLocalDB))
                        {
                            try
                            {
                                conDeleteOrder.Open();
                                SQLiteCommand cmdDeleteOrderItems = new SQLiteCommand(qDeleteOrderItems, conDeleteOrder);
                                SQLiteCommand cmdDeleteOrder = new SQLiteCommand(qDeleteOrder, conDeleteOrder);
                                cmdDeleteOrderItems.ExecuteNonQuery();
                                cmdDeleteOrder.ExecuteNonQuery();
                                //ToastNotification.ShowCustom($"Заказ {OrderNumber} был удалён", Color.DarkOrange, Color.White);
                                ToastNotification.ShowSuccess($"Заказ {OrderNumber} был удалён");
                                //MessageBox.Show($"Заказ {OrderNumber} был успешно удалён.", "Удаление заказа", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                LoadOrders(dtpDateFrom.Value.ToString("yyyy-MM-dd"), dtpDateTo.Value.ToString("yyyy-MM-dd"), string.Empty);
                            }
                            catch(Exception ex)
                            {
                                ToastNotification.ShowError($"Не удалось удалить заказ {OrderNumber}.\n{ex.Message}");
                                //MessageBox.Show($"При удалении заказа {OrderNumber} возникла ошибка. Заказ не был удалён. \nТекст ошибки:\n{ex.ToString()}", "Ошибка удаления", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            finally
                            {
                                conDeleteOrder.Close();
                            }
                        }
                    }
                }
                else
                {
                    ToastNotification.ShowCustom($"Можно удалять только неотправленные заказы", Color.DarkOrange, Color.White);
                }
            }
        }
    }
}
