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;
using System.Data.SQLite;
using System.Data.OleDb;
using System.Data.Common;
using Электронная_Фармация.Classes;
using Электронная_Фармация.HelpForms;

namespace Электронная_Фармация.UserControls
{
    public partial class UCPriceList : UserControl
    {
        public UCPriceList(string workWithConsignee)
        {
            InitializeComponent();
            _WorkWithConsignee = workWithConsignee;
        }

        public string ConsigneeName => txtConsignee?.Text ?? string.Empty;

        SQLiteDataAdapter daPriceList;
        DataSet dsPriceList;
        BindingSource bsPriceList = new BindingSource();
        DataAdapter daPriceListMain;
        DataTable tablePriceList;
        string _WorkWithConsignee;
        decimal _percentageAsDefault;
        string _selectedSupplierFilter = string.Empty;
        bool _suppressSupplierFilterEvents;
        int _committedSupplierFilterIndex;

        string connectionStringToLocalDB = AppConfig.SqliteConnectionString;

        public void RefreshFromDatabase()
        {
            loadPriceListV2();
            InitializeSupplierFilter();
            loadTempOrderItems();
            ApplyPriceListFilters();
        }

        private void UCPriceList_Load(object sender, EventArgs e)
        {
            UiThemeHelper.ApplyToControlTree(this);
            Tag = "chrome-child";

            btnDeleteGood.Height = 34;
            btnClearSearchInPriceList.Height = 32;
            txtSearchGoodNameInPriceList.Height = 32;
            btnClearSupplierFilter.Height = 32;

            panel1.SizeChanged += (_, __) => LayoutMarkupRow();
            LayoutMarkupRow();

            txtConsignee.Enabled = false;
            txtConsignee.Text = _WorkWithConsignee;
            //loadConsignees();
            //loadPriceList(string.Empty);
            loadPriceListV2();
            InitializeSupplierFilter();
            loadTempOrderItems();
            loadInfoAboutDefaultMarkup();
            txtSearchGoodNameInPriceList.Focus();
        }

        private void LayoutMarkupRow()
        {
            // Keep markup row readable at different DPI/window sizes.
            try
            {
                var paddingLeft = 8;
                var y = 30;
                var gap = 8;

                label4.Location = new Point(paddingLeft, y + 2);

                numericPercent.Location = new Point(label4.Right + 6, y);
                numericPercent.Width = 56;

                checkUsePercentageAsDefault.AutoSize = true;
                checkUsePercentageAsDefault.Location = new Point(
                    Math.Max(numericPercent.Right + gap, panel1.ClientSize.Width - checkUsePercentageAsDefault.PreferredSize.Width - 10),
                    y + 2);

                lblPriceForGood.AutoSize = false;
                lblPriceForGood.AutoEllipsis = true;
                lblPriceForGood.Location = new Point(numericPercent.Right + gap, y + 2);
                lblPriceForGood.Height = 22;
                lblPriceForGood.Width = Math.Max(90, checkUsePercentageAsDefault.Left - lblPriceForGood.Left - gap);
            }
            catch
            {
                // best-effort layout; ignore
            }
        }

        private void InitializeSupplierFilter()
        {
            try
            {
                _suppressSupplierFilterEvents = true;
                comboSupplierFilter.BeginUpdate();
                comboSupplierFilter.Items.Clear();
                comboSupplierFilter.Items.Add("Все поставщики");

                var suppliers = new List<string>();
                using (var con = new SQLiteConnection(connectionStringToLocalDB))
                {
                    con.Open();
                    using (var cmd = new SQLiteCommand("select SupplierName from PriceList where SupplierName is not null and SupplierName <> '' group by SupplierName order by SupplierName asc;", con))
                    {
                        using (var reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                var value = reader.GetString(0);
                                if (!string.IsNullOrWhiteSpace(value))
                                {
                                    suppliers.Add(value);
                                }
                            }
                        }
                    }
                }

                foreach (var s in suppliers)
                {
                    comboSupplierFilter.Items.Add(s);
                }

                comboSupplierFilter.SelectedIndex = 0;
                _selectedSupplierFilter = string.Empty;
                _committedSupplierFilterIndex = comboSupplierFilter.SelectedIndex;
                btnClearSupplierFilter.Visible = false;
            }
            finally
            {
                comboSupplierFilter.EndUpdate();
                _suppressSupplierFilterEvents = false;
            }
        }

        private void ApplyPriceListFilters()
        {
            var parts = new List<string>();

            if (!string.IsNullOrWhiteSpace(_selectedSupplierFilter))
            {
                var escapedSupplier = _selectedSupplierFilter.Replace("'", "''");
                parts.Add($"[Поставщик] = '{escapedSupplier}'");
            }

            if (!string.IsNullOrWhiteSpace(GoodsFilter))
            {
                var escaped = GoodsFilter.Replace("'", "''");
                parts.Add($"[Наименование] like '%{escaped}%'");
            }

            bsPriceList.Filter = parts.Count == 0 ? null : string.Join(" AND ", parts);
        }

        private void comboSupplierFilter_SelectionChangeCommitted(object sender, EventArgs e)
        {
            // Defer until the dropdown has fully closed.
            BeginInvoke(new Action(ApplySupplierFilterFromCombo));
        }

        private void ApplySupplierFilterFromCombo()
        {
            if (_suppressSupplierFilterEvents)
            {
                return;
            }

            if (comboSupplierFilter.SelectedIndex == _committedSupplierFilterIndex)
            {
                return;
            }

            _committedSupplierFilterIndex = comboSupplierFilter.SelectedIndex;

            var selected = comboSupplierFilter.SelectedItem as string;
            if (string.IsNullOrWhiteSpace(selected) || selected == "Все поставщики")
            {
                _selectedSupplierFilter = string.Empty;
                btnClearSupplierFilter.Visible = false;
            }
            else
            {
                _selectedSupplierFilter = selected;
                btnClearSupplierFilter.Visible = true;
            }

            ApplyPriceListFilters();
        }

        private void btnClearSupplierFilter_Click(object sender, EventArgs e)
        {
            _suppressSupplierFilterEvents = true;
            comboSupplierFilter.SelectedIndex = 0;
            _suppressSupplierFilterEvents = false;

            _committedSupplierFilterIndex = comboSupplierFilter.SelectedIndex;
            _selectedSupplierFilter = string.Empty;
            btnClearSupplierFilter.Visible = false;
            ApplyPriceListFilters();
        }

        private DataTable LoadPriceListTable(string supplierName)
        {
            var tablePrice = new DataTable();

            var q = "select * from PriceList";
            if (!string.IsNullOrWhiteSpace(supplierName))
            {
                q += " where SupplierName = @supplierName";
            }

            using (var con = new SQLiteConnection(connectionStringToLocalDB))
            {
                con.Open();
                using (var cmd = new SQLiteCommand(q, con))
                {
                    if (!string.IsNullOrWhiteSpace(supplierName))
                    {
                        cmd.Parameters.AddWithValue("@supplierName", supplierName);
                    }

                    using (var da = new SQLiteDataAdapter(cmd))
                    {
                        da.Fill(tablePrice);
                    }
                }
            }

            return tablePrice;
        }

