@using PantheonRA.BackOffice.Enums

<div class="modal inmodal fade" id="moveTipFiscalizationModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
            <div class="modal-body">
                <input id="MoveTipFiscalizationQid" hidden />
                <input id="MoveTipFiscalizationToPayAmount" hidden />
                <div class="form-horizontal form-md">
                    <div class="row">
                        <div class="col-xs-6 padding-left-none">
                            <h3>@Loc.TipFiscalization</h3>
                        </div>
                        <div class="col-xs-6 text-right">
                            <i class="fa fa-times clickable-icon" data-dismiss="modal" title="@Loc.Close"></i>
                        </div>
                    </div>
                    <div class="row">
                        <div id="moveTipFiscalizationContainer" class="project-list m-t-sm">
                            <table id="moveTipFiscalizationGrid" class="table advance-payment-modal-table">
                                <thead>
                                    <tr>
                                        <th width="15%">@Loc.Amount</th>
                                        <th width="15%">@Loc.Percent</th>
                                        <th width="15%" class="dt-head-center text-center">@Loc.PaymentMethod</th>
                                        <th width="35%">@Loc.Error</th>
                                        <th width="17%" class="dt-head-center text-center">@Loc.Fiscalized</th>
                                        <th width="3%" class="dt-head-center"></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr id="tr-tipFisc-0">
                                        <!-- Value -->
                                        <td class="serial-numbers-td">
                                            <input id="input-mtf-value-0"
                                                   type="text"
                                                   step="2"
                                                   placeholder="@Loc.Amount"
                                                   onchange="changeTipFiscValue(0)"
                                                   autocomplete="off"
                                                   class="form-control border-bottom-none text-right numberInput" />
                                        </td>
                                        <!-- Percent -->
                                        <td class="serial-numbers-td">
                                            <input id="input-mtf-percent-0"
                                                   type="text"
                                                   step="2"
                                                   placeholder="@Loc.Percent"
                                                   onchange="changeTipFiscPercent(0)"
                                                   autocomplete="off"
                                                   class="form-control border-bottom-none text-right numberInput" />
                                        </td>
                                        <!-- PayMet -->
                                        <td class="serial-numbers-td">
                                            <select id="input-mtf-payMet-0"
                                                    class="form-control border-bottom-none"
                                                    title="@Loc.PaymentMethod">
                                                @foreach (var item in ViewBag.PaymentTypes)
                                                {
                                                    <option value="@item.PaymentMethod">
                                                        @(item.PaymentMethod) - @(item.Name)
                                                    </option>
                                                }
                                            </select>
                                        </td>
                                        <!-- Error -->
                                        <td class="serial-numbers-td">
                                            <input id="input-mtf-error-0"
                                                   type="text"
                                                   autocomplete="off"
                                                   class="form-control border-bottom-none tipFiscInputDisabled"
                                                   disabled />
                                        </td>
                                        <!-- Fiscalized -->
                                        <td class="serial-numbers-td text-center">
                                            <input id="input-mtf-fiscalized-0"
                                                   class="tipFiscInputDisabled"
                                                   type="checkbox"
                                                   autocomplete="off"
                                                   disabled />
                                        </td>
                                        <!-- Action -->
                                        <td class="td-action">
                                            <p id="tipFiscAddBtn" class="btn btn btn-success" title="@Loc.AddPosition" onclick="saveMoveTipFisc(0, true)">
                                                <i class="far fa-plus cursor-pointer" aria-hidden="true"></i>
                                            </p>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer m-t-xs" id="fiscalizeTipFooter">
                <button id="fiscalizeTipsBtn" type="button" class="btn btn-primary" onclick="tryFiscalizeTips()" disabled><i class="fa fa-check m-r-xs"></i>@Loc.FiscalizeTip</button>
            </div>
        </div>
    </div>
</div>

<div hidden>
    <select id="mtf-payMethod-options"
            class="form-control border-bottom-none">
        @foreach (var item in ViewBag.PaymentTypes)
        {
            <option value="@item.PaymentMethod">
                @(item.PaymentMethod) - @(item.Name)
            </option>
        }
    </select>
</div>

