using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using BeWo.Data.Access;

namespace SkmRheydt.Export
{
    public class SkmDiamantExporter
    {
        
        public static string CreateExportString(string[] pHeaderCaption, string[][] pContent)
        {
            if (pHeaderCaption != null && pHeaderCaption.Length > 1 && pHeaderCaption[0].Contains("Diamant"))
            {
                DateTime dt = DateTime.Now;

                DateTime.TryParse(pHeaderCaption[1], out dt);

                if (pHeaderCaption[0].Contains("Stammdaten"))
                {
                    return GetDebitorenString(dt);
                }
                else
                {
                    return GetAbrechnungenString(dt);
                }
            }

                
            return null;
        }

        public static String GetDebitorenString(DateTime date)
        {
            var dt = ExecuteQuery(GetDebitorenSql(date), date);

            StringBuilder sb = new StringBuilder();
            foreach (DataRow row in dt.Rows)
            {
                if (sb.Length > 0)
                {
                    sb.AppendLine();
                }
                for (int i = 0; i < row.ItemArray.Length; i++)
                {
                    if (i > 0)
                    {
                        sb.Append(",");
                    }
                    var item = row[i];
                    bool quote = i == 5 || i == 6 || i > 25;

                    if (quote)
                    {
                        sb.Append('"');
                        sb.Append(item);
                        sb.Append('"');
                    }
                    else
                    {
                        sb.Append(item);
                    }
                }
                
            }
            //Debitorenstamm
            //S,0, D,200001,,"Bezeichnung1","Bezeichnung2",,,1200,,,,,,,,,,,,,,,,,"Name1","Name2", "Name3","Straße","PLZ","Ort"
            return sb.ToString();
        }

        public static String GetAbrechnungenString(DateTime date)
        {
            StringBuilder sb = new StringBuilder();
            var s = GetMonatlicheAbrechnungLvrString(date);
            if (!String.IsNullOrWhiteSpace(s))
            {
                sb.Append(s);
            }
            if (sb.Length > 0)
                sb.AppendLine();

            s = GetAbschlagszahlungenString(date);
            if (!String.IsNullOrWhiteSpace(s))
            {
                sb.Append(s);
            }
            if (sb.Length > 0)
                sb.AppendLine();

            //s = GetSelbstzahlerString(date);
            //if (!String.IsNullOrWhiteSpace(s))
            //{
            //    sb.Append(s);
            //}
            
            return sb.ToString();
        }

        public static String GetMonatlicheAbrechnungLvrString(DateTime date)
        {
            var dt = ExecuteQuery(GetMonatlicheAbrechnungLvrSql(date), date);

            StringBuilder sb = new StringBuilder();
            foreach (DataRow row in dt.Rows)
            {
                if (sb.Length > 0)
                {
                    sb.AppendLine();
                }
                for (int i = 0; i < row.ItemArray.Length; i++)
                {
                    if (i > 0)
                    {
                        sb.Append(",");
                    }
                    var item = row[i];
                    bool quote = i == 15 || i == 38;

                    if (quote)
                    {
                        sb.Append('"');
                        sb.Append(item);
                        sb.Append('"');
                    }
                    else
                    {
                        sb.Append(item);
                    }
                }

            }
//F,0,050,,BEWO,DA,01012016,012016,iBelegNr1,Belegnr1,220001,,,,999.99, "Name AZ Abrechnung 01/2016 LVR",,,EUR,,,,,,,,,,,R,,,
//G,0,1695,,,-999.99,"Name AZ Abrechnung 01/2016 LVR",

            return sb.ToString();
        }

        public static String GetAbschlagszahlungenString(DateTime date)
        {
            var dt = ExecuteQuery(GetAbschlagszahlungenSql(date), date);

            StringBuilder sb = new StringBuilder();
            foreach (DataRow row in dt.Rows)
            {
                if (sb.Length > 0)
                {
                    sb.AppendLine();
                }
                for (int i = 0; i < row.ItemArray.Length; i++)
                {
                    if (i > 0)
                    {
                        sb.Append(",");
                    }
                    var item = row[i];
                    bool quote = i == 15 || i == 38;

                    if (quote)
                    {
                        sb.Append('"');
                        sb.Append(item);
                        sb.Append('"');
                    }
                    else
                    {
                        sb.Append(item);
                    }
                }

            }
            //F,0,050,,BEWO,DA,02012016,012016,iBelegNr2,Belegnr2,220001,,,,-888.88, "Name AZ Abschlagszahlung LVR 01/2016",,,EUR,,,,,,,,,,,R,,,
            //G,0,4473,,,888.88,"Name AZ Abschlagszahlung LVR 05/2016",

            return sb.ToString();
        }

