@using Elwig.Helpers
@using RazorLight
@inherits TemplatePage<Elwig.Documents.CreditNote>
@model Elwig.Documents.CreditNote
@{ Layout = "BusinessDocument"; }
<link rel="stylesheet" href="file:///@Raw(Model.DocumentsPath)\CreditNote.css" />
<main>
    <h1>@Model.Title</h1>
    <table class="credit">
        <colgroup>
            <col style="width: 25mm;"/>
            <col style="width:  6mm;"/>
            <col style="width: 21mm;"/>
            <col style="width: 15mm;"/>
            <col style="width: 10mm;"/>
            <col style="width: 10mm;"/>
            <col style="width: 15mm;"/>
            <col style="width: 12mm;"/>
            <col style="width: 13mm;"/>
            <col style="width:  5mm;"/>
            <col style="width: 17mm;"/>
            <col style="width: 16mm;"/>
        </colgroup>
        <thead>
            <tr>
                <th rowspan="2" style="text-align: left;">Lieferschein-Nr.</th>
                <th rowspan="2" class="narrow">Pos.</th>
                <th rowspan="2" style="text-align: left;">Sorte</th>
                <th rowspan="2" style="text-align: left;">Attr./Bewirt.</th>
                <th colspan="2">Gradation</th>
                <th colspan="2">Flächenbindung</th>
                <th>Preis</th>
                <th class="narrow">Rbl.</th>
                <th class="narrow">Zu-/Abschläge</th>
                <th>Betrag</th>
            </tr>
            <tr>
                <th class="unit">[°Oe]</th>
                <th class="unit narrow">[°KMW]</th>
                <th class="unit" colspan="2">[kg]</th>
                <th class="unit">[@Model.CurrencySymbol/kg]</th>
                <th class="narrow unit">[%]</th>
                <th class="unit">[@Model.CurrencySymbol]</th>
                <th class="unit">[@Model.CurrencySymbol]</th>
            </tr>
        </thead>
        <tbody class="sum">
            @foreach (var p in Model.Data.Rows) {
                var rows = Math.Max(p.Buckets.Length, p.Modifiers.Length + 1);
                @for (int i = 0; i < rows; i++) {
                    <tr class="@(i == 0 ? "first" : "") @(rows == i + 1 ? "last" : "")">
                        @if (i == 0) {
                            <td rowspan="@rows">@p.LsNr</td>
                            <td rowspan="@rows" class="center narrow">@p.DPNr</td>
                            <td class="small">@p.Variety</td>
                            <td class="small">
                                @p.Attribute@(p.Attribute != null && p.Cultivation != null ? " / " : "")@p.Cultivation
                                @((p.Attribute != null || p.Cultivation != null) && p.QualId == "WEI" ? " / " : "")@Raw(p.QualId == "WEI" ? "<i>abgew.</i>" : "")
                            </td>
                            <td rowspan="@rows" class="center">@($"{p.Gradation.Oe:N0}")</td>
                            <td rowspan="@rows" class="center">@($"{p.Gradation.Kmw:N1}")</td>
                        }
                        @if (i > 0 && i <= p.Modifiers.Length) {
                            <td colspan="4" class="small mod">@p.Modifiers[i - 1]</td>
                        } else if (i > 0) {
                            <td colspan="4"></td>
                        }
                        @if (i < p.Buckets.Length) {
                            var bucket = p.Buckets[i];
                            <td class="small">@bucket.Name:</td>
                            <td class="number">@($"{bucket.Value:N0}")</td>
                            <td class="number">@($"{bucket.Price:N4}")</td>
                        } else {
                            <td></td>
                        }
                        @if (i == p.Buckets.Length - 1) {
                            var rebelMod = p.WeighingModifier * 100;
                            var totalMod = p.TotalModifiers ?? 0;
                            <td class="tiny center">@(rebelMod == 0 ? "-" : (Utils.GetSign(rebelMod) + $"{Math.Abs(rebelMod):0.0##}"))</td>
                            <td class="number@(totalMod == 0 ? " center" : "")">@(totalMod == 0 ? "-" : Utils.GetSign(totalMod) + $"{Math.Abs(totalMod):N2}")</td>
                            <td class="number">@($"{p.Amount:N2}")</td>
                        } else {
                            <td colspan="2"></td>
                        }
                    </tr>
                }
            }
        </tbody>
    </table>
    <div class="hint">
        Hinweis:<br/>
        Die Summe der Lieferungen und die Summe der anfal&shy;lenden Pönalen werden mit
        @Model.Payment?.Variant.Season.Precision Nach&shy;komma&shy;stellen berechnent,
        erst das Ergebnis wird kauf&shy;männisch auf 2 Nach&shy;komma&shy;stellen gerundet.
    </div>
    <table class="credit-sum">
        <colgroup>
            <col style="width: auto;"/>
            <col style="width:  5mm;"/>
            <col style="width: 30mm;"/>
        </colgroup>
        @{
            string FormatRow(string name, decimal? value, bool add = false, bool bold = false, bool subCat = false, bool noTopBorder = false) {
                return $"<tr class=\"{(!add && !noTopBorder ? "sum" : !add ? "large" : "")} {(bold ? "large bold" : "")}\">"
                     + $"<td class=\"{(subCat ? "small" : "")}\">{name}:</td>"
                     + $"<td class=\"number {(subCat ? "small" : "large")}\">{(value < 0 ? "–" : (add ? "+" : ""))}</td>"
                     + $"<td class=\"number {(subCat ? "small" : "large")}\">"
                     +   $"<span class=\"fleft\">{Model.CurrencySymbol}</span>{Math.Abs(value ?? 0):N2}</td>"
                     + $"</tr>\n";
            }
        }
        <tbody style="break-inside: avoid;">
            @{ var sum = Model.Data.Rows.Sum(p => p.Amount); }
            @if (Model.Payment == null) {
                @Raw(FormatRow("Gesamt", sum, bold: true, noTopBorder: true))
            } else {
                var noBorder = true;
                if (Model.Payment.NetAmount != Model.Payment.Amount) {
                    @Raw(FormatRow("Zwischensumme", Model.Payment.NetAmount, noTopBorder: noBorder))
                    noBorder = false;
                    @Raw(FormatRow(Model.MemberModifier, Model.Payment.Amount - Model.Payment.NetAmount, add: true))
                }
                if (Model.Credit == null) {
                    @Raw(FormatRow("Gesamtbetrag", Model.Payment.Amount, bold: true, noTopBorder: noBorder))
                    // TODO Mock VAT
                } else {
                    var hasPrev = Model.Credit.PrevNetAmount != null;
                    @Raw(FormatRow(hasPrev ? "Gesamtbetrag" : "Nettobetrag", Model.Credit.NetAmount, bold: true, noTopBorder: noBorder))
                    if (hasPrev) {
                        @Raw(FormatRow("Bisher berücksichtigt", -Model.Credit.PrevNetAmount, add: true))
                        @Raw(FormatRow("Nettobetrag", Model.Credit.NetAmount - (Model.Credit.PrevNetAmount ?? 0)))
                    }
                    @Raw(FormatRow($"Mehrwertsteuer ({Model.Credit.Vat * 100} %)", Model.Credit.VatAmount, add: true))
                    @Raw(FormatRow("Bruttobetrag", Model.Credit.GrossAmount, bold: true))
                }
            }
        </tbody>
        <tbody style="break-inside: avoid;">
            @{
                decimal penalty = 0;
                string? comment = null;
            }

            @if (Model.MemberUnderDeliveries != null && Model.MemberUnderDeliveries.Count() > 0) {
                <tr class="small">
                    <td colspan="2" style="padding-top: 5mm;">Anfallende Pönalen durch Unterlieferungen:</td>
                    <td></td>
                </tr>
                foreach (var u in Model.MemberUnderDeliveries) {
                    @Raw(FormatRow($"{u.Name} ({u.Kg:N0} kg)", u.Amount, add: true, subCat: true))
                    penalty += u.Amount;
                }
                penalty = Math.Round(penalty, 2, MidpointRounding.AwayFromZero);
            }
            @if (Model.MemberTotalUnderDelivery != 0) {
                @Raw(FormatRow("Unterlieferung (GA)", Model.MemberTotalUnderDelivery, add: true));
                penalty += Model.MemberTotalUnderDelivery;
            }
            @if (Model.MemberAutoBusinessSharesAmount != 0) {
                @Raw(FormatRow($"Autom. Nachz. von GA ({Model.MemberAutoBusinessShares})", Model.MemberAutoBusinessSharesAmount, add: true));
                penalty += Model.MemberAutoBusinessSharesAmount;
            }
            @if (Model.CustomPayment?.Amount != null) {
                comment = Model.CustomPayment.Comment;
                string text = (Model.CustomPayment.Amount.Value < 0 ? "Weitere Abzüge" : "Weitere Zuschläge") + (comment != null ? "*" : "");
                if (comment != null && comment!.Length <= 30) {
                    text = comment;
                    comment = null;
                }
                @Raw(FormatRow(text, Model.CustomPayment.Amount.Value, add: true));
                penalty += Model.CustomPayment.Amount.Value;
            }

            @if (Model.Credit == null) {
                @Raw(FormatRow("Auszahlungsbetrag", (Model.Payment?.Amount + penalty) ?? (sum + penalty), bold: true))
            } else {
                var diff = Model.Credit.Modifiers - penalty;
                if (diff != 0) {
                    @Raw(FormatRow(diff < 0 ? "Sonstige Abzüge" : "Sonstige Zuschläge", diff, add: true))
                }
                if (Model.Credit.PrevModifiers != null && Model.Credit.PrevModifiers != 0) {
                    @Raw(FormatRow("Bereits berücksichtigte Abzüge", -Model.Credit.PrevModifiers, add: true))
                }
                @Raw(FormatRow("Auszahlungsbetrag", Model.Credit.Amount, bold: true))
            }
        </tbody>
    </table>
    @if (comment != null) {
        <p>* @comment</p>
    }
    <p>Überweisung erfolgt auf Konto @(Elwig.Helpers.Utils.FormatIban(Model.Member.Iban ?? "-")).</p>
    <div style="margin-top: 1em;">
        @if (Model.Text != null) {
            <p class="custom">@Model.Text</p>
        }
    </div>
</main>
