using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Data.SQLite;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Elfisa.UI.Theming;
using Электронная_Фармация.Classes;
using Электронная_Фармация.Properties;
using Электронная_Фармация.Forms;
using Электронная_Фармация.HelpForms;
using Электронная_Фармация.UserControls;

namespace Электронная_Фармация
{
    public partial class ElectroPharmacy : Form
    {
        partial void InitializeModernShell();
        partial void FinalizeModernShell();
        partial void RefreshOpenPriceLists();

        partial void ShowShellLoading(string message);
        partial void HideShellLoading();

        public string ConsigneeName { get; private set; } = string.Empty;

        public ElectroPharmacy()
        {
            InitializeComponent();
            InitializeModernShell();
        }

        private void tsItemContractors_Click(object sender, EventArgs e)
        {
            var fContractors = new FContractors();
            UiThemeHelper.ApplyToControlTree(fContractors);
            fContractors.ShowDialog();
        }

        private void tsItemExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void ElectroPharmacy_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult drExitFromApplication = UiDialogs.ConfirmYesNo("Завершить работу программы?", "Предупреждение", this);
            if (drExitFromApplication == DialogResult.Yes)
            {
                e.Cancel = false;
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void ElectroPharmacy_Load(object sender, EventArgs e)
        {
            FinalizeModernShell();

            // Принудительное обновление: если на Gitea есть более новый Release — не пускаем в работу.
            // При недоступной сети не блокируем (офлайн-аптека должна открываться).
            try
            {
                var update = UpdateChecker.CheckForUpdate();
                if (update != null && update.UpdateRequired)
                {
                    using (var dlg = new HF_UpdateAvailable(update))
                    {
                        UiThemeHelper.ApplyToControlTree(dlg);
                        dlg.ShowDialog(this);
                    }

                    // Жёстко завершаем процесс, чтобы updater смог заменить exe.
                    Environment.Exit(0);
                    return;
                }
            }
            catch (Exception ex)
            {
                AppDebugLog.Info("App", $"Проверка обновлений пропущена: {ex.Message}");
            }

            FCheckDatabaseIntegrary fCheckDatabaseIntegrary = new FCheckDatabaseIntegrary();
            UiThemeHelper.ApplyToControlTree(fCheckDatabaseIntegrary);
            fCheckDatabaseIntegrary.ShowDialog();

            var hasToken = !string.IsNullOrWhiteSpace(Settings.Default.stringToken);

            // Окно выбора грузополучателя открываем только после авторизации.
            // Если аптек одна — не открываем окно вообще.
            int consigneeCount = 0;
            using (var con = new SQLiteConnection(AppConfig.SqliteConnectionString))
            {
                con.Open();
                using (var cmd = new SQLiteCommand("SELECT COUNT(*) FROM Consignees", con))
                {
                    consigneeCount = Convert.ToInt32(cmd.ExecuteScalar());
                }
            }

            if (hasToken && consigneeCount > 1)
            {
                var consigneeDialog = new HFConsignees { ParentForm = this };
                UiThemeHelper.ApplyToControlTree(consigneeDialog);
                consigneeDialog.ShowDialog();
            }

            if (string.IsNullOrWhiteSpace(ConsigneeName))
            {
                var defaultName = ConsigneeHelper.GetDefaultConsigneeName();
                if (!string.IsNullOrWhiteSpace(defaultName))
                {
                    ConsigneeName = defaultName;
                    ConsigneeHelper.SetActiveConsignee(defaultName);
                }
            }

            if (!HasDocumentTabs())
            {
                loadDefaultPriceList();
            }

            RefreshCurrentUserStatus();
        }

        void loadDefaultPriceList()
        {
            var consignee = !string.IsNullOrWhiteSpace(ConsigneeName)
                ? ConsigneeName
                : ConsigneeHelper.GetDefaultConsigneeName();
            if (string.IsNullOrWhiteSpace(consignee))
            {
                consignee = "Прайс-Лист";
            }
            else
            {
                ConsigneeName = consignee;
            }

            var title = consignee == "Прайс-Лист"
                ? "Прайс-лист"
                : $"Прайс-лист ({consignee})";

            // На смене аптеки не должно появляться много вкладок прайса.
            // Поэтому перед открытием закрываем все вкладки с navKey="price".
            ConsigneeHelper.SyncCartToPriceList(consignee);
            foreach (var tab in _documentTabStrip.Tabs.Where(t => t.NavKey == "price").ToList())
            {
                CloseDocumentTab(tab.Id);
            }

            var ucPriceList = new UCPriceList(consignee);
            OpenDocumentTab(title, "price", ucPriceList, allowDuplicate: false);
            ucPriceList.dgvPriceList.Focus();
            RefreshCurrentUserStatus();
        }

        #region загрузкаПрайсЛиста_старая версия
        //void loadDefaultPriceList()
        //{
        //    string defaultConsignee = string.Empty;
        //    string connectionStringToLocalDB = AppConfig.SqliteConnectionString;
        //    using (SQLiteConnection conShowMeDefaultPriceList = new SQLiteConnection(connectionStringToLocalDB))
        //    {
        //        string qShowMeDefaultPriceList = "select ConsigneesName as [Грузополучатель] from Consignees where ConsigneesUseAsDefault = '1'";

        //        try
        //        {
        //            conShowMeDefaultPriceList.Open();

        //            SQLiteCommand cmdShowMeDefaultPriceList = new SQLiteCommand(qShowMeDefaultPriceList, conShowMeDefaultPriceList);
        //            defaultConsignee = cmdShowMeDefaultPriceList.ExecuteScalar().ToString();

        //            string tabPageName = $"Прайс-лист ({defaultConsignee})";

        //            TabPage pagePriceList = new TabPage(tabPageName);
        //            UCPriceList UCPriceList = new UCPriceList(defaultConsignee);

        //            pagePriceList.SuspendLayout();
        //            pagePriceList.ResumeLayout();
        //            tabContent.TabPages.Add(pagePriceList);


        //            pagePriceList.Controls.Add(UCPriceList);

        //            UCPriceList.Dock = DockStyle.Fill;



        //            tabContent.SelectTab(pagePriceList);

        //            UCPriceList.dgvPriceList.Focus();
        //        }
        //        catch(Exception ex)
        //        {
        //            MessageBox.Show($"Возникла ошибка при загрузке прайс-листа по умолчанию. Текст ошибки:\n{ex.ToString()}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //        }
        //        finally
        //        {
        //            conShowMeDefaultPriceList.Close();
        //        }
        //    }


        //}
        #endregion

        private void tsConsignee_Click(object sender, EventArgs e)
        {
            var hasToken = !string.IsNullOrWhiteSpace(Settings.Default.stringToken);
            if (!hasToken)
            {
                UiDialogs.ShowInfo("Сначала выполните авторизацию, чтобы выбрать грузополучателя.", "Авторизация", this);
                return;
            }

            var fConsignees = new FConsignees();
            UiThemeHelper.ApplyToControlTree(fConsignees);
            var dr = fConsignees.ShowDialog(this);
            if (dr == DialogResult.OK &&
                !string.IsNullOrWhiteSpace(fConsignees.SelectedConsigneeNameAfterSave))
            {
                showMePriceList(fConsignees.SelectedConsigneeNameAfterSave);
            }
        }

        private void tsItemInvoices_Click(object sender, EventArgs e)
        {
            OpenInvoicesTab();
        }

        private void tsItemPriceList_Click(object sender, EventArgs e)
        {
            loadDefaultPriceList();


            //HFConsignees hfConsignees = new HFConsignees();
            //hfConsignees.ParentForm = this;
            //hfConsignees.ShowDialog();
        }

        

        public void showMePriceList(string consignee)
        {
            ConsigneeName = consignee ?? string.Empty;
            if (!string.IsNullOrWhiteSpace(ConsigneeName))
            {
                ConsigneeHelper.SetActiveConsignee(ConsigneeName);
            }

            // Перед открытием прайс-листа синхронизируем Zakaz/SummaZakaza с корзиной активной аптеки.
            ConsigneeHelper.SyncCartToPriceList(ConsigneeName);

            var ucPriceList = new UCPriceList(consignee);
            foreach (var tab in _documentTabStrip.Tabs.Where(t => t.NavKey == "price").ToList())
            {
                CloseDocumentTab(tab.Id);
            }

            OpenDocumentTab($"Прайс-лист ({consignee})", "price", ucPriceList, allowDuplicate: false);
            ucPriceList.dgvPriceList.Focus();
            RefreshCurrentUserStatus();
        }

        private void SwitchConsignee()
        {
            var hasToken = !string.IsNullOrWhiteSpace(Settings.Default.stringToken);
            if (!hasToken)
            {
                UiDialogs.ShowInfo("Сначала выполните авторизацию, чтобы сменить грузополучателя.", "Авторизация", this);
                return;
            }

            var consigneeDialog = new HFConsignees { ParentForm = this };
            UiThemeHelper.ApplyToControlTree(consigneeDialog);
            consigneeDialog.ShowDialog(this);
            RefreshCurrentUserStatus();
        }

        private void tsDebug_Click(object sender, EventArgs e)
        {
            var fDebug = new FDebug();
            UiThemeHelper.ApplyToControlTree(fDebug);
            fDebug.Show();
        }

        private void tsItemOrders_Click(object sender, EventArgs e)
        {
            OpenOrdersTab();
        }

        private void tsExchangeLoad_Click(object sender, EventArgs e)
        {
            string connectionStringToLocalDB = AppConfig.SqliteConnectionString;
            var consigneeSafe = (string.IsNullOrWhiteSpace(ConsigneeName) ? ConsigneeHelper.GetDefaultConsigneeName() : ConsigneeName)
                ?.Replace("'", "''");
            string qShowMeCoountDataFromTempOrder = $"select count(*) from TempOrderItems where ConsigneeName = '{consigneeSafe}'";
            int countDataTempOrder = 0;

            using (SQLiteConnection sqlCon = new SQLiteConnection(connectionStringToLocalDB))
            {
                try
                {
                    sqlCon.Open();
                    SQLiteCommand cmdCountOfDataTempOrder = new SQLiteCommand(qShowMeCoountDataFromTempOrder, sqlCon);
                    countDataTempOrder = Convert.ToInt32(cmdCountOfDataTempOrder.ExecuteScalar());
                }
                catch (Exception ex)
                {
                    UiDialogs.ShowError($"При получении данных из локальных базы данных произошла ошибка. Возможно БД повреждена. Текст ошибки:{ex.ToString()}", "Не удалось получить данные", this);
                }
                finally
                {
                    sqlCon.Close();
                }
            }

            ClearDocumentTabs();

            HF_DownloadDataFromServer hF_DownloadDataFromServer = new HF_DownloadDataFromServer();
            hF_DownloadDataFromServer.ActiveConsigneeName =
                string.IsNullOrWhiteSpace(ConsigneeName) ? ConsigneeHelper.GetDefaultConsigneeName() : ConsigneeName;
            UiThemeHelper.ApplyToControlTree(hF_DownloadDataFromServer);
            DialogResult downloadResult = DialogResult.Cancel;
            if (countDataTempOrder > 0)
            {
                DialogResult drShowDataDownload = UiDialogs.ConfirmYesNoCancel("В корзине найдены товары. При обновлении прайса она будет очищена.\nПродолжить?", "ТОВАРЫ В КОРЗИНЕ", this);
                if(drShowDataDownload == DialogResult.Yes)
                {
                    downloadResult = hF_DownloadDataFromServer.ShowDialog();
                }
            }
            else
            {
                downloadResult = hF_DownloadDataFromServer.ShowDialog();
            }

            if (downloadResult == DialogResult.OK)
            {
                RefreshOpenPriceLists();
            }
            else if (!HasDocumentTabs())
            {
                loadDefaultPriceList();
            }
        }

            #region старая кнопка загрузки данных
            /*
        private void tsExchangeLoad_Click(object sender, EventArgs e)
        {

            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], '2' as [ConsigneesCode], '3' 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 qDbfPriceListDate = $"select '{DateTime.Now.ToString()}' as [DatePriceList] from {fileName}";
                string qDbfConsigneesCode = $"select '2' as [ConsigneesCode] from {fileName}";
                string qDbfSupplierCode = $"select '3' as [CodeSuppliers] from {fileName}";

                OleDbCommand cmdPriceListDate = new OleDbCommand(qDbfPriceListDate, oleCon);
                OleDbCommand cmdConsigneesCode = new OleDbCommand(qDbfConsigneesCode, oleCon);
                OleDbCommand cmdSupplierCode = new OleDbCommand(qDbfSupplierCode, oleCon);

                string dbfPriceListDate = cmdPriceListDate.ExecuteScalar().ToString();
                string dbfConsigneesCode = cmdConsigneesCode.ExecuteScalar().ToString();
                string dbfSupplierCode = cmdSupplierCode.ExecuteScalar().ToString();


                string dbPriceListDate = string.Empty;

                string connectionStringToLocalDB = AppConfig.SqliteConnectionString;
                using (SQLiteConnection conShowMePriceListDateFromPriceListSuppliers = new SQLiteConnection(connectionStringToLocalDB))
                {
                    string qShowMeLastDateOfPriceList = $"select PriceListDate from PriceListFromSuppliers where ConsigneesCode = '{dbfConsigneesCode}' and CodeSuppliers = '{dbfSupplierCode}'";
                    

                    string qShowMeCountOfPriceListForThisConsigneeFromThisSupplier = $"select Count(PriceListDate) from PriceListFromSuppliers where ConsigneesCode = '{dbfConsigneesCode}' and CodeSuppliers = '{dbfSupplierCode}'";
                    try
                    {
                        conShowMePriceListDateFromPriceListSuppliers.Open();

                        SQLiteCommand cmdShowMeCountPriceListFromThisSupplierForThisConsignee = new SQLiteCommand(qShowMeCountOfPriceListForThisConsigneeFromThisSupplier, conShowMePriceListDateFromPriceListSuppliers);

                        Int32 countPriceLists = Convert.ToInt32(cmdShowMeCountPriceListFromThisSupplierForThisConsignee.ExecuteScalar().ToString());

                        if (countPriceLists != 0)
                        {
                            SQLiteCommand cmdShowMeLastPriceListDate = new SQLiteCommand(qShowMeLastDateOfPriceList, conShowMePriceListDateFromPriceListSuppliers);
                            dbPriceListDate = cmdShowMeLastPriceListDate.ExecuteScalar().ToString();
                        }
                        else
                        {
                            string qCreateNewPriceList = $"insert into PriceListFromSuppliers (ConsigneesCode, CodeSuppliers, PriceListDate) values('{dbfConsigneesCode}', '{dbfSupplierCode}', (select strftime('%Y-%m-%d','{Convert.ToDateTime(dbfPriceListDate).ToString("yyyy-MM-dd")}')))";
                            SQLiteCommand cmdCreatePriceList = new SQLiteCommand(qCreateNewPriceList, conShowMePriceListDateFromPriceListSuppliers);
                            
                            cmdCreatePriceList.ExecuteNonQuery();


                            SQLiteCommand cmdShowMeLastPriceListDate = new SQLiteCommand(qShowMeLastDateOfPriceList, conShowMePriceListDateFromPriceListSuppliers);
                            dbPriceListDate = cmdShowMeLastPriceListDate.ExecuteScalar().ToString();
                        }
                    }
                    catch(Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                    finally
                    {
                        conShowMePriceListDateFromPriceListSuppliers.Close();
                    }
                }



                // SQLiteCommand cmdShowMeLastPriceListDate = new SQLiteCommand(qShowMeLastDateOfPriceList, conFillPriceListByNewData);

                //DateTime dateLastPriceListDate = Convert.ToDateTime(cmdShowMeLastPriceListDate.ExecuteScalar().ToString());


                if (Convert.ToDateTime(dbfPriceListDate) > Convert.ToDateTime(dbPriceListDate))
                {
                    using (SQLiteConnection conPriceListFromSupplier = new SQLiteConnection(connectionStringToLocalDB))
                    {
                        try
                        {
                            conPriceListFromSupplier.Open();


                            string qShowMeIdPriceListFromSupplier = $"select idPriceListSuppliers from PriceListFromSuppliers where ConsigneesCode = '{dbfConsigneesCode}' and CodeSuppliers = '{dbfSupplierCode}'";

                            SQLiteCommand cmdShowMeIdPriceListSupplier = new SQLiteCommand(qShowMeIdPriceListFromSupplier, conPriceListFromSupplier);
                            string IdPriceListFromSupplier = cmdShowMeIdPriceListSupplier.ExecuteScalar().ToString();

                            string qUpdatePriceListFromSupplier = $"update PriceListFromSuppliers set PriceListDate = (select strftime('%Y-%m-%d','{Convert.ToDateTime(dbfPriceListDate).ToString("yyyy-MM-dd")}')) where idPriceListSuppliers = '{IdPriceListFromSupplier}'";
                            string qDeletePriceListItems = $"delete from PriceList where idPriceListSupplier = '{IdPriceListFromSupplier}'";

                            SQLiteCommand cmdUpdatePriceListFromSuppliers = new SQLiteCommand(qUpdatePriceListFromSupplier, conPriceListFromSupplier);
                            SQLiteCommand cmdDeletePriceListItems = new SQLiteCommand(qDeletePriceListItems, conPriceListFromSupplier);

                            cmdUpdatePriceListFromSuppliers.ExecuteNonQuery();
                            

                            string qShowMeCountOfItemFromPriceList = $"select count(idPriceListSupplier) from PriceList where idPriceListSupplier = '{IdPriceListFromSupplier}'";
                            SQLiteCommand cmdShowMeCountItemsFromPriceList = new SQLiteCommand(qShowMeCountOfItemFromPriceList, conPriceListFromSupplier);
                            Int32 countItemsFromPriceList = Convert.ToInt32(cmdShowMeCountItemsFromPriceList.ExecuteScalar().ToString());

                            if(countItemsFromPriceList < 1)
                            {
                                
                            }
                            else
                            {
                                cmdDeletePriceListItems.ExecuteNonQuery();
                            }

                            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 dbfSupplierName = dr["SupplierName"].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 qInsertDataInLocalDB = $@"insert into PriceList (idPriceListSupplier, ConsigneesCode, GoodCode, GoodName, ProducerName, SupplierName, BestBefore, JNVLS, PriceReestr, AvaibleCount, PriceSupplierWithNDS, NDS , Marked)
                            values ('{IdPriceListFromSupplier}', '{dbfConsigneesCode}', '{dbfCode}','{dbfGood}','{dbfProducer}', (select SuppliersName from Suppliers where codeSuppliers = '{dbfSupplierCode}'),'{dbfBestBefore}','{dbfJNVLS}','{dbfPriceReestr}', '{dbfQuantity}', '{dbfPriceSupplierWithNds}', '{dbfNDS}', '{dbfMarked}')
                            ";
                                //MessageBox.Show(qInsertDataInLocalDB);

                                SQLiteCommand cmdInsertDataInPriceList = new SQLiteCommand(qInsertDataInLocalDB, conPriceListFromSupplier);
                                cmdInsertDataInPriceList.ExecuteNonQuery();
                            }
                            MessageBox.Show("Загрузка прайса завершена");

                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                        finally
                        {
                            conPriceListFromSupplier.Close();
                        }
                    }


                    //string IdPriceListFromSupplier = cmdShowMeIdPriceListSupplier.ExecuteScalar().ToString();

                    //string qUpdatePriceListFromSupplier = $"update PriceListFromSuppliers set PriceListDate = '{dbfPriceListDate}' where idPriceListSuppliers = '{IdPriceListFromSupplier}'";
                    //string qDeletePriceListItems = $"delete from PriceList where idPriceListSupplier = '{IdPriceListFromSupplier}'";

                    //SQLiteCommand cmdUpdatePriceListFromSuppliers = new SQLiteCommand(qUpdatePriceListFromSupplier, conFillPriceListByNewData);
                    //SQLiteCommand cmdDeletePriceListItems = new SQLiteCommand(qDeletePriceListItems, conFillPriceListByNewData);

                    ////cmdUpdatePriceListFromSuppliers.ExecuteNonQuery();
                    ////cmdDeletePriceListItems.ExecuteNonQuery();
                }

                //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 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();
                //    }
                //}
            }
        }
        */
        #endregion

        private void tsmi_CloseTab_Click(object sender, EventArgs e)
        {
            tabContent.TabPages.Remove(tabContent.SelectedTab);
        }

        private void закрытьВсеToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ClearDocumentTabs();
        }