        public static String GetSelbstzahlerString(DateTime date)
        {
            var dt = ExecuteQuery(GetSelbstzahlerSql(date), date);

            StringBuilder sb = new StringBuilder();
            foreach (DataRow row in dt.Rows)
            {
                if (sb.Length > 0)
                {
                    sb.AppendLine();
                }
                for (int i = 0; i < row.ItemArray.Length; i++)
                {
                    if (i > 0)
                    {
                        sb.Append(",");
                    }
                    var item = row[i];
                    bool quote = i == 15 || i == 38;

                    if (quote)
                    {
                        sb.Append('"');
                        sb.Append(item);
                        sb.Append('"');
                    }
                    else
                    {
                        sb.Append(item);
                    }
                }

            }
            return sb.ToString();
        }

        private static String GetDebitorenSql(DateTime date)
        {
            String sql = @"
SELECT
distinct
'S',
'0',
'D',
org.DebitorNumber,
null,
'',
'',
null,
null,
'1200',
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
org.`Name`,
'',
'',
a.Street,
a.PostalCode,
a.Town
FROM `organisation` org 
INNER JOIN `costbearer` cb ON org.`CostBearerOid` = cb.`Oid`
INNER JOIN costbearer2supportconcept cb2sc on cb2sc.CostBearerOID = cb.Oid
LEFT JOIN Address a on org.addressOid = a.oid 
WHERE org.isactive=1 
order by org.`Name`
";
            return sql;
        }