        private void ApplyPriceListTable(DataTable tablePrice)
        {
            // Keep existing logic: just rename columns and re-bind.
            tablePrice.Columns[0].ColumnName = "ИД товара";
            tablePrice.Columns[1].ColumnName = "Код товара";
            tablePrice.Columns[2].ColumnName = "ИД поставщика";
            tablePrice.Columns[3].ColumnName = "Наименование";
            tablePrice.Columns[4].ColumnName = "Поставщик";
            tablePrice.Columns[5].ColumnName = "Цена";
            tablePrice.Columns[6].ColumnName = "Остаток";
            tablePrice.Columns[7].ColumnName = "Срок годности";
            tablePrice.Columns[8].ColumnName = "Описание";
            tablePrice.Columns[9].ColumnName = "Заказ";
            tablePrice.Columns[10].ColumnName = "Сумма";
            tablePrice.Columns[12].ColumnName = "ИДПрайсЛистАйтем";

            bsPriceList.DataSource = tablePrice;
            dgvPriceList.DataSource = bsPriceList;
            dgvPriceList.AutoGenerateColumns = true;
            dgvPriceList.Font = new Font("Segoe UI", 13, FontStyle.Regular);

            dgvPriceList.Columns[0].Visible = false;
            dgvPriceList.Columns[1].Visible = false;
            dgvPriceList.Columns[2].Visible = false;
            dgvPriceList.Columns[7].Visible = true;
            dgvPriceList.Columns[8].Visible = false;
            dgvPriceList.Columns[11].Visible = false;
            dgvPriceList.Columns[12].Visible = false;

            dgvPriceList.Columns[3].Width = 760;
            dgvPriceList.Columns[4].Width = 150;
            dgvPriceList.Columns[5].Width = 120;
            dgvPriceList.Columns[6].Width = 100;
            dgvPriceList.Columns[7].Width = 140;
            dgvPriceList.Columns[9].Width = 100;
            dgvPriceList.Columns[10].Width = 100;
        }


        void loadInfoAboutDefaultMarkup()
        {
            decimal percentageMarkupDefault = Convert.ToDecimal(Properties.Settings.Default.IntDefaultPercentMarkup);

            if (percentageMarkupDefault == 0)
            {
                percentageMarkupDefault = 30;
            }

            _percentageAsDefault = percentageMarkupDefault;
            numericPercent.Value = Convert.ToDecimal(Properties.Settings.Default.IntDefaultPercentMarkup);

        }

        public void loadSupplierTabs(string SupplierName)
        {
            string tabName;

            if (SupplierName == string.Empty)
            {
                tabName = "Корзина";
            }
            else
            {
                tabName = SupplierName;
            }

            TabPage pageSupplier = new TabPage($"{tabName}");
            UCOrderItems UCOrderItemsBySuppliers = new UCOrderItems(SupplierName);
            UCOrderItemsBySuppliers.ParentForm = this;

            pageSupplier.SuspendLayout();
            pageSupplier.ResumeLayout();
            tabOrderItems.TabPages.Add(pageSupplier);


            pageSupplier.Controls.Add(UCOrderItemsBySuppliers);

            UCOrderItemsBySuppliers.Dock = DockStyle.Fill;

            tabOrderItems.SelectTab(pageSupplier);
        }

        public void loadTempOrderItems()
        {
            string connectionStringToLocalDB = AppConfig.SqliteConnectionString;

            List<String> SuppliersFromOrder = new List<String>();

            string qShowMeSuppliersFromOrder = $@"
select 
[SupplierName]
from [TempOrderItems]
group by [SupplierName]
";

            tabOrderItems.TabPages.Clear();

            int tabPagesCount = tabOrderItems.TabCount;

            loadSupplierTabs(string.Empty);

            using (SQLiteConnection conSuppliersTempOrderGroup = new SQLiteConnection(connectionStringToLocalDB))
            {
                try
                {
                    conSuppliersTempOrderGroup.Open();
                    SQLiteCommand cmdShowMeSuppliersFromOrder = new SQLiteCommand(qShowMeSuppliersFromOrder, conSuppliersTempOrderGroup);
                    SQLiteDataReader dr = cmdShowMeSuppliersFromOrder.ExecuteReader();

                    while (dr.Read())
                    {
                        loadSupplierTabs(dr.GetString(0));
                    }
                }
                catch(Exception ex)
                {
                    ToastNotification.ShowError($"Ошибка при создании вкладок: {ex.Message}");
                }
                finally
                {
                    conSuppliersTempOrderGroup.Close();
                }
            }
            dgvPriceList.Focus();
        }


        public void loadPriceListV2()
        {
            ApplyPriceListTable(LoadPriceListTable(string.Empty));
            ApplyPriceListFilters();
        }

        private void loadPriceListV2(string supplierFilter)
        {
            ApplyPriceListTable(LoadPriceListTable(string.Empty));
            _selectedSupplierFilter = supplierFilter ?? string.Empty;
            ApplyPriceListFilters();
        }