<script>
    var allMoveTipFiscalizationItems = [];

    $(document).ready(function () {
        $('.modal-dialog').draggable();
    });

    function openMoveTipFiscalizationModal() {
        $("#MoveTipFiscalizationQid").val($("#Qid").val());
        if ($("#FiscalizeTip").val() === "True")
            $("#fiscalizeTipFooter").removeClass("hidden");
        else
            $("#fiscalizeTipFooter").addClass("hidden");
        getMoveTipFiscalizationData();

        if ($("#MoveType").val() === "@AuthorType.Wholesale")
            $("#MoveTipFiscalizationToPayAmount").val($("#ToPayAmount").text());
        else
            $("#MoveTipFiscalizationToPayAmount").val($("#ToPayAmount").val());

        $("#moveTipFiscalizationModal :input").prop("disabled", false);
        $(".tipFiscInputDisabled").prop("disabled", true);
        $("#moveTipFiscalizationModal").modal("show");
    }

    function getMoveTipFiscalizationData() {
        $.get("@Url.Action("GetMoveTipFiscalization", "Move")?moveQid=" + $("#MoveTipFiscalizationQid").val(), function (response) {
            if (response && response.length > 0) {
                var isAlreadyFiscalized = response.some(el => el.Fiscalised === true);
                if (isAlreadyFiscalized)
                    $('#moveTipFiscalizationGrid tbody tr').remove();
                else
                    $('#moveTipFiscalizationGrid tbody tr:not(:first)').remove();

                for (var i = 0; i < response.length; i++) {
                    addMoveTipFiscRow(response[i].AnQid, response[i].Value, response[i].Percent, response[i].PayMethod, response[i].Error, response[i].Fiscalised);
                }
            } else
                $("#fiscalizeTipsBtn").prop("disabled", true);
        });
    }

    function addMoveTipFiscRow(id, value, percent, payMet, err, isFiscalized) {
        $('#moveTipFiscalizationGrid > tbody:last-child').append(
            '<tr id="tr-tipFisc-' + id + '" class="sortable-row">' +
            '<td class="serial-numbers-td"><input class="form-control border-bottom-none numberInput text-right" id="input-mtf-value-' + id + '" value="' + value + '" onchange="changeTipFiscValue(' + id + ')" /></td>' +
            '<td class="serial-numbers-td"><input class="form-control border-bottom-none numberInput text-right" id="input-mtf-percent-' + id + '" value="' + percent + '" onchange="changeTipFiscPercent(' + id + ')" /></td>' +
            '<td class="serial-numbers-td"><select class="form-control border-bottom-none" id="input-mtf-payMet-' + id + '" value="' + payMet + '" onchange="saveMoveTipFisc(' + id + ')">' + $("#mtf-payMethod-options").html() + '</select></td>' +
            '<td class="serial-numbers-td"><input class="form-control border-bottom-none " id="input-mtf-error-' + id + '" value="' + err + '" disabled /></td>' +
            '<td class="serial-numbers-td text-center"><input class="border-bottom-none" id="input-mtf-fiscalized-' + id + '" value="' + isFiscalized + '" type="checkbox" ' + (isFiscalized == true ? 'checked' : '') + ' disabled /></td>' +
            '<td class="td-action"><button type="button" onclick="deleteTipFiscalization(\'' + id + '\')" class="btn btn-link editableInput"><span class="far fa-trash-alt"></span></button></td>' +
            '</tr>'
        );

        setDropdownSelectedValue("input-mtf-payMet-" + id, payMet, true);
        initializeNumberInputs();

        if (isFiscalized === true) {
            $("#tr-tipFisc-0 :input").prop("disabled", true);
            $("#tr-tipFisc-" + id + " :input").prop("disabled", true);
            $("#fiscalizeTipsBtn").prop("disabled", true);
            $("#tipFiscAddBtn").prop("disabled", true);
        } else
            $("#fiscalizeTipsBtn").prop("disabled", false);
    }

    async function saveMoveTipFisc(id, isNew) {
        var model = {
            AnQid: id,
            MoveQid: $("#MoveTipFiscalizationQid").val(),
            Value: $("#input-mtf-value-" + id).val(),
            Percent: $("#input-mtf-percent-" + id).val(),
            PayMethod: $("#input-mtf-payMet-" + id).val(),
        };

        $("#tipFiscAddBtn i").addClass("fa-spin fa-spinner").removeClass("fa-plus");

        var url = "@Url.Action("UpdateMoveTipFiscalization", "Move")";
        if (isNew === true)
            url = "@Url.Action("AddMoveTipFiscalization", "Move")";

        await fetch(url, {
            method: "POST",
            body: JSON.stringify(model),
            headers: { 'Content-Type': 'application/json' },
        }).then((response) => response.json()
        ).then(async (response) => {
            $("#tipFiscAddBtn i").removeClass("fa-spin fa-spinner").addClass("fa-plus");
            if (response && response > 0) {
                addMoveTipFiscRow(response, $("#input-mtf-value-" + id).val(), $("#input-mtf-percent-" + id).val(), $("#input-mtf-payMet-" + id).val(), "", false);
                $("#input-mtf-value-" + id).val(0);
                $("#input-mtf-percent-" + id).val(0);
                formatNumberInput($("#input-mtf-value-" + id));
                formatNumberInput($("#input-mtf-percent-" + id));
            }
        }).catch((error) => {
            $("#tipFiscAddBtn i").removeClass("fa-spin fa-spinner").addClass("fa-plus");
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: "@Loc.GeneralError",
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: "@Loc.Confirm",
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        });
    }

    function changeTipFiscValue(id) {
        var value = toNumber($("#input-mtf-value-" + id).val());
        var toPayAmount = toNumber($("#MoveTipFiscalizationToPayAmount").val());

            var percent = value / toPayAmount * 100;
            $("#input-mtf-percent-" + id).val(percent);
            formatNumberInput($("#input-mtf-percent-" + id));

        if (id !== 0) {
            saveMoveTipFisc(id, false);
        }
    }

    function changeTipFiscPercent(id) {
        var percent = toNumber($("#input-mtf-percent-" + id).val());
        var toPayAmount = toNumber($("#MoveTipFiscalizationToPayAmount").val());

        var value = toPayAmount / 100 * percent;
        $("#input-mtf-value-" + id).val(value);
        formatNumberInput($("#input-mtf-value-" + id));

        if (id !== 0) {
            saveMoveTipFisc(id, false);
        }
    }

    function deleteTipFiscalization(id) {
        $.get("@Url.Action("RemoveMoveTipFiscalization", "Move")?id=" + id, function (response) {
            if (response && response.IsDeleted === true) {
                $("#tr-tipFisc-" + id).remove();
                if ($('#moveTipFiscalizationGrid tbody tr').length <= 1)
                    $("#fiscalizeTipsBtn").prop("disabled", true);
            } else {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "alert",
                    text: "@Loc.GeneralError",
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: "@Loc.Confirm",
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            }
        });
    }

    function tryFiscalizeTips() {
        if ((!$("#FiscalCode").val() && $("#MoveType").val() === "@AuthorType.Wholesale") || (!$("#FiscalizationCode").val() && $("#MoveType").val() === "@AuthorType.POS")) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: "@Loc.InvoiceNotFiscalizedTipFiscalizationNotPossible",
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: "@Loc.Confirm",
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        } else if (!$("#DocTypeTipFiscalization").val() || $("#DocTypeTipFiscalization").val() === "") {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: "@Loc.TipFiscalizationNotPossibleMissingDocTypeReceipt",
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: "@Loc.Confirm",
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        } else {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "question",
                text: "@Loc.ReallyFiscalizeTip",
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: "@Loc.Confirm",
                        closeOnAction: true,
                        action: function () {
                            fiscalizeTips();
                        },
                        type: 'primary'
                    }
                ]
            });
        }
    }

    function fiscalizeTips() {
        $("#fiscalizeTipsBtn i").addClass("fa-spin fa-spinner").removeClass("fa-plus");

        $.get("@Url.Action("FiscalizeInvoice", "Move")?ackey=" + $("#AcKey").val() + "&isTip=true", function (response) {
            $("#fiscalizeTipsBtn i").removeClass("fa-spin fa-spinner").addClass("fa-plus");
            if (response && response.Success) {
                getMoveTipFiscalizationData();
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "success",
                    text: "@Loc.FiscalizationFinished",
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: "@Loc.Confirm",
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            } else {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "alert",
                    text: "@Loc.GeneralError",
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: "@Loc.Confirm",
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            }
        });
    }
</script>