        private static String GetMonatlicheAbrechnungLvrSql(DateTime date)
        {
            String sql = @"
SELECT
'F',
'0',
'050',
null,
'BEWO',
'DA',
':Abrechnungsmonat',
':Periode',
GetNextBelegnr(),
GetNextBelegnr(),
c.DebitorNumber,
null,
null,
null,
IF(crpRateFactor.`CostRateValue` is null, ROUND((sr.`GeleisteteFLM` / 60) * (SELECT crp.`CostRateValue` FROM `costrateperiod` crp WHERE crp.`ObjectTid` = 22  AND crp.`CostRateType` = 0 AND crp.`ObjectOid` = cb2sc.`CostBearerOid` AND (crp.`EndDate` is null or crp.`EndDate` > ':Monat_Start') order by IF(crp.`EndDate` is null, MAKEDATE(9999,365),crp.`EndDate`) LIMIT 1 )),
		ROUND(ROUND((sr.`GeleisteteFLM` / 60), 2) * (SELECT crp.`CostRateValue` FROM `costrateperiod` crp WHERE crp.`ObjectTid` = 22  AND crp.`CostRateType` = 0 AND crp.`ObjectOid` = cb2sc.`CostBearerOid` AND (crp.`EndDate` is null or crp.`EndDate` > ':Monat_Start') order by IF(crp.`EndDate` is null, MAKEDATE(9999,365),crp.`EndDate`) LIMIT 1 ) * ((100 + crpRateFactor.`CostRateValue`)/100), 2)) AS 'Betrag',
CONCAT(p.`LastName`, ', ', p.`FirstName`, ' ', cb2sc.CustomerRefenrenceNumber, ' Abrechnung :PeriodeSlash ', org.Name) as 'Verwendung',
null,
null,
'EUR',
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
'R',
null,
null,
'G',
'0',
'1695',
null,
null,
-1 * IF(crpRateFactor.`CostRateValue` is null, ROUND((sr.`GeleisteteFLM` / 60) * (SELECT crp.`CostRateValue` FROM `costrateperiod` crp WHERE crp.`ObjectTid` = 22  AND crp.`CostRateType` = 0 AND crp.`ObjectOid` = cb2sc.`CostBearerOid` AND (crp.`EndDate` is null or crp.`EndDate` > ':Monat_Start') order by IF(crp.`EndDate` is null, MAKEDATE(9999,365),crp.`EndDate`) LIMIT 1 )),
		ROUND(ROUND((sr.`GeleisteteFLM` / 60), 2) * (SELECT crp.`CostRateValue` FROM `costrateperiod` crp WHERE crp.`ObjectTid` = 22  AND crp.`CostRateType` = 0 AND crp.`ObjectOid` = cb2sc.`CostBearerOid` AND (crp.`EndDate` is null or crp.`EndDate` > ':Monat_Start') order by IF(crp.`EndDate` is null, MAKEDATE(9999,365),crp.`EndDate`) LIMIT 1 ) * ((100 + crpRateFactor.`CostRateValue`)/100), 2)) AS 'Betrag2',
CONCAT(p.`LastName`, ', ', p.`FirstName`, ' ', cb2sc.CustomerRefenrenceNumber, ' Abrechnung :PeriodeSlash ', org.Name) as 'Verwendung2',
null
FROM `supportconcept` sc 
INNER JOIN `costbearer2supportconcept` cb2sc ON sc.`Oid` = cb2sc.`SupportConceptOid`
INNER JOIN `costbearer` cb ON cb2sc.`CostBearerOid` = cb.`Oid`
LEFT JOIN 
	(SELECT crp.`ObjectOid`, crp.`CostRateValue` FROM `costrateperiod` crp 
    WHERE crp.`ObjectTid` = 22  AND crp.`CostRateType` = 2 AND (crp.`EndDate` is null or crp.`EndDate` > NOW()))
    AS crpRateFactor ON crpRateFactor.`ObjectOid` = cb.`Oid`
INNER JOIN `organisation` org ON org.`CostBearerOid` = cb.`Oid`
INNER JOIN `customer` c ON sc.`CustomerOid` = c.`Oid`
INNER JOIN `person` p on c.`PersonOid` = p.`Oid` 
LEFT JOIN 
	(SELECT sr2.`CostBearer2SupportConceptOid`, SUM(sr2.`roundedduration` / IF(sr2.`GroupEmployeeCount` is null, 1, sr2.`GroupEmployeeCount`)) AS GeleisteteFLM FROM `servicerecord` sr2
    INNER JOIN `servicedescription` sd ON sr2.`ServiceDescriptionOid` = sd.`Oid`
    INNER JOIN `servicecategory` sc ON sd.`ServiceCategoryOid` = sc.`Oid`
    WHERE sr2.`StartDate` >= ':Monat_Start' AND sr2.`StartDate` < ':Monat_End' AND sc.`Billable` = 1 GROUP BY sr2.`CostBearer2SupportConceptOid`)
    AS sr ON sr.`CostBearer2SupportConceptOid` = cb2sc.`Oid`
WHERE c.`IsActive` = 1 AND sc.`IsActive` = 1
and (sr.`GeleisteteFLM` is not null)
ORDER BY p.`LastName`, p.`FirstName`, cb2sc.`ApprovedStartDate`
";

            return sql;
        }

        private static String GetAbschlagszahlungenSql(DateTime date)
        {
            String sql = @"
SELECT
'F',
'0',
'050',
null,
'BEWO',
'DA',
':Abrechnungsmonat',
':Periode',
GetNextBelegnr(),
GetNextBelegnr(),
c.DebitorNumber,
null,
null,
null,
-1 * ROUND(at.`GesamtBetrag`, 2) as 'Abschlagszahlungen',
CONCAT(p.`LastName`, ', ', p.`FirstName`, ' ', cb2sc.CustomerRefenrenceNumber, ' Abschlagszahlung :PeriodeSlash ', org.Name) as 'Verwendung',
null,
null,
'EUR',
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
'R',
null,
null,
'G',
'0',
'1696',
null,
null,
ROUND(at.`GesamtBetrag`, 2) as 'Abschlagszahlungen2',
CONCAT(p.`LastName`, ', ', p.`FirstName`, ' ', cb2sc.CustomerRefenrenceNumber, ' Abschlagszahlung :PeriodeSlash ', org.Name) as 'Verwendung2',
null
FROM `supportconcept` sc 
INNER JOIN `costbearer2supportconcept` cb2sc ON sc.`Oid` = cb2sc.`SupportConceptOid`
INNER JOIN `costbearer` cb ON cb2sc.`CostBearerOid` = cb.`Oid`
LEFT JOIN 
	(SELECT crp.`ObjectOid`, crp.`CostRateValue` FROM `costrateperiod` crp 
    WHERE crp.`ObjectTid` = 22  AND crp.`CostRateType` = 2 AND (crp.`EndDate` is null or crp.`EndDate` > NOW()))
    AS crpRateFactor ON crpRateFactor.`ObjectOid` = cb.`Oid`
INNER JOIN `organisation` org ON org.`CostBearerOid` = cb.`Oid`
INNER JOIN `customer` c ON sc.`CustomerOid` = c.`Oid`
INNER JOIN `person` p on c.`PersonOid` = p.`Oid` 
LEFT JOIN 
	(SELECT at2.`CostBearer2SupportConceptOid`, SUM(at2.`Amount`) AS GesamtBetrag FROM `accountingtransaction` at2
    WHERE at2.`BookingDate` >= ':Monat_Start' AND at2.`BookingDate` < ':Monat_End' GROUP BY at2.`CostBearer2SupportConceptOid`)
    AS at ON at.`CostBearer2SupportConceptOid` = cb2sc.`Oid`
WHERE c.`IsActive` = 1 AND sc.`IsActive` = 1
and (at.`GesamtBetrag` is not null)
ORDER BY p.`LastName`, p.`FirstName`, cb2sc.`ApprovedStartDate`
";
            return sql;
        }