        #region старая загрузка прайсов
        public void loadPriceListV1(string FilterAddon)
        {
            string connectionStringToLocalDB = AppConfig.SqliteConnectionString;

            string qShowMePriceList = $@"
select
pl.[GoodCode] as [Код товара],
pl.[GoodName] as [Наименование],
pl.[ProducerName] as [Производитель],
pl.[SupplierName] as [Поставщик],
pl.[BestBefore] as [Срок годности],
pl.[JNVLS] as [ЖНВЛП?],
pl.[AvaibleCount] as [Доступно],
pl.[PriceSupplierWithNDS] as [Цена],
pl.[CountIWantBuy] as [Заказано],
pl.[SumIWantBuy] as [Сумма],
pl.[Marked] as [Признак маркировки]
from [PriceList] pl
where pl.AvaibleCount > 0
and pl.ConsigneesCode = (select codeConsignees from Consignees where ConsigneesName = '{_WorkWithConsignee}')
{FilterAddon}
order by pl.goodname asc
";

            SQLiteConnection conPriceList = new SQLiteConnection(connectionStringToLocalDB);
            try
            {
                conPriceList.Open();
                daPriceList = new SQLiteDataAdapter(qShowMePriceList, conPriceList);
                dsPriceList = new DataSet();
                daPriceList.Fill(dsPriceList, "PriceList");


                dgvPriceList.DataSource = dsPriceList.Tables["PriceList"];

                //dgvPriceList.AutoGenerateColumns = true;
                BindingSource bsPriceList = new BindingSource();
                bsPriceList.DataSource = dsPriceList.Tables["PriceList"];



                dgvPriceList.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing;
                dgvPriceList.RowHeadersVisible = false;

                dgvPriceList.Columns[0].ReadOnly = true;
                dgvPriceList.Columns[1].ReadOnly = true;
                dgvPriceList.Columns[2].ReadOnly = true;
                dgvPriceList.Columns[3].ReadOnly = true;
                dgvPriceList.Columns[4].ReadOnly = true;
                dgvPriceList.Columns[5].ReadOnly = true;
                dgvPriceList.Columns[6].ReadOnly = true;
                dgvPriceList.Columns[7].ReadOnly = true;
                dgvPriceList.Columns[8].ReadOnly = true;
                dgvPriceList.Columns[9].ReadOnly = false;
                dgvPriceList.Columns[10].ReadOnly = true;

                dgvPriceList.Columns[9].DefaultCellStyle.Format = "N0";

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


                //dgvPriceList.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;

                dgvPriceList.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;

                dgvPriceList.Columns["Код товара"].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
                dgvPriceList.Columns["Код товара"].Width = 1;

                dgvPriceList.Columns["Наименование"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvPriceList.Columns["Производитель"].Width = 200;
                dgvPriceList.Columns["Поставщик"].Width = 130;
                dgvPriceList.Columns["Срок годности"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                //dgvPriceList.Columns["Доступно"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                //dgvPriceList.Columns["Цена"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                //dgvPriceList.Columns["Заказано"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                //dgvPriceList.Columns["Сумма"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                //dgvPriceList.Columns["Признак маркировки"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;

                dgvPriceList.Columns["ЖНВЛП?"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;

            }
            catch (Exception ex)
            {
                ToastNotification.ShowError($"Ошибка загрузки прайс-листа: {ex.Message}");
            }
            finally
            {
                conPriceList.Close();
            }

        }
        #endregion



        void AddItemInOrdersItems(string GoodCode, string GoodName, string SupplierName, string ItemConsigner, string BestBefore, string CountItem, string SumItem, string PriceItem)
        {
            string connectionStringToLocalDB = AppConfig.SqliteConnectionString;

            using (SQLiteConnection conTempOrder = new SQLiteConnection(connectionStringToLocalDB))
            {


                string qInsertDataInTempTableOrderItems = $@"
insert into [TempOrderItems] values (
'{GoodCode}',
'{GoodName}',
'{SupplierName}',
'{ItemConsigner}',
'{CountItem}',
'{SumItem}',
'{PriceItem}',
'{BestBefore}'
)
";

                string qShowMeCountsOfOrderedThatGood = $@"
select count(GoodCode) from TempOrderItems where
GoodCode = '{GoodCode}' and
GoodName = '{GoodName}' and
SupplierName = '{SupplierName}' and
ConsigneesName = '{ItemConsigner}' and
SupplierPrice = '{PriceItem}' and
BestBefore  = '{BestBefore}'
";

                string qUpdateOrderedPriceListItems = $@"
update TempOrderItems
set OrderedCountItems = '{CountItem}',
SumOrderedItems = '{SumItem}'
where
GoodCode = '{GoodCode}' and
GoodName = '{GoodName}' and
SupplierName = '{SupplierName}' and
ConsigneesName = '{ItemConsigner}' and
SupplierPrice = '{PriceItem}' and
BestBefore  = '{BestBefore}'
";

                try
                {
                    conTempOrder.Open();
                    int RowCountsOfThatGood = 0;
                    SQLiteCommand cmdCheckCountOfOrderedItems = new SQLiteCommand(qShowMeCountsOfOrderedThatGood, conTempOrder);
                    RowCountsOfThatGood = Convert.ToInt32(cmdCheckCountOfOrderedItems.ExecuteScalar());
                    if (RowCountsOfThatGood > 0)
                    {
                        SQLiteCommand cmdUpdatePriceListItems = new SQLiteCommand(qUpdateOrderedPriceListItems, conTempOrder);
                        cmdUpdatePriceListItems.ExecuteNonQuery();
                    }
                    else
                    {
                        SQLiteCommand cmdFillTempOrderItems = new SQLiteCommand(qInsertDataInTempTableOrderItems, conTempOrder);
                        cmdFillTempOrderItems.ExecuteNonQuery();
                    }
                }
                catch (Exception ex)
                {
                    ToastNotification.ShowError($"Ошибка заполнения корзины: {ex.Message}");
                }
                finally
                {
                    conTempOrder.Close();
                }
                loadTempOrderItems();
            }
        }

        private void btnSendOrder_Click(object sender, EventArgs e)
        {
            string connectionStringToLocalDB = AppConfig.SqliteConnectionString;

            string OrderNumber = $"EP-{DateTime.Now.Millisecond.ToString()}{DateTime.Now.Date.ToString("mmdd")}";
            string OrderDate = DateTime.Now.ToString("yyyy-MM-dd");//DateTime.Now.ToShortDateString();

            

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

                    string CountOrderedItems;
                    string SumOrderedItems;

                    string qShowMeCountOrderedItems = "select count(GoodCode) from TempOrderItems where OrderedCountItems > 0";
                    string qShowMeSumOrderedItems = "select sum(SumOrderedItems) from TempOrderItems where OrderedCountItems > 0";

                    SQLiteCommand cmdShowMeCountOfOrderedItems = new SQLiteCommand(qShowMeCountOrderedItems, conCreateOrder);
                    SQLiteCommand cmdShowMeSumOfOrderedItems = new SQLiteCommand(qShowMeSumOrderedItems, conCreateOrder);

                    qShowMeCountOrderedItems = Convert.ToString(cmdShowMeCountOfOrderedItems.ExecuteScalar());
                    qShowMeSumOrderedItems = Convert.ToString(cmdShowMeSumOfOrderedItems.ExecuteScalar());

                    string qCreateOrder = $@"
insert into [Orders] (OrderNumber, OrderDate, OrderedItemsCount, OrderSum, OrderState)
values
(
'{OrderNumber}',
select strftime('%Y-%m-%d','{OrderDate}'),
'{qShowMeCountOrderedItems}',
'{qShowMeSumOrderedItems}',
'SAVE'
)
";

                    

                    SQLiteCommand cmdCreateOrder = new SQLiteCommand(qCreateOrder, conCreateOrder);
                    cmdCreateOrder.ExecuteNonQuery();

                    foreach (DataGridViewRow row in dgvOrder.Rows)
                    {
                        string qCreateOrderItems = $@"
    insert into OrderItems (idOrder, GoodCode, GoodName, codeSuppliers, codeConsignees, OrderedCountItems, SupplierPrice, SumOrderedItems, BestBefore, ProducerName, ProducerPrice)
    values
    (
        (select idOrder from Orders where OrderNumber = '{OrderNumber}'),
        '{row.Cells[0].Value.ToString()}',
        '{row.Cells[1].Value.ToString()}',
        (select codeSuppliers from Suppliers where SuppliersName = '{row.Cells[2].Value.ToString()}'),
        (select codeConsignees from Consignees where ConsigneesName = '{row.Cells[3].Value.ToString()}'),
        '{row.Cells[5].Value.ToString()}',
        '{row.Cells[4].Value.ToString()}',
        '{row.Cells[6].Value.ToString()}',
        '{row.Cells[7].Value.ToString()}',
        '{row.Cells[8].Value.ToString()}',
        '{row.Cells[9].Value.ToString()}'
    )
    ";

                        SQLiteCommand cmdCreateOrderItems = new SQLiteCommand(qCreateOrderItems, conCreateOrder);
                        cmdCreateOrderItems.ExecuteNonQuery();
                    }
                    EraseOrder();
                }
                catch (Exception ex)
                {
                    ToastNotification.ShowError($"Ошибка формирования заказа: {ex.Message}");
                }
                finally
                {
                    conCreateOrder.Close();
                    
                }
            }
        }


        #region TODO: что-то с заказом, потом доделать под актуальную версию
//        void IWantBuyThisGood()
//        {
//            int selectedRowIndex = dgvPriceList.CurrentRow.Index;
//            //int IWantBuyGood = Convert.ToInt32(dgvPriceList.Rows[selectedRowIndex].Cells[10].Value.ToString());
//            int IWantBuyGood = Convert.ToInt32(dgvPriceList.Rows[selectedRowIndex].Cells[8].Value.ToString());

//            if (IWantBuyGood <= 0)
//            {
//                ErasePriceListOrderItem();
//            }
//            else if (IWantBuyGood > 0)
//            {
//                double SuppliersPrice = Convert.ToDouble(dgvPriceList.Rows[selectedRowIndex].Cells[7].Value.ToString());
//                double SumGoodsIWantBuy = SuppliersPrice * IWantBuyGood;
//                string sumBuy = SumGoodsIWantBuy.ToString();
//                dgvPriceList.Rows[selectedRowIndex].Cells[9].Value = sumBuy.ToString();
//                //dgvPriceList.Rows[selectedRowIndex].Cells[11].Value = "1";//SumGoodsIWantBuy.ToString();
//                //dgvPriceList.CurrentRow.Cells[11].Value =  SumGoodsIWantBuy.ToString();

//                string qUpdateCountAndSumInPriceListTable = $@"
//update PriceList set 
//[CountIWantBuy] = '{IWantBuyGood.ToString()}',
//[SumIWantBuy] = '{sumBuy.ToString()}'
//where 
//[GoodCode] = '{dgvPriceList.Rows[selectedRowIndex].Cells[0].Value.ToString()}'
//and [GoodName] = '{dgvPriceList.Rows[selectedRowIndex].Cells[1].Value.ToString()}'
//and [ProducerName] = '{dgvPriceList.Rows[selectedRowIndex].Cells[2].Value.ToString()}'
//and [SupplierName] = '{dgvPriceList.Rows[selectedRowIndex].Cells[3].Value.ToString()}'
//and [ConsigneesCode] = (select codeConsignees from Consignees where ConsigneesName = '{_WorkWithConsignee}')
//";
//                string connectionStringToLocalDB = AppConfig.SqliteConnectionString;

//                //dgvPriceList.Rows[selectedRowIndex].DefaultCellStyle.Font = new Font("Segoe UI", 10, FontStyle.Bold);

//                using (SQLiteConnection conUpdateBuyingGoods = new SQLiteConnection(connectionStringToLocalDB))
//                {
//                    try
//                    {
//                        conUpdateBuyingGoods.Open();
//                        SQLiteCommand cmdUpdateBuyingGoods = new SQLiteCommand(qUpdateCountAndSumInPriceListTable, conUpdateBuyingGoods);
//                        cmdUpdateBuyingGoods.ExecuteNonQuery();
//                    }
//                    catch (Exception ex)
//                    {
//                        MessageBox.Show($"Возникла ошибка при обновлении данных о закупке товаров. Текст ошибки:\n{ex.ToString()}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
//                    }
//                    finally
//                    {
//                        conUpdateBuyingGoods.Close();
//                    }
//                }



//                string ItemConsigner = txtConsignee.Text;
//                //if (ItemConsigner == "" | ItemConsigner == "Грузополучатель")
//                //{
//                //    MessageBox.Show("Пожалуйста, укажите грузополучателя.", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Hand);
//                //}
//                //else
//                //{
//                    string GoodCode = dgvPriceList.Rows[selectedRowIndex].Cells[0].Value.ToString();
//                    string GoodName = dgvPriceList.Rows[selectedRowIndex].Cells[1].Value.ToString();
//                    string SupplierName = dgvPriceList.Rows[selectedRowIndex].Cells[3].Value.ToString();
//                    string BestBefore = dgvPriceList.Rows[selectedRowIndex].Cells[4].Value.ToString();
//                    string CountItem = dgvPriceList.Rows[selectedRowIndex].Cells[8].Value.ToString();
//                    string SumItem = dgvPriceList.Rows[selectedRowIndex].Cells[9].Value.ToString();
//                    string PriceItem = dgvPriceList.Rows[selectedRowIndex].Cells[7].Value.ToString();

//                    AddItemInOrdersItems(GoodCode, GoodName, SupplierName, ItemConsigner, BestBefore, CountItem, SumItem, PriceItem);
//                //}

//            }
            
//        }
        #endregion

        private void dgvPriceList_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
           //IWantBuyThisGood();

            //int RowIndex = dgvPriceList.SelectedRows[0].Index;
            //if (dgvPriceList.Rows[RowIndex].Cells[4].Value != string.Empty)
            //{

            //    Font customFont = new Font("Segoe UI", 13, FontStyle.Bold);

            //    dgvPriceList.Rows[RowIndex].DefaultCellStyle.Font = customFont;
            //}

        }


