using craftsReport.Interfaces;
using System;

namespace craftsReport.modules
{
	public class rbvjou_xbs : IReportModule, IReportModuleEvents
	{
		#region Members and Contructor

		private bool m_IsLastPage = false;

		public rbvjou_xbs()
		{
		}

		#endregion

		#region IReportModule

		public IReportHost HostObject { set; get; }

		// public string ResourceFileName { get { return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\rbvjou.res"; } }

		// Rechnungsausgangsbuch
		public bool Execute()
		{
            #region Filtervariablen

            if (!HostObject.IsVar("mRepTitle"))
				HostObject.DefineVariable2("mRepTitle", "c,250,0");
			if (HostObject.IsEmpty("mRepTitle"))
				HostObject.Set("mRepTitle", "Belegjournal", false);

			// -------------------------------------------------------------------------
			//  Prüfen der Übergabe von Filtervariablen
			if (!HostObject.IsVar("BelegArt"))
				HostObject.DefineVariable2("BelegArt", "u,2,0");
			if (!HostObject.IsVar("BisBelArt"))
				HostObject.DefineVariable2("BisBelArt", "u,2,0");
			if (!HostObject.IsVar("VonDatum"))
				HostObject.DefineVariable2("VonDatum", "u,10,0");
			if (!HostObject.IsVar("BisDatum"))
				HostObject.DefineVariable2("BisDatum", "u,10,0");
			if (!HostObject.IsVar("VonKnd"))
				HostObject.DefineVariable2("VonKnd", "u,15,0");
			if (!HostObject.IsVar("BisKnd"))
				HostObject.DefineVariable2("BisKnd", "u,15,0");
			if (!HostObject.IsVar("VonPrj"))
				HostObject.DefineVariable2("VonPrj", "u,8,0");
			if (!HostObject.IsVar("BisPrj"))
				HostObject.DefineVariable2("BisPrj", "u,8,0");
			if (!HostObject.IsVar("UZ"))
				HostObject.DefineVariable2("UZ", "C,10,0");
			if (!HostObject.IsVar("phase"))
				HostObject.DefineVariable2("phase", "u,2,0");
			if (!HostObject.IsVar("offen"))
				HostObject.DefineVariable2("offen", "u,1,0");

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

			#endregion

			// SQL-Abfrage erstellen
			#region SqlQuery (Satznummernabfrage nach recSQLMain)
			// ---------------------------------------------------------------------------------
			System.Text.StringBuilder sbQuery = new System.Text.StringBuilder("SELECT RecId FROM ut_Belege");
			sbQuery.Append(" WHERE (BELEGART <> '20') AND (BELEGART <> '22')");

			string bsFilterText = "";
			string cVonValue = HostObject.GetVariable("BelegArt").Get().Trim();
			string cBisValue = HostObject.GetVariable("BisBelArt").Get().Trim();
			if (cVonValue != "")
            {
				if (cBisValue == "") cBisValue = cVonValue;
				/* alte Rechnungslogik
				if (cVonValue == "10")
                {
					cVonValue = "1";
					cBisValue = "4";
				}
				*/
				sbQuery.AppendFormat(" AND (BELEGART >= '{0}') AND (BELEGART <= '{1}')", cVonValue.PadLeft(2), cBisValue.PadLeft(2));
				bsFilterText += cVonValue + ".." + cBisValue;
			}

			cVonValue = HostObject.GetVariable("VonKnd").Get().TrimEnd();
			cBisValue = HostObject.GetVariable("BisKnd").Get().TrimEnd();
			if (cVonValue != "")
            {
				if (cBisValue == "") cBisValue = cVonValue;
				cVonValue = HostObject.FormatSqlString(cVonValue, false);
				cBisValue = HostObject.FormatSqlString(cBisValue, false);
				sbQuery.AppendFormat(" AND (KDNR >= {0}) AND (KDNR <= {1})", cVonValue, cBisValue);
				bsFilterText += (String.IsNullOrEmpty(bsFilterText) ? "" : "|") + cVonValue + ".." + cBisValue;
			}

			cVonValue = HostObject.GetVariable("VonPrj").Get().TrimEnd();
			cBisValue = HostObject.GetVariable("BisPrj").Get().TrimEnd();
			if (cVonValue != "")
			{
				if (cBisValue == "") cBisValue = cVonValue;
				cVonValue = HostObject.FormatSqlString(cVonValue, false);
				cBisValue = HostObject.FormatSqlString(cBisValue, false);
				sbQuery.AppendFormat(" AND (PRJNR >= {0}) AND (PRJNR <= {1})", cVonValue, cBisValue);
				bsFilterText += (String.IsNullOrEmpty(bsFilterText) ? "" : "|") + cVonValue + ".." + cBisValue;
			}

			cVonValue = HostObject.GetVariable("VonDatum").Get().TrimEnd();
			cBisValue = HostObject.GetVariable("BisDatum").Get().TrimEnd();
			if (cVonValue.Length >= 10)
			{
				if (cBisValue.Length < 10) cBisValue = cVonValue;
				cVonValue = HostObject.FormatSqlString(cVonValue.Substring(6, 4) + cVonValue.Substring(3, 2) + cVonValue.Substring(0, 2), false);
				cBisValue = HostObject.FormatSqlString(cBisValue.Substring(6, 4) + cBisValue.Substring(3, 2) + cBisValue.Substring(0, 2), false);
				sbQuery.AppendFormat(" AND ((JAHR+MONAT+TAG) >= {0}) AND ((JAHR+MONAT+TAG) <= {1})", cVonValue, cBisValue);
				bsFilterText += (String.IsNullOrEmpty(bsFilterText) ? "" : "|") + cVonValue + ".." + cBisValue;
			}

			cVonValue = HostObject.GetVariable("phase").Get().TrimEnd();
			if (cVonValue != "")
			{
				sbQuery.AppendFormat(" AND (BAUPHAAKT = {0})", HostObject.CastInt(cVonValue));
			}

			cVonValue = HostObject.GetVariable("UZ").Get().TrimEnd();
			if (cVonValue != "")
			{
				cVonValue = HostObject.FormatSqlString(cVonValue, false);
				sbQuery.AppendFormat(" AND (UZ = {0})", cVonValue);
			}

			cVonValue = HostObject.GetVariable("offen").Get().TrimEnd();
			if (cVonValue == "J")
			{
				sbQuery.AppendFormat(" AND (FERTIGJN = 0)");
			}

			sbQuery.Append(" ORDER BY JAHR, MONAT, TAG");
			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.Set("mFilterText", bsFilterText, false);

            #endregion

            #region Ausfuehrung

            HostObject.LoadAdditionalResources("/r");
			HostObject.PaperDefinition("PaperDefinition");
			HostObject.DefineVariable2("mSeiteZuvo", "N,4,0");

			HostObject.DefineVariable2("mWaehr", "u,3,0");
			HostObject.Set("mWaehr", @"EUR", true);

			//  Summen Netto/Ust
			HostObject.DefineVariable2("mSuN1", "d,14,2");
			HostObject.DefineVariable2("mSuU1", "d,14,2");
			//  Summen Brutto 
			HostObject.DefineVariable2("mSuB1", "d,14,2");

			HostObject.DefineRecord("recMAIN", "BELEGVERZEICHNIS", 0, 0, "");
			HostObject.DefineRecord("recZText", "ZUSATZTEXTE", 0, 0, "");
			HostObject.DefineRecord("recEUR", "WAEHRUNGEN", 1, 3, HostObject.EvalString(@"EUR"));
			if (HostObject.TestEof("recEUR"))
				HostObject.Set("recEUR.EUROKURS", @"1,00000", true);
			HostObject.DefineRecord("recDEM", "WAEHRUNGEN", 1, 3, HostObject.EvalString(@"DEM"));
			if (HostObject.TestEof("recDEM"))
				HostObject.Set("recDEM.EUROKURS", @"1,95883", true);
			//  Datensatzschleife OPTIONEN
			HostObject.DefineRecord("recOPT", "OPTIONEN", 0, 5, HostObject.EvalString(@" 7008"));
			if (HostObject.TestEof("recOPT"))
				HostObject.Set("recOPT.OPTDATAC", @"DEM", true);
			if (HostObject.IsEmpty("recOPT.OPTDATAC"))
				HostObject.Set("recOPT.OPTDATAC", @"DEM", true);
			HostObject.Set("mWaehr", @"$[recOPT.OPTDATAC]", true);
			HostObject.DefineRecord("recMWC", "WAEHRUNGEN", 1, 6, HostObject.EvalString(@"$[recOPT.OPTDATAC<6]"));
			if (HostObject.TestEof("recMWC"))
				HostObject.Set("recMWC.EUROKURS", @"1,00000", true);

			//  Kennzeichen fuer Gutschrift nicht invers
			HostObject.DefineRecord("recFS6246", "OPTIONEN", 0, 5, HostObject.EvalString(@" 6246"));

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

			//  Aufruf des Unterprogramms loopMAIN fuer jeden Datensatz
			while (!recSqlMain.Eof)
			{
				HostObject.SeekRecord("recMain", HostObject.CastInt(recSqlMain.GetI(1)));
				SUB_loopMAIN();
				recSqlMain.GoNext();
			}

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

			#endregion
		}

