using craftsReport.Interfaces;

namespace craftsReport.modules
{
	/// <summary>
	/// Zeitkladde Mitarbeiter
	/// Berichtsparameter
	/// 01	Kladdencode			mFltCode(u,20,0)
	/// 02	Jahresfilter		mFltJahr(u,4,0)
	/// 03	Monatsfilter		mFltMonat(u,2,0)	
	/// 04	Arbeitnehmernummer	mFltAnnr(u,4,0)
	/// 05	Projektnummer		mFltPrjNr(u,8,0)
	/// 06	Details				mDetails(L,1,0)
	/// 07	Lohnart				mFltLoa(u,3,0)
	/// </summary>
	public class rp0650_xbs : IReportModule, IReportModuleEvents
	{
		#region Members and Contructor

		private bool m_IsLastPage = false;
		private string m_CurrentAnnr = null;
		private string m_CurrentLoa = null;
		private bool m_CurrLoaSoll = false;
		private bool m_CurrLoaStunden = false;
		private bool m_WithDetails = false;
		private IReportRecord m_recMain;
		private IReportRecord m_recAnnr;
		private IReportRecord m_recLoa;

		public rp0650_xbs()
		{
		}

		#endregion

		#region IReportModule

		public IReportHost HostObject { set; get; }

		// ER_Kontierung
		public bool Execute()
		{
			if (!HostObject.IsVar("mRepTitle"))
				HostObject.DefineVariable2("mRepTitle", "c,250,0");
			if (HostObject.IsEmpty("mRepTitle"))
				HostObject.Set("mRepTitle", "Zeitkladde Arbeitnehmer", false);

			// -------------------------------------------------------------------------
			//  Prüfen Sie hier die Übergabe von Filtervariablen
			//  Beispiel
			if (!HostObject.IsVar("mFltJahr"))
				HostObject.DefineVariable2("mFltJahr", "C,4,0");
			if (!HostObject.IsVar("mFltMonat"))
				HostObject.DefineVariable2("mFltMonat", "C,2,0");
			if (!HostObject.IsVar("mFltCode"))
				HostObject.DefineVariable2("mFltCode", "u,20,0");
			if (!HostObject.IsVar("mFltAnnr"))
				HostObject.DefineVariable2("mFltAnnr", "u,4,0");
			if (!HostObject.IsVar("mFltPrjNr"))
				HostObject.DefineVariable2("mFltPrjNr", "u,4,0");
			if (!HostObject.IsVar("mDetails"))
				HostObject.DefineVariable2("mDetails", "L,1,0");
			if (!HostObject.IsVar("mFltLoa"))
				HostObject.DefineVariable2("mFltLoa", "u,3,0");

			HostObject.DefineVariable2("mFilterText", "c,250,0");

			// SQL-Abfrage erstellen
			#region SqlQuery (Satznummernabfrage nach recSQLMain)
			// ---------------------------------------------------------------------------------
			System.Text.StringBuilder sbQuery = new System.Text.StringBuilder(
				"select z.RecId, ROUND(z.Betrag + (z.Stunden * ROUND(z.Brutto * l.ekfaktor, 2)), 2) AS LineTotal " +
				"from ut_ZeitKladdenZeile z inner join ut_Lohnarten l on l.lohnart = z.Loa " +
				"where (z.Stunden <> 0 or z.Betrag <> 0)"
			);

			int nJahr  = HostObject.EvalInt("$[mFltJahr]");
			int nMonat = HostObject.EvalInt("$[mFltMonat]");
			if ((nJahr > 1900) && (nMonat > 0) && (nMonat < 13))
            {
				int nMonat2 = nMonat < 12 ? nMonat + 1 : 1;
				int nJahr2 = nMonat < 12 ? nJahr : nJahr + 1;
				sbQuery.AppendFormat("\r\n AND z.BuchDatum >= convert(datetime, '{0}-{1}-01', 120)", nJahr, nMonat.ToString().PadLeft(2,'0'));
				sbQuery.AppendFormat("\r\n AND z.BuchDatum < convert(datetime, '{0}-{1}-01', 120)", nJahr2, nMonat2.ToString().PadLeft(2, '0'));
				HostObject.Set("mFilterText", nMonat.ToString().PadLeft(2, '0') + "/" + nJahr.ToString(), false);
			}
			else if (nJahr > 1900)
            {
				sbQuery.AppendFormat(" AND z.BuchDatum >= convert(datetime, '{0}-01-01', 120)", nJahr);
				sbQuery.AppendFormat(" AND z.BuchDatum < convert(datetime, '{0}-01-01', 120)", nJahr + 1);
				HostObject.Set("mFilterText", nJahr.ToString(), false);
			}

			if (!HostObject.IsEmpty("mFltCode"))
			{
				sbQuery.Append("\r\n AND z.Code = " + HostObject.FormatSqlString("$[mFltCode]", true));
				HostObject.Set("mFilterText", "$[mFilterText] $[mFltCode]", true);
			}

			if (!HostObject.IsEmpty("mFltPrjNr"))
			{
				sbQuery.Append("\r\n AND z.PrjNr = " + HostObject.FormatSqlString("$[mFltPrjNr]", true));
				HostObject.Set("mFilterText", "$[mFilterText] $[mFltPrjNr]", true);
			}

			if (!HostObject.IsEmpty("mFltAnnr"))
			{
				sbQuery.Append("\r\n AND z.Annr = " + HostObject.FormatSqlString("$[mFltAnnr]", true));
				HostObject.Set("mFilterText", "$[mFilterText] $[mFltAnnr]", true);
			}

			if (!HostObject.IsEmpty("mFltLoa"))
			{
				sbQuery.Append("\r\n AND z.Loa = " + HostObject.FormatSqlString("$[mFltLoa]", true));
				HostObject.Set("mFilterText", "$[mFilterText] $[mFltLoa]", true);
			}

			m_WithDetails = HostObject.EvalBool("$[mDetails]");
			if (m_WithDetails)
				sbQuery.Append("\r\n ORDER BY z.Annr, z.BuchDatum, z.Loa, z.PrjNr, z.Code, z.LfdNr");
			else
				sbQuery.Append("\r\n ORDER BY z.Annr, z.Loa, z.BuchDatum, z.PrjNr, z.Code, z.LfdNr");

			var recSqlMain = HostObject.DefineSqlRecord("recSQLMain", sbQuery.ToString());
			if (recSqlMain == null)
			{
				HostObject.Confirm("Die SQL-Abfrage ist fehlgeschlagen\r\n\r\n" + sbQuery.ToString());
				return false;
			}
			//HostObject.Confirm(sbQuery.ToString());
			// ---------------------------------------------------------------------------------
			#endregion

			HostObject.LoadAdditionalResources("/r");
			HostObject.PaperDefinition("PaperDefinition");

			m_recMain = HostObject.DefineRecord("recMAIN", "ZeitKladdenZeile", 0, 0, "");
			m_recAnnr = HostObject.DefineRecord("recAnnr", "Adressstamm", 6, 2, " 4");
			m_recLoa = HostObject.DefineRecord("recLoa", "Lohnarten", 0, 0, "");
			HostObject.DefineVariable2("mLineTotal", "N,12,2");
			HostObject.DefineVariable2("mVkzLohnart", "C,4,0");
			HostObject.DefineVariable2("mSummeLohnart", "N,12,2");
			HostObject.DefineVariable2("mSummeAnnr", "N,12,2");
			HostObject.DefineVariable2("mSummeGesamt", "N,12,2");
			HostObject.DefineVariable2("mStundenLohnart", "N,12,2");
			HostObject.DefineVariable2("mStundenAnnr", "N,12,2");  // nur Sollstunden
			HostObject.DefineVariable2("mStundenGesamt", "N,12,2");  // nur Sollstunden
			HostObject.DefineVariable2("mAnzahlLohnart", "N,8,0");
			HostObject.DefineVariable2("mCurrLoaBetrag", "N,12,2");
			HostObject.DefineVariable2("mCurrLoaBrutto", "N,12,2");
			HostObject.DefineVariable2("mCurrLoaFaktor", "N,12,2");

			HostObject.DokumentStart();
			HostObject.SeitenKopf();

			while (!recSqlMain.Eof)
			{
				HostObject.SeekRecord("recMain", HostObject.CastInt(recSqlMain.GetI(1)));
				SUB_loopMAIN();
				recSqlMain.GoNext();
			}
			if ((!m_WithDetails) && (m_CurrentLoa != null))
			{
				SUB_SummeLohnart();
			}
			if (m_CurrentAnnr != null)
			{
				SUB_SummeAnnr();
			}
			if (!m_WithDetails)
            {
				SUB_SummeGesamt();
            }

			m_IsLastPage = true;
			HostObject.SeitenFuss();
			HostObject.DokumentEnde();
			return true;
		}