        private void btnClearSearchInPriceList_Click(object sender, EventArgs e)
        {
            txtSearchGoodNameInPriceList.Text = string.Empty;
            GoodsFilter = string.Empty;
            ApplyPriceListFilters();
            //loadPriceList(string.Empty);
        }


        private void btnEraseOrder_Click(object sender, EventArgs e)
        {
            //DialogResult drAreYouSeriesAboutEraseOrder = MessageBox.Show("Вы уверены, что хотите очистить корзину?", "Сообщение", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            //if (drAreYouSeriesAboutEraseOrder == DialogResult.Yes)
            //{
            //    EraseOrder();
            //}

        }

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

            string qUpdatePriceListBuyingItems = $@"
update PriceList set 
[CountIWantBuy] = null,
[SumIWantBuy] = null
from (select GoodCode, GoodName, SupplierName, SupplierPrice from TempOrderItems) as tempOrder
where
tempOrder.GoodCode = PriceList.GoodCode
and tempOrder.GoodName = PriceList.GoodName
";
            string qEraseOrder = "delete from TempOrderItems";

            using (SQLiteConnection conEraseOrder = new SQLiteConnection(connectionStringToLocalDB))
            {
                try
                {
                    conEraseOrder.Open();
                    SQLiteCommand cmdUpdateBuyingItems = new SQLiteCommand(qUpdatePriceListBuyingItems, conEraseOrder);
                    SQLiteCommand cmdEraseOrder = new SQLiteCommand(qEraseOrder, conEraseOrder);
                    cmdUpdateBuyingItems.ExecuteNonQuery();
                    cmdEraseOrder.ExecuteNonQuery();
                    loadTempOrderItems();
                    //loadPriceList(string.Empty);
                }
                catch (Exception ex)
                {
                    ToastNotification.ShowError($"Ошибка очистки корзины: {ex.Message}");
                }
                finally
                {
                    conEraseOrder.Close();
                }
            }
        }

        string SumIWantBuy = string.Empty;
        int lastSelectedRowIndex;
        string GoodsFilter = string.Empty;
        string stringIWantBuy = string.Empty;


        private void dgvPriceList_KeyPress(object sender, KeyPressEventArgs e)
        {
            int RowIndex = dgvPriceList.SelectedRows[0].Index;

            string idPriceListItem = dgvPriceList.Rows[RowIndex].Cells[11].Value.ToString();

            if (timerForResetSearch.Enabled == false)
            {
                deleteGood(RowIndex, idPriceListItem);
                timerForResetSearch.Enabled = true;
                timerForResetSearch.Start();
            }

            if ((e.KeyChar >= 'A' && e.KeyChar <= 'Z') || (e.KeyChar >= 'a' && e.KeyChar <= 'z') || (e.KeyChar >= 'А' && e.KeyChar <= 'Я') || (e.KeyChar >= 'а' && e.KeyChar <= 'я') || (e.KeyChar == (Char)Keys.Subtract))
            {
                if (e.KeyChar == (Char)Keys.Enter)
                {

                }
                else
                {
                    dgvPriceList.ClearSelection();
                    GoodsFilter += e.KeyChar.ToString();
                    txtSearchGoodNameInPriceList.Text = GoodsFilter;

                    #region поиск без фильтрации (НЕ РАБОТАЕТ)
                    //foreach(DataGridViewRow row in dgvPriceList.Rows)
                    //{
                    //    //string cellValue = row.Cells["Наименование"].Value.ToString().ToLower();
                    //    if (row.Cells[2].Value.ToString().Equals(GoodsFilter))
                    //    {
                    //        int indexOfSearchValue = row.Index;
                    //        dgvPriceList.Rows[indexOfSearchValue].Selected = true;
                    //    }
                    //}
                    #endregion

                    #region старый способ поиска с фильтрацией данных
                    if (!string.IsNullOrEmpty(GoodsFilter))
                    {
                        ApplyPriceListFilters();
                        if (dgvPriceList.Rows.Count == 0)
                        {
                            UiDialogs.ShowInfo("Подходящий товар не найден.", "Поиск", FindForm());
                            GoodsFilter = string.Empty;

                            txtSearchGoodNameInPriceList.Text = string.Empty;
                            ApplyPriceListFilters();
                        }
                    }
                    #endregion
                }
            }
            else if ((e.KeyChar >= (Char)Keys.D1 && e.KeyChar <= (Char)Keys.D9) ||
               (e.KeyChar >= (Char)Keys.NumPad1 && e.KeyChar <= (Char)Keys.NumPad9) || (e.KeyChar == (Char)Keys.D0 && dgvPriceList.Rows[RowIndex].Cells[10].Value.ToString().Length > 1) || (e.KeyChar == (Char)Keys.NumPad0 && dgvPriceList.Rows[RowIndex].Cells[10].Value.ToString().Length > 1))
            {
                
                    int QuantityForSale = Convert.ToInt32(dgvPriceList.Rows[RowIndex].Cells[6].Value.ToString());

                    stringIWantBuy = dgvPriceList.Rows[RowIndex].Cells[9].Value.ToString() + e.KeyChar.ToString();
                    int IWantBuy = Convert.ToInt32(stringIWantBuy);

                    if (IWantBuy <= QuantityForSale)
                    {
                        dgvPriceList.Rows[RowIndex].Cells[9].Value = IWantBuy.ToString();

                        decimal PriceForOne = Convert.ToDecimal(dgvPriceList.Rows[RowIndex].Cells[5].Value.ToString());
                        decimal sumOrder = IWantBuy * PriceForOne;
                        dgvPriceList.Rows[RowIndex].Cells[10].Value = sumOrder.ToString();
                    }
                    else if (IWantBuy > QuantityForSale)
                    {
                        DialogResult drIWantBuyAll = UiDialogs.ConfirmYesNoCancel($"Для заказа доступно только {QuantityForSale.ToString()}. Заказать доступное количество?", "Заказ", FindForm());

                        if (drIWantBuyAll == DialogResult.Yes)
                        {
                            dgvPriceList.Rows[RowIndex].Cells[9].Value = QuantityForSale.ToString();

                            decimal PriceForOne = Convert.ToDecimal(dgvPriceList.Rows[RowIndex].Cells[5].Value.ToString());
                            decimal sumOrder = QuantityForSale * PriceForOne;
                            dgvPriceList.Rows[RowIndex].Cells[10].Value = sumOrder.ToString();
                        }
                    }
            }
            else if (e.KeyChar == (Char)Keys.Escape)
            {
                txtSearchGoodNameInPriceList.Text = string.Empty;
                GoodsFilter = string.Empty;
                ApplyPriceListFilters();
            }
            else if (e.KeyChar == (Char)Keys.Back)
            {

                string countToBuy = dgvPriceList.Rows[RowIndex].Cells[9].Value.ToString();
                if (countToBuy.Length > 1)
                {
                    string result = countToBuy.Remove(countToBuy.Length - 1);

                    dgvPriceList.Rows[RowIndex].Cells[9].Value = result;

                    decimal PriceForOne = Convert.ToDecimal(dgvPriceList.Rows[RowIndex].Cells[5].Value.ToString());
                    decimal sumOrder = Convert.ToDecimal(result) * PriceForOne;
                    dgvPriceList.Rows[RowIndex].Cells[10].Value = sumOrder.ToString();
                }
            }
            else if (e.KeyChar == (Char)Keys.Delete)
            {
                deleteGood(RowIndex, idPriceListItem);
            }
            else if (dgvPriceList.Rows[RowIndex].Cells[9].Value.ToString() == string.Empty  && e.KeyChar == (Char)Keys.D0)
            {
                
            }
            else if (e.KeyChar == (Char)Keys.Down || e.KeyChar == (Char)Keys.Up)
            {
                timerForResetSearch.Enabled = false;
                timerForResetSearch.Stop();

                foreach (DataGridViewRow row in dgvPriceList.Rows)
                {
                    if (Convert.ToInt32(row.Cells[9].Value) == 0)
                    {
                        int rowIndex = row.Index;
                        deleteGood(rowIndex, idPriceListItem);
                    }
                }
            }

            string summaZakaza = dgvPriceList.Rows[RowIndex].Cells[10].Value.ToString();


            if (summaZakaza.Trim().Length > 0)
            {
                string Zakaz = dgvPriceList.Rows[RowIndex].Cells[9].Value.ToString();

                creatingTempOrder(idPriceListItem, Zakaz, summaZakaza);

            }

            #region старое добавление товара в PLI
            //tabOrderItems.

            //dgvPriceList.EndEdit();
            //bsPriceList.EndEdit();

            //daPriceListMain.Update(dsPriceList);

            ////dsPriceList.Tables.Clear();
            //dsPriceList.WriteXml("PriceList.xml", XmlWriteMode.DiffGram);
            //dsPriceList.Tables.Add(tablePriceList.Copy());

            //dsPriceList.Tables["PriceList"].AcceptChanges();

            //tablePriceList = (dgvPriceList.DataSource as DataTable);



            //daPriceListMain.Update();
            //bsPriceList.DataSource = (dgvPriceList.DataSource as DataTable);
            //daPriceListMain.Update(dsPriceList);
            #endregion
        }

        void creatingTempOrder(string idPriceListItem, string zakaz, string summaZakaza)
        {
            string qUpdatePriceList = $"update [PriceList] set [Zakaz] = '{zakaz}', [SummaZakaza] = '{summaZakaza}' where [id_PriceList_Item] = '{idPriceListItem}'";
            string qDeleteFromTempOrder = $"delete from [TempOrderItems] where [id_PriceList_Item] = '{idPriceListItem}'";
            string qCreateNewTempOrder = $"insert into TempOrderItems([guid_es],[es_code],[supplier_id],[DrugName],[SupplierName],[Price],[Quantity],[ExpiryPeriod],[Description],[Zakaz],[SummaZakaza],[id_PriceList_Item],[supplier_price_id]) select [guid_es],[es_code],[supplier_id],[DrugName],[SupplierName],[Price],[Quantity],[ExpiryPeriod],[Description],[Zakaz],[SummaZakaza],[id_PriceList_Item],[supplier_price_id] from [PriceList] where [id_PriceList_Item] = '{idPriceListItem}'";

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

                    SQLiteCommand cmdUpdatePriceList = new SQLiteCommand(qUpdatePriceList, sqlCon);
                    SQLiteCommand cmdDeleteFromTempOrder = new SQLiteCommand(qDeleteFromTempOrder, sqlCon);
                    SQLiteCommand cmdCreateNewTempOrder = new SQLiteCommand(qCreateNewTempOrder, sqlCon);

                    cmdUpdatePriceList.ExecuteNonQuery();
                    cmdDeleteFromTempOrder.ExecuteNonQuery();
                    cmdCreateNewTempOrder.ExecuteNonQuery();

                    loadTempOrderItems();
                    
                }
                catch(Exception ex)
                {
                    //MessageBox.Show($"Возникла ошибка при обновлении данных прайс-листов. Текст ошибки:\n{ex.ToString()}", "Обработка прайс-листов", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    sqlCon.Close();
                }
            }

        }
        

        void deleteGood(int index, string IdPriceListItem)
        {
            dgvPriceList.Rows[index].Cells[9].Value = string.Empty;
            dgvPriceList.Rows[index].Cells[10].Value = string.Empty;

            string IdPLI = IdPriceListItem;

            string qClearPriceList = $"update [PriceList] set [Zakaz] = null, [SummaZakaza] = null where id_PriceList_Item = '{IdPLI}'";
            string qDeleteFromTempOrder = $"delete from [TempOrderItems] where [id_PriceList_Item] = '{IdPLI}'";

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

                    SQLiteCommand cmdClearPriceListItem = new SQLiteCommand(qClearPriceList, sqlCon);
                    SQLiteCommand cmdDeleteFromTempOrder = new SQLiteCommand(qDeleteFromTempOrder, sqlCon);

                    cmdClearPriceListItem.ExecuteNonQuery();
                    cmdDeleteFromTempOrder.ExecuteNonQuery();

                    loadTempOrderItems();
                }
                catch(Exception ex)
                {
                    //MessageBox.Show($"При обновлении данных прайс-листа возникла ошибка. Текст ошибки:\n{ex.ToString()}", "Обработка прайс-листов", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    sqlCon.Close();
                }
            }
        }

        #region TODO: старый метод, не работает
        //private void dgvPriceList_KeyPress(object sender, KeyPressEventArgs e)
        //{

        //    if ((e.KeyChar >= 'A' && e.KeyChar <= 'Z') || (e.KeyChar >= 'a' && e.KeyChar <= 'z') || (e.KeyChar >= 'А' && e.KeyChar <= 'Я') || (e.KeyChar >= 'а' && e.KeyChar <= 'я') || (e.KeyChar == (Char)Keys.Subtract))
        //    {
        //        if (e.KeyChar == (Char)Keys.Enter || e.KeyChar == (Char)Keys.Tab)
        //        {

        //        }
        //        else
        //        {
        //            timerForResetSearch.Enabled = false;
        //            timerForResetSearch.Stop();
        //            txtSearchGoodNameInPriceList.Text += e.KeyChar.ToString();



        //            string GoodNameFilter = txtSearchGoodNameInPriceList.Text;
        //            //GoodNameFilter = GoodNameFilter.Replace(" ", "%");
        //            //GoodNameFilter = GoodNameFilter.Replace("   ", "%");
        //            //string filterAddon = $" and pl.[GoodName] LIKE '%{GoodNameFilter.ToLower()}%'";
        //            //MessageBox.Show(GoodNameFilter);
        //            (dgvPriceList.DataSource as DataTable).DefaultView.RowFilter = $"[Наименование] like '%{GoodNameFilter.ToLower()}%'";

        //            timerForResetSearch.Enabled = true;
        //            timerForResetSearch.Start();

        //            if (dgvPriceList.RowCount < 1)
        //            {
        //                MessageBox.Show($"Подходящий товар не найден.", "Поиск", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        //                txtSearchGoodNameInPriceList.Text = string.Empty;
        //                //loadPriceList(string.Empty);

        //                (dgvPriceList.DataSource as DataTable).DefaultView.RowFilter = string.Empty;
        //                timerForResetSearch.Stop();
        //            }


        //        }

        //    }
        //    else if ((e.KeyChar >= (Char)Keys.D0 && e.KeyChar <= (Char)Keys.D9) ||
        //        (e.KeyChar >= (Char)Keys.NumPad0 && e.KeyChar <= (Char)Keys.NumPad9))
        //    {
        //        txtSearchGoodNameInPriceList.Text = string.Empty;
        //        int selectedRowIndex = dgvPriceList.SelectedCells[0].RowIndex;
        //        if (selectedRowIndex != lastSelectedRowIndex)
        //        {
        //            SumIWantBuy = string.Empty;
        //        }
        //        SumIWantBuy += e.KeyChar.ToString();
        //        if (SumIWantBuy == "0")
        //        {
        //            ErasePriceListOrderItem();
        //        }
        //        else
        //        {
        //            int AvaibleCountGood = Convert.ToInt32(dgvPriceList.Rows[selectedRowIndex].Cells[6].Value.ToString());


        //            if (AvaibleCountGood < Convert.ToInt32(SumIWantBuy))
        //            {
        //                MessageBox.Show("Заказано максимальное количество товара", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        //                SumIWantBuy = AvaibleCountGood.ToString();
        //            }
        //            dgvPriceList.Rows[selectedRowIndex].Cells[8].Value = SumIWantBuy;
        //            //IWantBuyThisGood();
        //            lastSelectedRowIndex = selectedRowIndex;
        //        }
        //    }
        //    else if (e.KeyChar == (Char)Keys.Back || e.KeyChar == (Char)Keys.Escape)
        //    {
        //        txtSearchGoodNameInPriceList.Text = string.Empty;
        //        (dgvPriceList.DataSource as DataTable).DefaultView.RowFilter = string.Empty;
        //        //loadPriceList(string.Empty);
        //    }
        //    else if (e.KeyChar == (Char)Keys.Delete)
        //    {
        //        ErasePriceListOrderItem();
        //    }
        //    else if (e.KeyChar != (Char)Keys.Enter)
        //    {
        //        txtSearchGoodNameInPriceList.Text += e.KeyChar.ToString();

        //        string GoodNameFilter = txtSearchGoodNameInPriceList.Text;
        //        //GoodNameFilter = GoodNameFilter.Replace(" ", "%");
        //        //string filterAddon = $" and pl.[GoodName] LIKE '%{GoodNameFilter.ToLower()}%'";

        //        (dgvPriceList.DataSource as DataTable).DefaultView.RowFilter = $"[Наименование] like '%{GoodNameFilter.ToLower()}%'";

        //        if (dgvPriceList.RowCount < 1)
        //        {
        //            MessageBox.Show($"Подходящий товар не найден.", "Поиск", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        //            txtSearchGoodNameInPriceList.Text = string.Empty;
        //            (dgvPriceList.DataSource as DataTable).DefaultView.RowFilter = string.Empty;
        //            //loadPriceList(string.Empty);
        //        }
        //    }
        //}
        #endregion

        void ErasePriceListOrderItem()
        {
            int rowIndex = dgvPriceList.SelectedCells[0].RowIndex;

            string goodCode = dgvPriceList.Rows[rowIndex].Cells[0].Value.ToString();
            string goodName = dgvPriceList.Rows[rowIndex].Cells[1].Value.ToString();
            string SupplierName = dgvPriceList.Rows[rowIndex].Cells[3].Value.ToString();
            string PriceGood = dgvPriceList.Rows[rowIndex].Cells[7].Value.ToString();
            string SumOrder = dgvPriceList.Rows[rowIndex].Cells[9].Value.ToString();

            string qUpdatePriceList = $@"update PriceList set 
[CountIWantBuy] = null,
[SumIWantBuy] = null
where [GoodCode] = '{goodCode}'
and [GoodName] = '{goodName}'
and [SupplierName] = '{SupplierName}'";


            string qDeleteFromTempOrder = $@"delete from TempOrderItems
where [GoodCode] = '{goodCode}'
and [GoodName] = '{goodName}'
and [SupplierName] = '{SupplierName}'
and [SupplierPrice] = '{PriceGood}'
and SumOrderedItems = '{SumOrder}'";

            string connectionStringToLocalDB = AppConfig.SqliteConnectionString;
            using (SQLiteConnection conEraceOrderOfSelectedGood = new SQLiteConnection(connectionStringToLocalDB))
            {
                try
                {
                    conEraceOrderOfSelectedGood.Open();

                    SQLiteCommand cmdEraseOrderedGoodFromPriceList = new SQLiteCommand(qUpdatePriceList, conEraceOrderOfSelectedGood);
                    SQLiteCommand cmdDeleteOrderedGoodFromTempOrder = new SQLiteCommand(qDeleteFromTempOrder, conEraceOrderOfSelectedGood);

                    cmdEraseOrderedGoodFromPriceList.ExecuteNonQuery();
                    cmdDeleteOrderedGoodFromTempOrder.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    ToastNotification.ShowError($"Ошибка удаления из заказа: {ex.Message}");
                }
                finally
                {
                    conEraceOrderOfSelectedGood.Close();
                    //loadPriceList(string.Empty);
                    loadTempOrderItems();
                }
            }
        }

        void ShowMePriceWithMarkupPercentForSelectedGood()
        {
            if(dgvPriceList.RowCount > 0)
            {
                lblSelectedGoodName.Text = dgvPriceList.CurrentRow.Cells[3].Value.ToString();


                double priceForGood = Convert.ToDouble(dgvPriceList.CurrentRow.Cells[5].Value.ToString());
                double MarkupPercentage = Convert.ToDouble(numericPercent.Value);

                double priceWithPercentage = priceForGood + (priceForGood / 100 * MarkupPercentage);
                lblPriceForGood.Text = $"= {priceWithPercentage.ToString()} руб";
            }
        }

        private void dgvPriceList_SelectionChanged(object sender, EventArgs e)
        {
            SumIWantBuy = string.Empty;

            if (timerForResetSearch.Enabled == true)
            {
                timerForResetSearch.Enabled = false;
                timerForResetSearch.Stop();
            }

            ShowMePriceWithMarkupPercentForSelectedGood();
        }

        

        private void btnImport_Click(object sender, EventArgs e)
        {
            #region импорт из FTP
            string fileName = "0027379.dbf";
            string filePath = @"ftp:\\lboefc91:Oop3OoF4@lbo.protek.ru\session\Rostov_na_Donu\TestFTPFile\";
            string connectionToDbf = $"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={filePath};Extended Properties=dBASE IV;User ID=Admin;Password=;";

            using (OleDbConnection oleCon = new OleDbConnection(connectionToDbf))
            {
                var sql = $"select '{DateTime.Now.ToShortDateString()}' as [DatePriceList], '1' as [ConsigneesCode], '2' as [SupplierCode], CODE, PRODUCT, PRODUCER, 'Поставщик 2' as [SupplierName], EXP, VTIMPORT, REGCOST, QUANTITY, COST, COUNTRY, NDS, PRODCOST, '0' as [Marked] from {fileName}";
                OleDbCommand cmd = new OleDbCommand(sql, oleCon);
                oleCon.Open();
                OleDbDataAdapter daDbfReader = new OleDbDataAdapter(cmd);
                DataTable tablePriceFromDbf = new DataTable();
                daDbfReader.Fill(tablePriceFromDbf);


                string connectionStringToLocalDB = AppConfig.SqliteConnectionString;
                using (SQLiteConnection conFillPriceListByNewData = new SQLiteConnection(connectionStringToLocalDB))
                {
                    try
                    {
                        conFillPriceListByNewData.Open();

                        foreach (DataRow dr in tablePriceFromDbf.Rows)
                        {
                            string dbfPriceListDate = dr["DatePriceList"].ToString();
                            string dbfConsigneesCode = dr["ConsigneesCode"].ToString();
                            string dbfCode = dr["CODE"].ToString();
                            string dbfGood = dr["PRODUCT"].ToString().ToLower();
                            string dbfProducer = dr["PRODUCER"].ToString();
                            string dbfSupplierCode = dr["SupplierCode"].ToString();
                            string dbfBestBefore = Convert.ToDateTime(dr["EXP"]).ToShortDateString();
                            string dbfJNVLS = dr["VTIMPORT"].ToString();
                            string dbfPriceReestr = dr["REGCOST"].ToString();
                            string dbfQuantity = dr["QUANTITY"].ToString();
                            string dbfPriceSupplierWithNds = dr["COST"].ToString();
                            string dbfCountry = dr["COUNTRY"].ToString();
                            string dbfNDS = dr["NDS"].ToString();
                            string dbfPriceProducer = dr["PRODCOST"].ToString();
                            string dbfMarked = dr["Marked"].ToString();

                            dbfGood = dbfGood.Replace("'", "");
                            dbfProducer = dbfProducer.Replace("'", "");
                            //dbfSupplierName = dbfSupplierName.Replace("'", "");
                            dbfCountry = dbfCountry.Replace("'", "");

                            string qShowMeLastDateOfPriceList = $"select PriceListDate from PriceListFromSuppliers where ConsigneesCode = '{dbfConsigneesCode}' and CodeSuppliers = '{dbfSupplierCode}'";
                            SQLiteCommand cmdShowMeLastPriceListDate = new SQLiteCommand(qShowMeLastDateOfPriceList, conFillPriceListByNewData);

                            DateTime dateLastPriceListDate = Convert.ToDateTime(cmdShowMeLastPriceListDate.ExecuteScalar().ToString());
                            MessageBox.Show($"{dbfPriceListDate} \n{dateLastPriceListDate}");

                            if (Convert.ToDateTime(dbfPriceListDate) > dateLastPriceListDate)
                            {

                            }

                            string qInsertDataInLocalDB = $@"insert into PriceList (PriceListDate, GoodCode, GoodName, ProducerName, SupplierName, BestBefore, JNVLS, PriceReestr, AvaibleCount, PriceSupplierWithNDS, NDS , Marked)
                                    values ('{dbfPriceListDate}','{dbfCode}','{dbfGood}','{dbfProducer}', '3','{dbfBestBefore}','{dbfJNVLS}','{dbfPriceReestr}', '{dbfQuantity}', '{dbfPriceSupplierWithNds}', '{dbfCountry}', '{dbfNDS}', '{dbfPriceProducer}', '{dbfMarked}')
                                    ";
                            MessageBox.Show(qInsertDataInLocalDB);

                            SQLiteCommand cmdInsertDataInPriceList = new SQLiteCommand(qInsertDataInLocalDB, conFillPriceListByNewData);
                            cmdInsertDataInPriceList.ExecuteNonQuery();
                        }
                    }
                    catch { }
                }
            }

            #endregion


            #region старыйИмпорт из локального файла
            //string fileName = "0027379.dbf";
            //string filePath = @"C:\!ElectroPharmacy\ElectoPharmacyOrder\";
            //string connectionToDbf = $"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={filePath};Extended Properties=dBASE IV;User ID=Admin;Password=;";

            //using (OleDbConnection oleCon = new OleDbConnection(connectionToDbf))
            //{
            //    var sql = $"select '{DateTime.Now.ToShortDateString()}' as [DatePriceList], '1' as [ConsigneesCode], '2' as [SupplierCode], CODE, PRODUCT, PRODUCER, 'Поставщик 2' as [SupplierName], EXP, VTIMPORT, REGCOST, QUANTITY, COST, COUNTRY, NDS, PRODCOST, '0' as [Marked] from {fileName}";
            //    OleDbCommand cmd = new OleDbCommand(sql, oleCon);
            //    oleCon.Open();
            //    OleDbDataAdapter daDbfReader = new OleDbDataAdapter(cmd);
            //    DataTable tablePriceFromDbf = new DataTable();
            //    daDbfReader.Fill(tablePriceFromDbf);


            //    string connectionStringToLocalDB = AppConfig.SqliteConnectionString;
            //    using (SQLiteConnection conFillPriceListByNewData = new SQLiteConnection(connectionStringToLocalDB))
            //    {
            //        try
            //        {
            //            conFillPriceListByNewData.Open();

            //            foreach (DataRow dr in tablePriceFromDbf.Rows)
            //            {
            //                string dbfPriceListDate = dr["DatePriceList"].ToString();
            //                string dbfConsigneesCode = dr["ConsigneesCode"].ToString();
            //                string dbfCode = dr["CODE"].ToString();
            //                string dbfGood = dr["PRODUCT"].ToString().ToLower();
            //                string dbfProducer = dr["PRODUCER"].ToString();
            //                string dbfSupplierCode = dr["SupplierCode"].ToString();
            //                string dbfBestBefore = Convert.ToDateTime(dr["EXP"]).ToShortDateString();
            //                string dbfJNVLS = dr["VTIMPORT"].ToString();
            //                string dbfPriceReestr = dr["REGCOST"].ToString();
            //                string dbfQuantity = dr["QUANTITY"].ToString();
            //                string dbfPriceSupplierWithNds = dr["COST"].ToString();
            //                string dbfCountry = dr["COUNTRY"].ToString();
            //                string dbfNDS = dr["NDS"].ToString();
            //                string dbfPriceProducer = dr["PRODCOST"].ToString();
            //                string dbfMarked = dr["Marked"].ToString();

            //                dbfGood = dbfGood.Replace("'", "");
            //                dbfProducer = dbfProducer.Replace("'", "");
            //                //dbfSupplierName = dbfSupplierName.Replace("'", "");
            //                dbfCountry = dbfCountry.Replace("'", "");

            //                string qShowMeLastDateOfPriceList = $"select PriceListDate from PriceListFromSuppliers where ConsigneesCode = '{dbfConsigneesCode}' and CodeSuppliers = '{dbfSupplierCode}'";
            //                SQLiteCommand cmdShowMeLastPriceListDate = new SQLiteCommand(qShowMeLastDateOfPriceList, conFillPriceListByNewData);

            //                DateTime dateLastPriceListDate = Convert.ToDateTime(cmdShowMeLastPriceListDate.ExecuteScalar().ToString());
            //                MessageBox.Show($"{dbfPriceListDate} \n{dateLastPriceListDate}");

            //                if (Convert.ToDateTime(dbfPriceListDate) > dateLastPriceListDate)
            //                {

            //                }

            //                string qInsertDataInLocalDB = $@"insert into PriceList (PriceListDate, GoodCode, GoodName, ProducerName, SupplierName, BestBefore, JNVLS, PriceReestr, AvaibleCount, PriceSupplierWithNDS, NDS , Marked)
            //                values ('{dbfPriceListDate}','{dbfCode}','{dbfGood}','{dbfProducer}', '{dbfSupplierCode}','{dbfBestBefore}','{dbfJNVLS}','{dbfPriceReestr}', '{dbfQuantity}', '{dbfPriceSupplierWithNds}', '{dbfCountry}', '{dbfNDS}', '{dbfPriceProducer}', '{dbfMarked}')
            //                ";
            //                //MessageBox.Show(qInsertDataInLocalDB);

            //                SQLiteCommand cmdInsertDataInPriceList = new SQLiteCommand(qInsertDataInLocalDB, conFillPriceListByNewData);
            //                cmdInsertDataInPriceList.ExecuteNonQuery();
            //            }
            //        }
            //        catch(Exception ex)
            //        {
            //            MessageBox.Show(ex.ToString());
            //        }
            //        finally
            //        {
            //            conFillPriceListByNewData.Close();
            //            loadPriceList(string.Empty);
            //        }
            //    }
            //}
            #endregion
        }

        private void dgvPriceList_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
        {
            if (e.RowIndex == this.dgvPriceList.RowCount - 1) return;

        }

        private void txtSearchGoodNameInPriceList_Enter(object sender, EventArgs e)
        {
            dgvPriceList.Focus();
        }

        private void numericPercent_ValueChanged(object sender, EventArgs e)
        {
            if (numericPercent.Value != _percentageAsDefault)
            {
                checkUsePercentageAsDefault.Checked = false;
            }

            ShowMePriceWithMarkupPercentForSelectedGood();
        }

        private void UCPriceList_Paint(object sender, PaintEventArgs e)
        {
            if (comboSupplierFilter.DroppedDown)
            {
                return;
            }

            dgvPriceList.Focus();
        }

        private void btnImport_MouseEnter(object sender, EventArgs e)
        {
            //btnImport.Focus();
        }

        private void btnImport_MouseLeave(object sender, EventArgs e)
        {
            //dgvPriceList.Focus()
        }

        private void checkUsePercentageAsDefault_CheckedChanged(object sender, EventArgs e)
        {
            int newDefaultPercent;
            if (_percentageAsDefault != numericPercent.Value && checkUsePercentageAsDefault.Checked == true)
            {
                newDefaultPercent = Convert.ToInt32(numericPercent.Value);
                Properties.Settings.Default.IntDefaultPercentMarkup = Convert.ToInt32(newDefaultPercent);
                Properties.Settings.Default.Save();
            }          
        }

        private void timerForResetSearch_Tick(object sender, EventArgs e)
        {
            txtSearchGoodNameInPriceList.Text = string.Empty;
            timerForResetSearch.Enabled = false;
            timerForResetSearch.Stop();
        }

        private void btnDeleteGood_Click(object sender, EventArgs e)
        {
            int RowIndex = dgvPriceList.SelectedRows[0].Index;
            string idPriceListItem = dgvPriceList.Rows[RowIndex].Cells[11].Value.ToString();
            deleteGood(RowIndex, idPriceListItem);
        }


        private void btnMoreInfoAboutGood_Click(object sender, EventArgs e)
        {
            if (dgvPriceList.CurrentRow == null)
            {
                return;
            }

            var goodName = dgvPriceList.CurrentRow.Cells["Наименование"]?.Value?.ToString()
                ?? dgvPriceList.CurrentRow.Cells[2]?.Value?.ToString()
                ?? string.Empty;
            var description = dgvPriceList.CurrentRow.Cells["Описание"]?.Value?.ToString()
                ?? dgvPriceList.CurrentRow.Cells[8]?.Value?.ToString()
                ?? string.Empty;

            var aboutGood = new HelpForms.HF_AboutGood
            {
                goodName = goodName,
                goodDescription = description
            };
            UiThemeHelper.ApplyToControlTree(aboutGood);
            aboutGood.ShowDialog(FindForm());
        }




        //private void dgvPriceList_Paint(object sender, PaintEventArgs e)
        //{
        //    //foreach (DataGridViewRow row in dgvPriceList.Rows)
        //    //{

        //    //    if (row.Cells[8].Value.ToString() != "")
        //    //    {

        //    //        row.DefaultCellStyle.Font = new Font("Segoe UI", 10, FontStyle.Bold);
        //    //    }
        //    //}

        //    //dgvPriceList.Focus();
        //}
    }
}