        private static String GetSelbstzahlerSql(DateTime date)
        {
            String sql = @"
SELECT
'F',
'0',
'050',
null,
'BEWO',
'DA',
':Abrechnungsmonat',
':Periode',
GetNextBelegnr(),
GetNextBelegnr(),
c.DebitorNumber,
null,
null,
null,
IF(crpRateFactor.`CostRateValue` is null, ROUND((sr.`GeleisteteFLM` / 60) * (SELECT crp.`CostRateValue` FROM `costrateperiod` crp WHERE crp.`ObjectTid` = 22  AND crp.`CostRateType` = 0 AND crp.`ObjectOid` = cb2sc.`CostBearerOid` AND (crp.`EndDate` is null or crp.`EndDate` > ':Monat_Start') order by IF(crp.`EndDate` is null, MAKEDATE(9999,365),crp.`EndDate`) LIMIT 1 )),
		ROUND(ROUND((sr.`GeleisteteFLM` / 60), 2) * (SELECT crp.`CostRateValue` FROM `costrateperiod` crp WHERE crp.`ObjectTid` = 22  AND crp.`CostRateType` = 0 AND crp.`ObjectOid` = cb2sc.`CostBearerOid` AND (crp.`EndDate` is null or crp.`EndDate` > ':Monat_Start') order by IF(crp.`EndDate` is null, MAKEDATE(9999,365),crp.`EndDate`) LIMIT 1 ) * ((100 + crpRateFactor.`CostRateValue`)/100), 2)) AS 'Betrag',
CONCAT(p.`LastName`, ', ', p.`FirstName`, ' ', cb2sc.CustomerRefenrenceNumber, ' Abrechnung :PeriodeSlash ', org.Name) as 'Verwendung',
null,
null,
'EUR',
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
'R',
null,
null,
'G',
'0',
'1695',
null,
null,
-1 * IF(crpRateFactor.`CostRateValue` is null, ROUND((sr.`GeleisteteFLM` / 60) * (SELECT crp.`CostRateValue` FROM `costrateperiod` crp WHERE crp.`ObjectTid` = 22  AND crp.`CostRateType` = 0 AND crp.`ObjectOid` = cb2sc.`CostBearerOid` AND (crp.`EndDate` is null or crp.`EndDate` > ':Monat_Start') order by IF(crp.`EndDate` is null, MAKEDATE(9999,365),crp.`EndDate`) LIMIT 1 )),
		ROUND(ROUND((sr.`GeleisteteFLM` / 60), 2) * (SELECT crp.`CostRateValue` FROM `costrateperiod` crp WHERE crp.`ObjectTid` = 22  AND crp.`CostRateType` = 0 AND crp.`ObjectOid` = cb2sc.`CostBearerOid` AND (crp.`EndDate` is null or crp.`EndDate` > ':Monat_Start') order by IF(crp.`EndDate` is null, MAKEDATE(9999,365),crp.`EndDate`) LIMIT 1 ) * ((100 + crpRateFactor.`CostRateValue`)/100), 2)) AS 'Betrag2',
CONCAT(p.`LastName`, ', ', p.`FirstName`, ' ', cb2sc.CustomerRefenrenceNumber, ' Abrechnung :PeriodeSlash ', org.Name) as 'Verwendung2',
null
FROM `supportconcept` sc 
INNER JOIN `costbearer2supportconcept` cb2sc ON sc.`Oid` = cb2sc.`SupportConceptOid`
INNER JOIN `costbearer` cb ON cb2sc.`CostBearerOid` = cb.`Oid`
LEFT JOIN 
	(SELECT crp.`ObjectOid`, crp.`CostRateValue` FROM `costrateperiod` crp 
    WHERE crp.`ObjectTid` = 22  AND crp.`CostRateType` = 2 AND (crp.`EndDate` is null or crp.`EndDate` > NOW()))
    AS crpRateFactor ON crpRateFactor.`ObjectOid` = cb.`Oid`
INNER JOIN `organisation` org ON org.`CostBearerOid` = cb.`Oid`
INNER JOIN `customer` c ON sc.`CustomerOid` = c.`Oid`
INNER JOIN `person` p on c.`PersonOid` = p.`Oid` 
LEFT JOIN 
	(SELECT sr2.`CostBearer2SupportConceptOid`, SUM(sr2.`roundedduration` / IF(sr2.`GroupEmployeeCount` is null, 1, sr2.`GroupEmployeeCount`)) AS GeleisteteFLM FROM `servicerecord` sr2
    INNER JOIN `servicedescription` sd ON sr2.`ServiceDescriptionOid` = sd.`Oid`
    INNER JOIN `servicecategory` sc ON sd.`ServiceCategoryOid` = sc.`Oid`
    WHERE sr2.`StartDate` >= ':Monat_Start' AND sr2.`StartDate` < ':Monat_End' AND sc.`Billable` = 1 GROUP BY sr2.`CostBearer2SupportConceptOid`)
    AS sr ON sr.`CostBearer2SupportConceptOid` = cb2sc.`Oid`
WHERE c.`IsActive` = 1 AND sc.`IsActive` = 1
and (sr.`GeleisteteFLM` is not null)
ORDER BY p.`LastName`, p.`FirstName`, cb2sc.`ApprovedStartDate`
";

            return sql;
        }