		#endregion

		#region IReportModuleEvents

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

			if (HostObject.EvalInt("$[Seite]") == 1)
			{
			}
			else
			{
				HostObject.Set("mSeiteZuvo", "$[Seite] - 1", true);
				HostObject.ProcessResource("Uebertrag");
			}
		}

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

		public void OnAfterExecute(string szOutFileName)
		{
		}

        #endregion

        #region Internals

        /// <summary>
        /// Wird für jeden Datensatz recMAIN abgearbeitet
        /// </summary>
        /// <returns></returns>
        bool SUB_loopMAIN()
		{
			//  Unterprogramm von ReportMain
			//  Datensatzschleife recMAIN
			HostObject.VariablesPush();

			//  Servicebericht Brutto ??
			if (!HostObject.CompareString("recMAIN.PHASE", "=", HostObject.EvalString(@"3B")))
				HostObject.VariablesPush();

			HostObject.DefineVariable2("mN1", "d,14,2");
			HostObject.DefineVariable2("mU1", "d,14,2");
			HostObject.DefineVariable2("mB1", "d,14,2");
			HostObject.DefineVariable2("mNummer", "C,10,0");
			HostObject.DefineVariable2("mDatum", "C,8,0");
			HostObject.DefineVariable2("mKunde", "C,30,0");

			HostObject.DefineRecord("recWAEHR", "WAEHRUNGEN", 1, 6, HostObject.EvalString(@"$[recMAIN.WAEHRUNG<6]"));
			if (HostObject.TestEof("recWAEHR"))
				HostObject.Set("recWAEHR.EUROKURS", @"1,00000", true);
			// **************************************************

			HostObject.Set("mN1", @"$[recMAIN.NETTO]  * ($[recMWC.EUROKURS] / $[recWAEHR.EUROKURS])", true);
			HostObject.Set("mU1", @"$[recMAIN.MWST]   * ($[recMWC.EUROKURS] / $[recWAEHR.EUROKURS])", true);
			HostObject.Set("mB1", @"$[recMAIN.BRUTTO] * ($[recEUR.EUROKURS] / $[recWAEHR.EUROKURS])", true);

			//  Vorzeichen fuer Gutschriftsbeleg umkehren
			if (HostObject.EvalBool("$[recFS6246.OptDataI] = 0"))
			{
				int nBelegArt = HostObject.EvalInt("$[recMAIN.BELEGART]");
				if ((nBelegArt % 10) == 2)
				{
					HostObject.Set("mN1", @"0-$[mN1]", true);
					HostObject.Set("mU1", @"0-$[mU1]", true);
					HostObject.Set("mB1", @"0-$[mB1]", true);
				}
			}

			string bsKey = "SYSPRJSTAT_" + HostObject.EvalInt("$[recMAIN.BAUPHAAKT]").ToString().PadLeft(2, '0');
			HostObject.FindRecord("recZText", bsKey);

			HostObject.CheckPageSpace(4);
			HostObject.ProcessResource("Detail");

			HostObject.Set("mSuN1", @"$[mSuN1]+$[mN1]", true);
			HostObject.Set("mSuU1", @"$[mSuU1]+$[mU1]", true);
			HostObject.Set("mSuB1", @"$[mSuB1]+$[mB1]", true);

			if (HostObject.EvalBool("$[Zeile] < ($[ZlMax]-1)"))
				HostObject.ProcessResource("Line");

			return HostObject.VariablesPop();
		}

		#endregion
	}
}
