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

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

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

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

            loadInvoicesList(dateFrom, dateTo, dateFromYear);
        }

        string filterAddons = "";

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

            string qShowMeSuppliersList = "select SuppliersName from suppliers order by [SuppliersName] asc";

            using (SQLiteConnection conSuppliers = new SQLiteConnection(connectionStringToLocalDB))
            {
                try
                {
                    conSuppliers.Open();
                    SQLiteCommand cmdShowMeSuppliersList = new SQLiteCommand(qShowMeSuppliersList, conSuppliers);
                    SQLiteDataAdapter daSuppliersList = new SQLiteDataAdapter(cmdShowMeSuppliersList);
                    DataTable tableSuppliers = new DataTable();
                    daSuppliersList.Fill(tableSuppliers);
                    comboSuppliers.DataSource = tableSuppliers;
                    comboSuppliers.DisplayMember = "SuppliersName";
                    comboSuppliers.Text = "Поставщик";
                }
                catch(Exception ex)
                {
                    ToastNotification.ShowError($"Ошибка загрузки поставщиков: {ex.Message}");
                }
                finally
                {
                    conSuppliers.Close();
                }
            }
        }

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

            string qShowMeConsigneesList = "select ConsigneesName from Consignees order by [ConsigneesUseAsDefault] desc";

            using (SQLiteConnection conConsignees = new SQLiteConnection(connectionStringToLocalDB))
            {
                try
                {
                    conConsignees.Open();
                    SQLiteCommand cmdShowMeConsigneesList = new SQLiteCommand(qShowMeConsigneesList, conConsignees);
                    SQLiteDataAdapter daConsigneesList = new SQLiteDataAdapter(cmdShowMeConsigneesList);
                    DataTable tableConsignees = new DataTable();
                    daConsigneesList.Fill(tableConsignees);
                    comboConsignees.DataSource = tableConsignees;
                    comboConsignees.DisplayMember = "ConsigneesName";
                    comboConsignees.Text = "Грузополучатель";
                }
                catch (Exception ex)
                {
                    ToastNotification.ShowError($"Ошибка загрузки грузополучателей: {ex.Message}");
                }
                finally
                {
                    conConsignees.Close();
                }
            }
        }

        void loadInvoicesList(string InvoicesDateFrom, string InvoicesDateTo, string dateFromYearFormat)
        {

            string connectionStringToLocalDB = AppConfig.SqliteConnectionString;

            string filterAddons = $"where i.InvoiceDate between date('{InvoicesDateFrom}') and date('{InvoicesDateTo}')";

            if (txtInvoiceNumber.Text != "" & txtInvoiceNumber.Text != "Номер накладной")
            {
                filterAddons += $" and i.InvoiceNumber like '%{txtInvoiceNumber.Text}%'";
            }

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

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

            string qShowMeListOfInvoices = $@"
select i.InvoiceNumber as [Номер],
i.invoiceDate as [Дата],
s.SuppliersName as [Поставщик],
c.ConsigneesName as [Грузополучатель],
c.ConsigneesAddress as [Адрес ГП],
i.SumWithoutNDS as [Сумма без НДС],
i.SumWithNDS as [Сумма с НДС],
i.SumNDS as [Сумма НДС]
from [Invoice] i
inner join [Suppliers] s on s.codeSuppliers = i.CodeSupplier
inner join [Consignees] c on c.codeConsignees = i.CodeConsignees
{filterAddons}
order by i.InvoiceDate asc
";

            using (SQLiteConnection conInvoices = new SQLiteConnection(connectionStringToLocalDB))
            {
                try
                {
                    conInvoices.Open();
                    SQLiteCommand cmdShowInvoicesList = new SQLiteCommand(qShowMeListOfInvoices, conInvoices);
                    DataTable tableInvoices = new DataTable();
                    SQLiteDataAdapter daInvoicesList = new SQLiteDataAdapter(cmdShowInvoicesList);
                    daInvoicesList.Fill(tableInvoices);
                    dgvInvoice.DataSource = tableInvoices;
                }
                catch (Exception ex)
                {
                    ToastNotification.ShowError($"Ошибка загрузки накладных: {ex.Message}");
                }
                finally
                {
                    conInvoices.Close();
                }
            }



            loadInvoiceItems(string.Empty);

            //selectInvoice();
        }

        private void UCInvoices_Load(object sender, EventArgs e)
        {
            UiThemeHelper.ApplyToControlTree(this);
            Font = new Font("Segoe UI", 9.75f, FontStyle.Regular);

            button1.Visible = true;
            button1.Text = "Обновить с сервера";
            button1.Width = 180;
            ModernButtonStyles.ApplyAuto(button1);
            button1.Click += async (_, __) => await SyncFromServerAsync();

            loadConsignees();
            loadSuppliers();
            getDatesFromCalendar();
        }

        private async Task SyncFromServerAsync()
        {
            button1.Enabled = false;
            UseWaitCursor = true;
            try
            {
                var sync = new InvoiceSyncService();
                int count = await sync.SyncFromServerAsync();
                ToastNotification.ShowSuccess($"Загружено накладных: {count}");
                getDatesFromCalendar();
            }
            catch (Exception ex)
            {
                ToastNotification.ShowError($"Не удалось загрузить накладные: {ex.Message}");
            }
            finally
            {
                button1.Enabled = true;
                UseWaitCursor = false;
            }
        }


        private void dtpDateTo_Leave(object sender, EventArgs e)
        {
            getDatesFromCalendar();
        }

        private void dtpDateFrom_Leave(object sender, EventArgs e)
        {
            getDatesFromCalendar();
        }

        private void dtpDateTo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                getDatesFromCalendar();
            }
        }

        private void dtpDateFrom_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                getDatesFromCalendar();
            }
        }


        void selectInvoice()
        {
            if (dgvInvoice.Rows.Count > 0)
            {
                int SelectedInvoiceIndex = dgvInvoice.CurrentCell.RowIndex;
                string SelectedInvoiceNumber = dgvInvoice.Rows[SelectedInvoiceIndex].Cells[0].Value.ToString();
                loadInvoiceItems(SelectedInvoiceNumber);
            }
        }

        void loadInvoiceItems(string InvoiceNumber)
        {
            string filterAddons = string.Empty;


            string InvNum = InvoiceNumber;
            if (dgvInvoice.Rows.Count > 0)
            {
                if (InvNum != "" | InvoiceNumber != string.Empty)
                {
                    filterAddons = $"where i.InvoiceNumber = '{InvNum}'";

                    string connectionStringToLocalDB = AppConfig.SqliteConnectionString;
                    string qShowMeInvoiceItems = $@"
select
ii.GoodCode as [Код товара],
ii.Good as [Товар],
ii.ProducerName as [Производитель],
ii.CountryName as [Страна],
ii.GoodsGount as [Количество],
ii.PriceSupplierWithoutNDS as [Цена пост. без НДС],
ii.PriceSupplierWithNDS as [Цена пост. с НДС],
ii.PriceProducerWithoutNDS as [Цена произв. без НДС],
ii.PriceProducerWithNDS as [Цена произв. с НДС],
ii.NDS as [НДС %],
ii.JNVLS as [ЖНВЛП?],
ii.PriceReestr as [Предел. цена произв.],
ii.SumWithoutNDS as [Сумма пост. без НДС],
ii.SumWithNDS as [Сумма пост. с НДС],
ii.SumNDS as [Сумма НДС],
ii.Serial as [Серия],
ii.BestBefore as [Срок годности],
ii.Sertificate as [Сертификат],
ii.Marked as [Признак маркировки],
ii.GTIN as [GTIN]
from InvoiceItem ii
inner join Invoice i on i.idInvoice = ii.idInvoice
{filterAddons}
";
                    using (SQLiteConnection conInvoiceItems = new SQLiteConnection(connectionStringToLocalDB))
                    {
                        try
                        {
                            conInvoiceItems.Open();
                            SQLiteCommand cmdShowMeInvoiceItems = new SQLiteCommand(qShowMeInvoiceItems, conInvoiceItems);
                            DataTable tableInvoiceItems = new DataTable();
                            SQLiteDataAdapter daInvoiceItems = new SQLiteDataAdapter(cmdShowMeInvoiceItems);
                            daInvoiceItems.Fill(tableInvoiceItems);
                            dgvInvoiceItems.DataSource = tableInvoiceItems;
                            dgvInvoiceItems.Columns[10].ValueType = typeof(bool);
                        }
                        catch (Exception ex)
                        {
                            ToastNotification.ShowError($"Ошибка загрузки позиций накладной: {ex.Message}");
                        }
                        finally
                        {
                            conInvoiceItems.Close();
                        }
                    }

                }
            }
            else
            {
                dgvInvoiceItems.DataSource = null;
            }
        }

        private void txtInvoiceNumber_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                if (dgvInvoice.Rows.Count > 0)
                {
                    (dgvInvoice.DataSource as DataTable).DefaultView.RowFilter = string.Format($"[Номер] like '%{txtInvoiceNumber.Text}%'");
                    if (dgvInvoice.Rows.Count == 0)
                    {
                        getDatesFromCalendar();
                    }
                }
                    txtInvoiceNumber.Text = "Номер накладной";
                dgvInvoice.Focus();
            }
        }

        private void txtInvoiceNumber_Enter(object sender, EventArgs e)
        {
            if (txtInvoiceNumber.Text == "Номер накладной") 
            {
                txtInvoiceNumber.Text = string.Empty;
            }
        }

        private void txtInvoiceNumber_Leave(object sender, EventArgs e)
        {
            if (txtInvoiceNumber.Text == string.Empty)
            {
                txtInvoiceNumber.Text = "Номер накладной";
            }
        }

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

        private void comboConsignees_SelectedIndexChanged(object sender, EventArgs e)
        {
            getDatesFromCalendar();
            selectInvoice();
        }

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

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

        private void dgvInvoice_SelectionChanged(object sender, EventArgs e)
        {
            selectInvoice();
        }
    }
}