        public static DataTable ExecuteQuery(String sql, DateTime dt)
        {
            var newsql = sql;
            newsql = newsql.Replace(":PeriodeSlash", String.Format("{0:MM/yyyy}", dt));
            newsql = newsql.Replace(":Periode", String.Format("{0:MMyyyy}", dt));
            newsql = newsql.Replace(":Abrechnungsmonat", String.Format("{0:ddMMyyyy}", dt));
            newsql = newsql.Replace(":Monat_Start", String.Format("{0:yyyy-MM}-01", dt));
            dt = dt.AddMonths(1);
            newsql = newsql.Replace(":Monat_End", String.Format("{0:yyyy-MM}-01", dt));

            return DAOFactory.AdoDAO.ExecuteQuery(newsql).Tables[0];
        }

        


        //Buchung Abrechnung Stundenzettel
        //F,0,050,, BEWO, DA,01012016,012016, iBelegNr1, Belegnr1,220001,,,,999.99, "Name AZ Abrechnung 01/2016 LVR",,, EUR,,,,,,,,,,, R,,,
        //G,0,1695,,,-999.99,"Name AZ Abrechnung 01/2016 LVR",



        //Buchung Abschlagszahlung
        //F,0,050,, BEWO, DA,02012016,012016, iBelegNr2, Belegnr2,220001,,,,-888.88, "Name AZ Abschlagszahlung LVR 01/2016",,, EUR,,,,,,,,,,, R,,,
        //G,0,4473,,,888.88,"Name AZ Abschlagszahlung LVR 05/2016",


        //Buchung Abrechnung LVR / Selbstzahler
        //F,0,050,, BEWO, DA,01022016,022016, iBelegNr3, Belegnr3,220001,,,,900.00, "Name AZ Abrechnung LVR + SZ 02/2016",,, EUR,,,,,,,,,,, R,,,
        //G,0,1695,,,-800.00,"Name AZ Abrechnung 05/2016 LVR",
        //G,0,1695,,,-100.00,"Name AZ Abrechnung 05/2016 SZ",



        //schwarz = konstant
        //rot = variabel


    }
}