using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using WK5.Core;
using WK5.Core.Models;

namespace WK5_Blazor.Pages.Statistik.Verkauf
{
    public partial class BestsellerProPreisgruppe
    {
        public List<(Artikel artikel, decimal Menge)> Ergebnis { get; set; } = new List<(Artikel artikel, decimal Menge)>();
        public BestsellerFilter Filter { get; set; } = new BestsellerFilter();
        public bool _loading { get; set; } = false;
        public string Message { get; set; } = String.Empty;
        private async Task Suchen()
        {
            _loading = true;
            Ergebnis.Clear();

            await InvokeAsync(StateHasChanged);
            await Task.Delay(1);

            string sql = @"SELECT FIRST 5 ARTI_A_NR, (COALESCE(SUM(BPOS_N_MENGE),0)-(SELECT COALESCE(SUM(BPOS_N_MENGE),0) FROM BELEGPOS
LEFT JOIN BELEGE ON BPOS_N_NR = BELE_N_NR AND BPOS_A_TYP = BELE_A_TYP
WHERE BPOS_A_TYP = 'GU'
AND BPOS_A_ARTIKELNR = ARTI_A_NR
AND BELE_D_DATE >= @FROM AND BELE_D_DATE <= @TO ) ) as Total FROM ARTIKEL
LEFT JOIN BELEGPOS ON BPOS_A_ARTIKELNR = ARTI_A_NR
LEFT JOIN BELEGE ON BELE_N_NR = BPOS_N_NR AND BELE_A_TYP = BPOS_A_TYP
WHERE ARTI_A_PREISGRUPPE = @PRGR AND BELE_A_TYP = 'RE'
AND BELE_D_DATE >= @FROM AND BELE_D_DATE <= @TO
GROUP BY ARTI_A_NR
ORDER BY Total DESC";

            using FbController2 fbController = new FbController2();
            fbController.AddParameter("@PRGR", Filter.PreisgruppenNr);
            fbController.AddParameter("@FROM", Filter.From);
            fbController.AddParameter("@TO", Filter.To);

            DataTable data = await fbController.SelectDataAsync(sql);

            if (data.Rows.Count <= 0)
            {
                Message = "Keine Ergebnisse gefunden!";
            }
            else
            {
                Message = String.Empty;
            }

            foreach (DataRow row in data.Rows)
            {
                if (row is not null)
                {
                    string artiNr = row.Field<string>("ARTI_A_NR") ?? String.Empty;
                    decimal total = row.Field<decimal>("Total");

                    Artikel? artikel = await artikelService.GetAsync(artiNr, fbController);
                    if (artikel is not null)
                    {
                        Ergebnis.Add((artikel, total));
                    }
                }
            }
            _loading = false;
        }
    }

    public class BestsellerFilter
    {
        public string PreisgruppenNr { get; set; } = Program.AppDaten.Preisgruppen.First().PRGR_A_NR;
        public DateTime From { get; set; } = DateTime.Now.AddYears(-1);
        public DateTime To { get; set; } = DateTime.Now;
    }
}
