using System;

namespace WK5.Core.Basis.Filter
{
    public class BelegFilter : PageFilter
    {
        public BelegTyp BelegTyp { get; set; }
        public bool ZeitraumEingrenzen { get; set; }
        public Zeitraum Zeitraum { get; set; } = new Zeitraum();

        public bool IdeaExportSuche { get; set; }

        public BelegFilter()
        {

        }

        public BelegFilter(BelegTyp belegTyp)
        {
            BelegTyp = belegTyp;
        }
        public override string ToCountQuery(FbController2 fbController)
        {
            sqlBuilder.Append("SELECT COUNT(*) FROM BELEGE WHERE 1 = 1");
            BuildQueryConditions(fbController);

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

        public override string ToSqlQuery(FbController2 fbcontroller)
        {

            sqlBuilder.Append(@$"SELECT FIRST {Limit} SKIP {(Seite - 1) * Limit} * FROM BELEGE WHERE 1 = 1");

            BuildQueryConditions(fbcontroller);

            sqlBuilder.Append(" ORDER BY BELE_D_DATE DESC, BELE_N_NR DESC");

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

        protected override void BuildQueryConditions(FbController2 fbController)
        {

            if (IdeaExportSuche)
            {
                sqlBuilder.Append($" AND BELE_A_TYP IN ('RE', 'GU')");
            }
            else
            {
                sqlBuilder.Append($" AND BELE_A_TYP = '{EnumHelper.GetBelegTypString(BelegTyp)}'");
            }

            

            if (!String.IsNullOrWhiteSpace(Suchbegriff))
            {
                if (Suchbegriff.Length > 255)
                {
                    throw new ArgumentOutOfRangeException(nameof(Suchbegriff), "Der Suchbegriff darf nicht mehr als 255 Zeichen haben.");
                }

                sqlBuilder.Append(@$" AND 
(
    CAST(BELE_N_NR AS VARCHAR(255)) LIKE @SUCHBEGRIFF
OR  CAST(UPPER(BELE_A_KUNDENNR) AS VARCHAR(255)) LIKE @SUCHBEGRIFF
OR  CAST(UPPER(BELE_A_NAME1) AS VARCHAR(255)) LIKE @SUCHBEGRIFF
OR  CAST(UPPER(BELE_A_NAME2) AS VARCHAR(255)) LIKE @SUCHBEGRIFF
OR  CAST(UPPER(BELE_A_NAME3) AS VARCHAR(255)) LIKE @SUCHBEGRIFF
)");

                fbController.AddParameter("@SUCHBEGRIFF", $"%{Suchbegriff}%");
            }

            if (ZeitraumEingrenzen)
            {
                sqlBuilder.Append(" AND BELE_D_DATE BETWEEN @ZEITRAUM_START AND @ZEITRAUM_ENDE");
                fbController.AddParameter("@ZEITRAUM_START", Zeitraum.Von.ToShortDateString());
                fbController.AddParameter("@ZEITRAUM_ENDE", Zeitraum.Bis.ToShortDateString());
            }
        }
    }

}