		#endregion

		#region IReportModuleEvents

		public void OnAfterPageStart()
		{
			HostObject.ProcessResource("KopfDetail");

			if (HostObject.EvalInt("$[Seite]") == 1)
			{
			}
			else
			{
				// HostObject.ProcessResource("Uebertrag");
			}
		}

		public void OnBeforePageClose()
		{
			if (m_IsLastPage)
			{
				//if (HostObject.EvalInt("$[ZlMax]") > HostObject.EvalInt("$[Zeile]"))
				//	HostObject.ProcessResource("Sterne");
				// HostObject.ProcessResource("FussBericht");
			}
			else
			{
				// HostObject.ProcessResource("FussSeite");
			}
		}

		public void OnAfterExecute(string szOutFileName)
		{
		}

		#endregion

		#region Internals

		void SUB_loopMAIN()
		{
			HostObject.Set("mLineTotal", "$[recSQLMain.LineTotal]", true);

			// Arbeitnehmer hat gewechselt
			if ((m_CurrentAnnr == null) || (m_CurrentAnnr != HostObject.EvalString("$[recMAIN.Annr]")))
			{
				if (m_CurrentAnnr != null)
				{
					if (m_WithDetails)
					{
						SUB_SummeAnnr();
						HostObject.FormFeed();
					}
					else
					{
						SUB_SummeLohnart();
						SUB_SummeAnnr();
						HostObject.LineFeed(1);
						m_CurrentLoa = null;
					}
				}
				m_CurrentAnnr = HostObject.EvalString("$[recMAIN.Annr]");
				m_recAnnr.Find(m_CurrentAnnr.PadRight(4));
				HostObject.Set("mSummeAnnr", "0", true);
				HostObject.Set("mSummeLohnart", "0", true);
				HostObject.Set("mStundenAnnr", "0", true);
				HostObject.Set("mStundenLohnart", "0", true);
				HostObject.Set("mAnzahlLohnart", "0", true);
				HostObject.ProcessResource("KopfAnnr");
			}

			// Lohnart oder Parameter derselben haben gewechselt
			if ((m_CurrentLoa == null) || (m_CurrentLoa != HostObject.EvalString("$[recMAIN.Loa]"))
				|| (HostObject.EvalString("$[mCurrLoaBetrag]") != HostObject.EvalString("$[recMAIN.Betrag]"))
				|| (HostObject.EvalString("$[mCurrLoaBrutto]") != HostObject.EvalString("$[recMAIN.Brutto]"))
				)
            {
				if ((!m_WithDetails) && (m_CurrentLoa != null))
				{
					SUB_SummeLohnart();
				}
				HostObject.Set("mSummeLohnart", "0", true);
				HostObject.Set("mStundenLohnart", "0", true);
				HostObject.Set("mAnzahlLohnart", "0", true);

				m_CurrentLoa = HostObject.EvalString("$[recMAIN.Loa]");
				m_recLoa.Find(m_CurrentLoa.PadRight(3));
				m_CurrLoaStunden = HostObject.EvalBool("$[recLoa.stdloa]");
				m_CurrLoaSoll = HostObject.EvalBool("$[recLoa.bsoll]");

				if (m_CurrLoaStunden && m_CurrLoaSoll)
					HostObject.Set("mVkzLohnart", "Soll", false);
				else if (m_CurrLoaStunden)
					HostObject.Set("mVkzLohnart", "Zeit", false);
				else
					HostObject.Set("mVkzLohnart", "Fix", false);

				HostObject.Set("mCurrLoaBetrag", "$[recMAIN.Betrag]", true);
				HostObject.Set("mCurrLoaBrutto", "$[recMAIN.Brutto]", true);
				HostObject.Set("mCurrLoaFaktor", "$[recLoa.ekfaktor]", true);
			}

			// Detailierte Ausgabe
			if (m_WithDetails)
			{
				SUB_Detail();
			}

			HostObject.Set("mSummeLohnart", "$[mSummeLohnart] + $[recSQLMain.LineTotal]", true);
			HostObject.Set("mSummeAnnr", "$[mSummeAnnr] + $[recSQLMain.LineTotal]", true);
			HostObject.Set("mSummeGesamt", "$[mSummeGesamt] + $[recSQLMain.LineTotal]", true);
			// Stunden aufsummieren
			if (m_CurrLoaStunden)
			{
				HostObject.Set("mStundenLohnart", "$[mStundenLohnart] + $[recMAIN.Stunden]", true);
				if (m_CurrLoaStunden && m_CurrLoaSoll)
				{
					HostObject.Set("mStundenAnnr", "$[mStundenAnnr] + $[recMAIN.Stunden]", true);
					HostObject.Set("mStundenGesamt", "$[mStundenGesamt] + $[recMAIN.Stunden]", true);
				}
			}
			// Anzahl aufsummieren
			else
            {
				HostObject.Set("mAnzahlLohnart", "$[mAnzahlLohnart] + 1", true);
			}
		}