        private void регистрацияToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var hF_Registration = new HF_Registration();
            UiThemeHelper.ApplyToControlTree(hF_Registration);
            hF_Registration.ShowDialog();
        }

        private async void tsExchangeDeploy_Click(object sender, EventArgs e)
        {
            DialogResult drUpdateData = UiDialogs.ConfirmYesNoCancel("Будут отправлены все сохранённые заказы. Вы уверены?", "Отправка заказов", this);

            if (drUpdateData == DialogResult.Yes)
            {
                ToastNotification.ShowCustom("Отправляем данные", Color.DarkOrange, Color.White);

                var uploadData = new DataSender();
                try
                {
                    await uploadData.Main();
                    //lblDataSent.Text = "ДАННЫЕ ОТПРАВЛЕНЫ";
                    //ToastNotification.ShowSuccess($"Данные отправлены");
                }
                catch (Exception ex)
                {
                    AppDebugLog.Error("Form1", "Не удалось отправить данные (меню Обмен)", ex);
                    ToastNotification.ShowError($"Не удалось отправить данные. {ex.Message}");
                    //MessageBox.Show(ex.ToString(), "Ошибка отправки данных на сервер", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //MessageBox.Show($"Не удалось отправить данные на сервер. Текст ошибки:\n{ex.ToString()}", "Ошибка отправки данных на сервер", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                //HF_UploadDataToServer hF_UploadDataToServer = new HF_UploadDataToServer();
                //hF_UploadDataToServer.Visible = false;
                //hF_UploadDataToServer.ShowDialog();
            }
        }

        private void tsJournal_DropDownOpened(object sender, EventArgs e)
        {
            tsJournal.ForeColor = System.Drawing.Color.Black;
        }

        private void tsJournal_DropDownClosed(object sender, EventArgs e)
        {
            tsJournal.ForeColor = System.Drawing.Color.White;
        }

        private void tsDirectory_DropDownOpened(object sender, EventArgs e)
        {
            tsDirectory.ForeColor = System.Drawing.Color.Black;
        }

        private void tsDirectory_DropDownClosed(object sender, EventArgs e)
        {
            tsDirectory.ForeColor = System.Drawing.Color.White;
        }

        private void tsExchange_DropDownClosed(object sender, EventArgs e)
        {
            tsExchange.ForeColor = System.Drawing.Color.White;
        }

        private void tsExchange_DropDownOpened(object sender, EventArgs e)
        {
            tsExchange.ForeColor = System.Drawing.Color.Black;
        }

        private void tsHelp_DropDownOpened(object sender, EventArgs e)
        {
            tsHelp.ForeColor = System.Drawing.Color.Black;
        }

        private void tsHelp_DropDownClosed(object sender, EventArgs e)
        {
            tsHelp.ForeColor = System.Drawing.Color.White;
        }

        private void roundBtnOrders_Click(object sender, EventArgs e)
        {
            OpenOrdersTab();
        }

        private void RoundBtnPriceList_Click(object sender, EventArgs e)
        {
            loadDefaultPriceList();
        }

        private void roundBtnRegister_Click(object sender, EventArgs e)
        {
            var hF_Registration = new HF_Registration();
            UiThemeHelper.ApplyToControlTree(hF_Registration);
            hF_Registration.ShowDialog();
        }

        private void tsBtnPriceList_Click(object sender, EventArgs e)
        {
            loadDefaultPriceList();
        }

        private void tsBtnOrders_Click(object sender, EventArgs e)
        {
            OpenOrdersTab();
        }

        private void tsBtnAuth_Click(object sender, EventArgs e)
        {
            var hF_Registration = new HF_Registration();
            UiThemeHelper.ApplyToControlTree(hF_Registration);
            if (hF_Registration.ShowDialog() == DialogResult.OK)
            {
                // После успешной авторизации сначала выбираем грузополучателя,
                // и только потом (если нужно) запрашиваем Location ID.
                int consigneeCount;
                using (var con = new SQLiteConnection(AppConfig.SqliteConnectionString))
                {
                    con.Open();
                    using (var cmd = new SQLiteCommand("SELECT COUNT(*) FROM Consignees", con))
                    {
                        consigneeCount = Convert.ToInt32(cmd.ExecuteScalar());
                    }
                }

                if (consigneeCount <= 1)
                {
                    var defaultName = ConsigneeHelper.GetDefaultConsigneeName();
                    if (!string.IsNullOrWhiteSpace(defaultName))
                    {
                        ConsigneeName = defaultName;
                        ConsigneeHelper.SetActiveConsignee(defaultName);
                    }
                }
                else
                {
                    var consigneeDialog = new HFConsignees { ParentForm = this };
                    UiThemeHelper.ApplyToControlTree(consigneeDialog);
                    if (consigneeDialog.ShowDialog(this) != DialogResult.OK)
                    {
                        // Без выбора грузополучателя дальше не идём.
                        return;
                    }
                }

                if (string.IsNullOrWhiteSpace(AppConfig.LocationId))
                {
                    var consigneeName = ConsigneeName ?? string.Empty;
                    var consigneeAddress = string.Empty;
                    if (!string.IsNullOrWhiteSpace(consigneeName))
                    {
                        using (var con = new SQLiteConnection(AppConfig.SqliteConnectionString))
                        {
                            con.Open();
                            using (var cmd = new SQLiteCommand(
                                @"SELECT ifnull(ConsigneesAddress, '') 
                                  FROM Consignees
                                  WHERE ConsigneesName = @name
                                  LIMIT 1",
                                con))
                            {
                                cmd.Parameters.AddWithValue("@name", consigneeName.Trim());
                                consigneeAddress = cmd.ExecuteScalar()?.ToString() ?? string.Empty;
                            }
                        }
                    }

                    if (!HF_LocationId.PromptAndSave(this, consigneeName, consigneeAddress))
                    {
                        ToastNotification.ShowCustom(
                            "Location ID не указан. Укажите его перед отправкой заказов.",
                            Color.DarkOrange,
                            Color.White);
                        return;
                    }
                }

                if (!string.IsNullOrWhiteSpace(AppConfig.LocationId))
                {
                    ConsigneeHelper.ApplyLocationIdToEmptyConsignees(AppConfig.LocationId);
                }

                RefreshCurrentUserStatus();
            }
        }

        private void OpenSettingsDialog()
        {
            var settingsForm = new HF_Settings();
            UiThemeHelper.ApplyToControlTree(settingsForm);
            if (settingsForm.ShowDialog(this) == DialogResult.OK)
            {
                RefreshCurrentUserStatus();
            }
        }

        private async void tsBtnSentData_Click(object sender, EventArgs e)
        {
            var hasToken = !string.IsNullOrWhiteSpace(Settings.Default.stringToken);
            if (!hasToken)
            {
                UiDialogs.ShowInfo("Сначала выполните авторизацию, чтобы отправить заказы.", "Авторизация", this);
                return;
            }

            DialogResult drUpdateData = UiDialogs.ConfirmYesNoCancel("Будут отправлены все сохранённые заказы. Вы уверены?", "Отправка заказов", this);

            if (drUpdateData == DialogResult.Yes)
            {
                var nowUtc = DateTime.UtcNow;
                var lastPriceUpdateUtc = Settings.Default.LastPriceUpdateUtc;
                var lastPriceReminderUtc = Settings.Default.LastPriceReminderUtc;

                var priceIsStale = lastPriceUpdateUtc == DateTime.MinValue ||
                                    (nowUtc - lastPriceUpdateUtc) > TimeSpan.FromHours(24);
                var canRemind = lastPriceReminderUtc == DateTime.MinValue ||
                                (nowUtc - lastPriceReminderUtc) > TimeSpan.FromHours(24);

                if (priceIsStale && canRemind)
                {
                    // Напоминание не блокирует отправку.
                    UiDialogs.ShowInfo(
                        "Прайс-лист не обновлялся более 24 часов. Рекомендуем обновить прайс перед отправкой заказов.",
                        "Прайс-лист",
                        this);

                    Settings.Default.LastPriceReminderUtc = nowUtc;
                    Settings.Default.Save();
                }

                ShowShellLoading("Отправка заказов...");
                ToastNotification.ShowCustom("Отправляем данные", Color.DarkOrange, Color.White);

                var uploadData = new DataSender();
                try
                {
                    await uploadData.Main();
                }
                catch (Exception ex)
                {
                    AppDebugLog.Error("Form1", "Не удалось отправить данные (кнопка ОТПРАВИТЬ)", ex);
                    ToastNotification.ShowError($"Не удалось отправить данные. {ex.Message}");
                }
                finally
                {
                    HideShellLoading();
                }
            }
        }

        private void tsBtnDownloadData_Click(object sender, EventArgs e)
        {
            string connectionStringToLocalDB = AppConfig.SqliteConnectionString;
            var consigneeSafe = (string.IsNullOrWhiteSpace(ConsigneeName) ? ConsigneeHelper.GetDefaultConsigneeName() : ConsigneeName)
                ?.Replace("'", "''");
            string qShowMeCoountDataFromTempOrder = $"select count(*) from TempOrderItems where ConsigneeName = '{consigneeSafe}'";
            int countDataTempOrder = 0;

            using (SQLiteConnection sqlCon = new SQLiteConnection(connectionStringToLocalDB))
            {
                try
                {
                    sqlCon.Open();
                    SQLiteCommand cmdCountOfDataTempOrder = new SQLiteCommand(qShowMeCoountDataFromTempOrder, sqlCon);
                    countDataTempOrder = Convert.ToInt32(cmdCountOfDataTempOrder.ExecuteScalar());
                }
                catch (Exception ex)
                {
                    UiDialogs.ShowError($"При получении данных из локальных базы данных произошла ошибка. Возможно БД повреждена. Текст ошибки:{ex.ToString()}", "Не удалось получить данные", this);
                }
                finally
                {
                    sqlCon.Close();
                }
            }

            ClearDocumentTabs();

            HF_DownloadDataFromServer hF_DownloadDataFromServer = new HF_DownloadDataFromServer();
            hF_DownloadDataFromServer.ActiveConsigneeName =
                string.IsNullOrWhiteSpace(ConsigneeName) ? ConsigneeHelper.GetDefaultConsigneeName() : ConsigneeName;
            UiThemeHelper.ApplyToControlTree(hF_DownloadDataFromServer);
            DialogResult downloadResult = DialogResult.Cancel;
            if (countDataTempOrder > 0)
            {
                DialogResult drShowDataDownload = UiDialogs.ConfirmYesNoCancel("В корзине найдены товары. При обновлении прайса она будет очищена.\nПродолжить?", "ТОВАРЫ В КОРЗИНЕ", this);
                if (drShowDataDownload == DialogResult.Yes)
                {
                    downloadResult = hF_DownloadDataFromServer.ShowDialog();
                }
            }
            else
            {
                downloadResult = hF_DownloadDataFromServer.ShowDialog();
            }

            if (downloadResult == DialogResult.OK)
            {
                RefreshOpenPriceLists();
            }
            else if (!HasDocumentTabs())
            {
                loadDefaultPriceList();
            }
        }
    }
}
