using System;

namespace WK5.Core.Basis.Filter.Statistik
{
    public class TopArtikelNachLieferantFilter : Filter
    {
        public int LieferantId { get; set; }
        public Zeitraum Zeitraum { get; set; }

        public int AnzahlMaxErgebnisse { get; set; } = 30;

        public TopArtikelNachLieferantFilter()
        {
            Zeitraum = new Zeitraum(new DateTime(DateTime.Today.Year - 1, 1, 1), new DateTime(DateTime.Today.Year - 1, 12, 31));
        }

        public override string ToSqlQuery(FbController2 fbController)
        {
            sqlBuilder.Append(@$"SELECT FIRST {AnzahlMaxErgebnisse} SKIP 0 C.CHAR_A_ARTINR, SUM(CHAR_N_MENGE) AS MENGE, SUM(C.CHAR_N_MENGEOFFEN) AS MENGE_OFFEN FROM ZUGAENGE Z
LEFT JOIN CHARGEN C ON (C.CHAR_N_STAPELNR = Z.ZUGA_N_NR)
WHERE 1 = 1");

            BuildQueryConditions(fbController);

            sqlBuilder.Append(@"
GROUP BY C.CHAR_A_ARTINR
ORDER BY SUM(CHAR_N_MENGE) DESC");

            string sql = sqlBuilder.ToString();
            sqlBuilder.Clear();
            return sql;
        }

        protected override void BuildQueryConditions(FbController2 fbController)
        {
            sqlBuilder.Append(" AND Z.ZUGA_N_LIEF = @ZUGA_N_LIEF");
            fbController.AddParameter("@ZUGA_N_LIEF", LieferantId);
            sqlBuilder.Append(" AND Z.ZUGA_D_DATUM BETWEEN @START AND @ENDE");
            fbController.AddParameter("@START", Zeitraum.Von.ToShortDateString());
            fbController.AddParameter("@ENDE", Zeitraum.Bis.ToShortDateString());
        }
    }
}