		void SUB_Detail()
        {
			HostObject.VariablesPush();
			HostObject.DefineVariable2("mBetrag", "C,12,0");
			HostObject.DefineVariable2("mStunden", "C,12,0");
			HostObject.DefineVariable2("mFaktor", "C,10,0");

			if (m_CurrLoaStunden)
			{
				HostObject.Set("mStunden", "$[recMAIN.Stunden]", true);
				HostObject.Set("mBetrag", "$[recMAIN.Brutto]", true);
				if (HostObject.EvalString("$[recLoa.ekfaktor]") != "1,00")
					HostObject.Set("mFaktor", "$[recLoa.ekfaktor]", true);
			}
			else
			{
				HostObject.Set("mBetrag", "$[recMAIN.Betrag]", true);
			}

			HostObject.CheckPageSpace(1);
			HostObject.ProcessResource("Detail");
			HostObject.VariablesPop();
		}

		void SUB_SummeLohnart()
		{
			HostObject.VariablesPush();
			HostObject.DefineVariable2("mBetrag", "C,12,0");
			HostObject.DefineVariable2("mStunden", "C,12,0");
			HostObject.DefineVariable2("mFaktor", "C,10,0");

			if (m_CurrLoaStunden)
			{
				HostObject.Set("mStunden", "$[mStundenLohnart!0]", true);
				HostObject.Set("mBetrag", "$[mCurrLoaBrutto]", true);
				if (HostObject.EvalString("$[mCurrLoaFaktor]") != "1,00")
					HostObject.Set("mFaktor", "$[mCurrLoaFaktor]", true);
			}
			else
			{
				HostObject.Set("mBetrag", "$[mCurrLoaBetrag]", true);
				HostObject.Set("mFaktor", "$[mAnzahlLohnart]", true);
			}

			HostObject.CheckPageSpace(1);
			HostObject.ProcessResource("SummeLohnart");

			HostObject.VariablesPop();
		}

		void SUB_SummeAnnr()
		{
			HostObject.CheckPageSpace(1);
			HostObject.ProcessResource("SummeAnnr");
		}

		void SUB_SummeGesamt()
		{
			HostObject.CheckPageSpace(2);
			HostObject.ProcessResource("SummeGesamt");
		}

		#endregion
	}
}
