using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WK5.Core.Basis.Filter
{
    public class RmaFilter : PageFilter
    {
        public bool ZeigeErledigte { get; set; }
        public bool IsFilterActive
        {
            get
            { 
                if(!String.IsNullOrWhiteSpace(Suchbegriff))
                {
                    return true;
                }

                if(ZeigeErledigte)
                {
                    return true;
                }

                return false; 
            }
        }
        public override string ToCountQuery(FbController2 fbController)
        {
            sqlBuilder.Append(@$"SELECT COUNT(*) 
FROM RMAS R 
LEFT JOIN KUNDEN K ON K.KUND_A_NR = R.RMA_A_KUNDENNR
WHERE 1 = 1");
            BuildQueryConditions(fbController);

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

        public override string ToSqlQuery(FbController2 fbController)
        {
            sqlBuilder.Append(@$"SELECT FIRST {Limit} SKIP {(Seite - 1) * Limit} 
R.*,
K.KUND_A_NAME1, K.KUND_A_NAME2, K.KUND_A_NAME3
FROM RMAS R 
LEFT JOIN KUNDEN K ON K.KUND_A_NR = R.RMA_A_KUNDENNR
WHERE 1 = 1");
            BuildQueryConditions(fbController);
            sqlBuilder.Append(" ORDER BY RMA_N_NR DESC");

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

        protected override void BuildQueryConditions(FbController2 fbController)
        {
            if(!String.IsNullOrWhiteSpace(Suchbegriff))
            {
                sqlBuilder.Append(@" AND 
(
    UPPER(CAST(RMA_N_NR as VARCHAR(255))) LIKE @SUCHBEGRIFF
OR  UPPER(CAST(RMA_N_LIEFNR as VARCHAR(255))) LIKE @SUCHBEGRIFF 
OR  UPPER(CAST(RMA_A_KUNDENNR as VARCHAR(255))) LIKE @SUCHBEGRIFF 
OR  UPPER(CAST(RMA_A_ARTIKELNR as VARCHAR(255))) LIKE @SUCHBEGRIFF 
OR  UPPER(CAST(RMA_A_SERIENNUMMER as VARCHAR(255))) LIKE @SUCHBEGRIFF 
OR  UPPER(CAST(RMA_N_NR_LS as VARCHAR(255))) LIKE @SUCHBEGRIFF 
OR  UPPER(CAST(RMA_A_RMANR_LIEFERANT as VARCHAR(255))) LIKE @SUCHBEGRIFF 
OR  UPPER(CAST(RMA_A_TICKETNR_LIEFERANT as VARCHAR(255))) LIKE @SUCHBEGRIFF 
OR  UPPER(CAST(RMA_A_TICKETNR as VARCHAR(255))) LIKE @SUCHBEGRIFF
OR  UPPER(CAST(KUND_A_NAME1 as VARCHAR(255))) LIKE @SUCHBEGRIFF
OR  UPPER(CAST(KUND_A_NAME2 as VARCHAR(255))) LIKE @SUCHBEGRIFF
OR  UPPER(CAST(KUND_A_NAME3 as VARCHAR(255))) LIKE @SUCHBEGRIFF
)");

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

            if (!ZeigeErledigte)
            {
                sqlBuilder.Append(" AND RMA_L_ERLEDIGT = 'N'");
            }
        }
    }
}
