@using PantheonRA.BackOffice.Enums
@using PAW.Contracts.Enums
@model PantheonRA.BackOffice.Models.PartialCancelInvoiceModalModel

<div class="modal inmodal fade" id="partialCancelInvoiceModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-partial-cancel" role="document">
        <div class="modal-content partialCancelInvoiceModalContent">
            <div class="modal-body partialCancelModalBody p-sm">
                @Html.HiddenFor(x => x.Type)
                @Html.HiddenFor(model => model.PartialCancelDefaultDecimalPlacesValue)
                @Html.HiddenFor(model => model.PartialCancelDefaultDecimalPlacesPrice)
                @Html.HiddenFor(model => model.PartialCancelDefaultDecimalPlacesQuantity)
                <div class="row border-bottom">
                    <div class="col-xs-5">
                        <div class="tabs-container">
                            <ul class="nav nav-tabs horizontal-menu">
                                <li class="active divided-tab-2"><a data-toggle="tab" href="#partialCancelTab" class="local-tab">@Loc.PartialCancelInvoice</a></li>
                                <li id="liSerialNumbersTab" class="divided-tab-2 hidden">
                                    <a data-toggle="tab" href="#serialNumbersTab" class="local-tab">@Loc.CancelSerialNumbers</a>
                                </li>
                            </ul>
                        </div>
                    </div>
                    <div class="col-xs-7 text-right">
                        <a class="btn-transparent m-r-xs" onclick="openUserManualHelpCancelInvoice()" title="@Loc.CheckSamples"><i class="fas fa-book-reader"></i></a>
                        <a class="btn-transparent m-r-xs" onclick="openPartialCancelHelp()" title="@Loc.CheckInstructions"><i class="fas fa-question clickable-icon"></i></a>
                        <i class="fa fa-times clickable-icon" data-dismiss="modal" title="@Loc.Close"></i>
                    </div>
                </div>
                <div class="row document-head">
                    <div class="col-xs-2 p-r-0">
                        <div class="form-group cancel-invoice-typeahead-container">
                            <label class="control-label">@Loc.BillNo</label>
                            <input id="partialCancelInvoiceAcKey" hidden />
                            <input class="form-control typeahead_3 search-input" id="partialCancelInvoiceAcKeyView" autocomplete="off" placeholder="@Loc.Search" />
                        </div>
                    </div>
                    <div class="col-xs-3 document-head-disabled-input">
                        <div class="form-group">
                            <label class="control-label">@(Model.Type == InvoiceType.Wholesale || Model.Type == InvoiceType.OrderBuyer ? Loc.Buyer : Loc.Supplier)</label>
                            <input class="form-control" id="partialCancelSubject" />
                        </div>
                    </div>
                    <div class="col-xs-3 document-head-disabled-input">
                        <div class="form-group">
                            <label class="control-label">@Loc.Driver</label>
                            <input class="form-control" id="partialCancelDriver" />
                        </div>
                    </div>
                    <div class="col-xs-2 document-head-disabled-input">
                        <div class="form-group">
                            <label class="control-label">@Loc.Date</label>
                            <input class="form-control datepicker" id="partialCancelDate" />
                        </div>
                    </div>
                    <div class="col-xs-2 document-head-disabled-input">
                        <div class="form-group">
                            <label class="control-label">@Loc.ForPayment</label>
                            <input class="form-control" step="@Model.PartialCancelDefaultDecimalPlacesValue" id="partialCancelForPay" />
                        </div>
                    </div>
                </div>
                <div class="tab-content">
                    <div id="partialCancelTab" class="tab-pane fade in active">
                        <div class="row m-t-sm">
                            <div class="col-xs-12">
                                <div class="project-list">
                                    <table id="partialCancelGrid" data-url="@Url.Action("PartialCancelMoveItemsList", "MoveItem")" class="list-table">
                                        <thead>
                                            <tr>
                                                <th width="5%"></th>
                                                <th width="5%">@Loc.PositionShort</th>
                                                <th width="20%">@Loc.Ident</th>
                                                <th width="40%">@Loc.Title</th>
                                                <th width="15%" class="dt-head-right">@Loc.Quantity</th>
                                                <th width="15%" class="dt-head-right">@Loc.Price</th>
                                            </tr>
                                        </thead>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div id="serialNumbersTab" class="tab-pane fade in">
                        <div class="row m-t-sm">
                            <div class="col-xs-12">
                                <div class="project-list">
                                    <table id="partialCancelSerialNumbersGrid" data-url="@Url.Action("GetByAcKey", "SerialNumbers")" class="list-table">
                                        <thead>
                                            <tr>
                                                <th width="6%"></th>
                                                <th width="15%">@Loc.Document</th>
                                                <th width="5%">@Loc.PositionShort</th>
                                                <th width="15%">@Loc.Subject</th>
                                                <th width="15%">@Loc.Ident</th>
                                                <th width="17%">@Loc.Title</th>
                                                <th width="5%">@Loc.Quantity</th>
                                                <th width="13%">@Loc.SerialNumberShort</th>
                                                <th width="10%">@Loc.DateDue</th>
                                            </tr>
                                        </thead>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <div class="row">
                    <div class="col-xs-10">
                        <div class="row text-left">
                            <div class="col-xs-9">
                                <div class="row">
                                    <div class="col-xs-6">
                                        <input type="checkbox" checked class="form-control js-switch partialCancelSwitch" id="partialCancelCreateNewDoc" />
                                        <label class="control-label m-l-xs">@Loc.CreateNewDocument</label>
                                    </div>
                                    @if (Model.Type == InvoiceType.Wholesale || Model.Type == InvoiceType.ReceivedBills || Model.Type == InvoiceType.OrderBuyer)
                                    {
                                        <div class="col-xs-6">
                                            <input type="checkbox" class="form-control js-switch partialCancelSwitch" id="partialCancelTransferDoc1" />
                                            <label class="control-label m-l-xs">@Loc.TransferLinkedDocument 1</label>
                                        </div>
                                        <div class="col-xs-6 m-t-xs">
                                            <input type="checkbox" class="form-control js-switch partialCancelSwitch" id="partialCancelDeleteConnections" />
                                            <label class="control-label m-l-xs">@Loc.DeleteConnectionsWithOrder</label>
                                        </div>
                                        <div class="col-xs-6 m-t-xs">
                                            <input type="checkbox" class="form-control js-switch partialCancelSwitch" id="partialCancelTransferDoc2" />
                                            <label class="control-label m-l-xs">@Loc.TransferLinkedDocument 2</label>
                                        </div>
                                    }
                                </div>
                            </div>
                            <div class="col-xs-3">
                                @if (Model.Type == InvoiceType.OrderBuyer)
                                {
                                    <label class="control-label">@Loc.DocTypeForCancel</label>
                                    <select id="partialCancelDocTypeSelect" class="form-control custom-select padding-left-none">
                                        @foreach (var item in ViewBag.DocumentTypes)
                                        {
                                            <option value="@item.Id">
                                                @item.Value
                                            </option>
                                        }
                                    </select>
                                }
                                <select type="text" class="form-control hidden" id="partialCancelCorrType">
                                    <option value="@CancelType.Corrective" selected>@Loc.CancelTypeCorrective</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="col-xs-2">
                        <button type="button" id="btnPartialCancelCreate" class="btn btn-primary" onclick="onPartialCancel()"><i class="fas fa-coins m-r-xs"></i>@Loc.CancelInvoice</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    var $partialCancelDataTable;
    var $partialCancelSerialNumbersDataTable;
    var selectedPartialCancelIdents = [];
    var selectedPartialCancelSerialNumbers = [];
    var invoiceHasCashExpenditureOrTransfer = false;

    $(document).ready(function () {
        var elems = Array.prototype.slice.call(document.querySelectorAll('.partialCancelSwitch'));
        elems.forEach(function (html) {
            var switchery = new Switchery(html, { size: 'small' });
        });

        var url = '@Url.Action("GetFilteredCancelInvoices", "CashRegister")';
        if ($("#Type").val() === '@InvoiceType.Wholesale')
            var url = '@Url.Action("GetFilteredCancelInvoices", "Wholesale")';
        else if ($("#Type").val() === '@InvoiceType.ReceivedBills')
            var url = '@Url.Action("GetFilteredCancelInvoices", "ReceivedBills")';
        else if ($("#Type").val() === '@InvoiceType.OrderBuyer')
            var url = '@Url.Action("GetFilteredCancelOrders", "Order")';

        var invoiceType = '@InvoiceType.Wholesale';
        if ($("#Type").val() === '@InvoiceType.ReceivedBills')
            invoiceType = '@InvoiceType.ReceivedBills';
        if ($("#Type").val() === '@InvoiceType.OrderBuyer')
            invoiceType = '@InvoiceType.OrderBuyer';

        initializeInvoiceTypeahead(url, $('#partialCancelInvoiceAcKeyView'), $("#partialCancelInvoiceAcKey"), invoiceType, $("#partialCancelDate"), null, null, function (item) {
            $("#partialCancelInvoiceAcKey").val(item.id);
            changePartialCancelInvoice();
            getPartialCancelInvoiceIdents();
            return { selected: true, value: item.name };
        });

        $('.partialCancelInvoiceModalContent').resizable({
            alsoResize: ".modal-partial-cancel",
            minHeight: 500
        });

        $('#partialCancelInvoiceModal .modal-dialog').draggable();

        $('#partialCancelInvoiceModal').on('show.bs.modal', function () {
            $(this).find('.partialCancelModalBody').css({
                'max-height': '100%',
                'min-height': '85%',
            });
        });

        $(".partialCancelInvoiceModalContent").resize(function () {
            jsRenderDataTable("partialCancelGrid", "partialCancelModalBody");
            jsRenderDataTable("partialCancelSerialNumbersGrid", "partialCancelModalBody");
        });
    });

    function openPartialCancelInvoice() {
        if ($("#Type").val() === '@InvoiceType.Wholesale' &&
            '@PantheonRA.BackOffice.CurrentUser.Localization' === '@Localization.Code.ME' &&
            ($("#DocTypeSelect option:selected").attr("data-fiscalize") === "True" ||
                $("#CanFiscalize").val() === "True" ||
                $("#CanFiscalize").val() === "true") &&
            !$("#FiscalNumber").val() &&
            !$("#FiscalNumber").val()) {

            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "error",
                text: "@Loc.CannotCancelDocumentBeforeFiscalize",
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: "@Loc.Confirm",
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });

            return;
        }

        $.get("@Url.Action("GetInvoiceAdvancePaymentCancelByAcKey", "Move")" + "?acKey=" + $("#AcKey").val(), function (response) {
            if (response && response.length > 0) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "question",
                    text: '@Loc.InvoiceAlreadyConnectedToReversedAdvancedPayment',
                    buttons: [
                        {
                            icon: 'fa fa-times',
                            text: '@Loc.No',
                            closeOnAction: true,
                            type: 'ghost'
                        },
                        {
                            icon: 'fa fa-check',
                            text: '@Loc.Yes',
                            action: function () {
                                partialCancelInvoiceModal();
                            },
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            } else
                partialCancelInvoiceModal();
        });
    }

    function partialCancelInvoiceModal() {
        $("#partialCancelTitle").text($("#Type").val() === '@InvoiceType.OrderBuyer' ? "@Loc.PartialCancelOrder" : "@Loc.PartialCancelInvoice");
        $("#partialCancelInvoiceAcKey").val($("#AcKey").val());
        $("#partialCancelInvoiceAcKeyView").val($("#AcKeyDisplay").val());
        $("#partialCancelDocTypeSelect").val($("#DocType").val());
        changePartialCancelInvoice();
        getPartialCancelInvoiceIdents();
        $("#partialCancelInvoiceModal").modal("show");
    }

    function getPartialCancelInvoiceIdents() {
        $.ajax({
            type: "POST",
            data: JSON.stringify({
                id: $("#partialCancelInvoiceAcKey").val()
            }),
            url: $("#Type").val() !== '@InvoiceType.OrderBuyer' ? $("#partialCancelGrid").attr('data-url') : "@Url.Action("PartialCancelOrderItemsList", "Order")",
            contentType: "application/json"
        }).done(function (response) {
            if (response && response.length > 0) {
                loadPartialCancelIdents(response);
                getPartialCancelInvoiceSerialNumbers();
            }
        });
    }

    function loadPartialCancelIdents(partialCancelIdents) {
        selectedPartialCancelIdents = [];
        $partialCancelDataTable = $('#partialCancelGrid');
        if ($.fn.dataTable.isDataTable('#partialCancelGrid'))
            $partialCancelDataTable.DataTable().destroy();

        $partialCancelDataTable.DataTable({
            serverSide: false,
            ajax: undefined,
            scroller: false,
            responsive: false,
            paging: false,
            info: false,
            data: partialCancelIdents,
            columns: [
                {
                    data: "",
                    className: 'dt-body-center',
                    render: function (data, type, full) {
                        selectedPartialCancelIdents.push({ AnNo: full.AnNo, Quantity: formatDisplay(6, full.Quantity, true), Price: formatDisplay(6, full.Price, true) });
                        return '<input class="ackey" id="selected-' + full.AnNo + '" onclick=selectedPartialCancelIdent("' + full.AnNo + '")  value="' + full.AnNo + '" type="checkbox" checked />'
                    }
                },
                { data: "AnNo" },
                { data: "Ident" },
                { data: "Name" },
                {
                    data: "Quantity",
                    render: function (data, type, full) {
                        return '<input class="form-control numberInput text-right" id="qty-' + full.AnNo + '" onchange=selectedPartialCancelIdent("' + full.AnNo + '") value="' + full.Quantity + '" data-maxQuantity="' + full.Quantity + '" step="@Model.PartialCancelDefaultDecimalPlacesQuantity" type="text" autocomplete="off" />'
                    },
                    className: 'dt-body-right'
                },
                {
                    data: "Price",
                    render: function (data, type, full) {
                        var price = full.Price;
                        if ($("#Type").val() === '@InvoiceType.POS')
                            price = full.NewRetailPrice;

                        return '<input class="form-control numberInput text-right" id="pcPrice-' + full.AnNo + '" value="' + price + '" step="@Model.PartialCancelDefaultDecimalPlacesPrice" type="text" autocomplete="off" readonly />'
                    },
                    className: 'dt-body-right'
                }
            ],
            initComplete: function (settings, json) {
                $partialCancelDataTable.DataTable().rows().recalcHeight().draw();
            }
        });

        initializeNumberInputs();
    }

    function validateInvoiceCancelSubjects() {
        if ((($("#Type").val() === '@InvoiceType.Wholesale')
            && ($("#partialCancelSubject").val() !== $("#ReceiverId").val() || $("#partialCancelDriver").val() !== $("#ThirdPartyId").val()))
            || ($("#Type").val() === '@InvoiceType.ReceivedBills'
                && ($("#partialCancelSubject").val() !== $("#SupplierId").val() || $("#partialCancelDriver").val() !== $("#DriverId").val()))
            || ($("#Type").val() === '@InvoiceType.OrderBuyer'
                && ($("#partialCancelSubject").val() !== $("#ConsigneeId").val() || $("#partialCancelDriver").val() !== $("#ReceiverId").val()))
            || ($("#Type").val() === '@InvoiceType.POS'
                && ($("#partialCancelSubject").val() !== $("#PartnerId").val()))) {

            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "error",
                text: "@Loc.FirstAndThirdPersonOnDocumentsDontMatch",
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: "@Loc.Confirm",
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }
    }

    function changePartialCancelInvoice() {
        var url = "@Url.Action("GetByAcKey", "Move")";
        if ($("#Type").val() === '@InvoiceType.OrderBuyer')
            url = "@Url.Action("GetByAcKey", "Order")";

        $.get(url + "?id=" + $("#partialCancelInvoiceAcKey").val(), function (data) {
            if (data) {
                if ($("#Type").val() === '@InvoiceType.ReceivedBills')
                    $("#partialCancelSubject").val(data.IssuerId);
                else if ($("#Type").val() === '@InvoiceType.OrderBuyer')
                    $("#partialCancelSubject").val(data.ConsigneeId);
                else
                    $("#partialCancelSubject").val(data.ReceiverId);

                if ($("#Type").val() === '@InvoiceType.OrderBuyer') {
                    $("#partialCancelDriver").val(data.ReceiverId);
                    $("#partialCancelForPay").val(data.ForPay);
                } else {
                    $("#partialCancelDriver").val(data.ThirdPartyId);
                    $("#partialCancelForPay").val(data.PriceWithVAT);
                }

                formatNumberInput($("#partialCancelForPay"));
                $("#partialCancelDate").datepicker('setDate', data.Date);
            }
        }).fail(function () {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: "@Loc.GeneralError",
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: "@Loc.Confirm",
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        });
    }

    function resetIdentQuantity(textLoc, anNo, index) {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "error",
            text: textLoc,
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: "@Loc.Confirm",
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });

        $("#qty-" + anNo).val(toNumber($("#qty-" + anNo).attr("data-maxQuantity")));
        formatNumberInput($("#qty-" + anNo));
        addPartialCancelIdentData(anNo, index);
    }

    function selectedPartialCancelIdent(anNo) {
        var index = selectedPartialCancelIdents.findIndex(x => x.AnNo === toNumber(anNo));

        if ($("#partialCancelSerialNumbersGrid").DataTable().data().any()) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "error",
                text: "@Loc.QuantityCannotBeDifferentThanSerialNumbersQuantity",
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: "@Loc.Confirm",
                        closeOnAction: true,
                        action: function () { $('.nav-tabs a[href="#serialNumbersTab"]').tab('show'); },
                        type: 'primary'
                    }
                ]
            });
            setSelectedPartialCancelIdentQty(anNo);
            return;
        }

        if ($("#selected-" + anNo).is(':checked')) {
            var maxQuantity = toNumber($("#qty-" + anNo).attr("data-maxQuantity"));
            if (maxQuantity < toNumber($("#qty-" + anNo).val())) {
                resetIdentQuantity("@Loc.EnteredQuantityIsTooLarge", anNo, index);
            } else if (toNumber($("#qty-" + anNo).val()) < 0) {
                resetIdentQuantity("@Loc.EnteredQuantityIsNegative", anNo, index);
            } else
                addPartialCancelIdentData(anNo, index);
        } else {
            if (index !== -1)
                selectedPartialCancelIdents.splice(index, 1);
        }
    }

    function addPartialCancelIdentData(anNo, index) {
        if (index !== -1) {
            selectedPartialCancelIdents[index].Quantity = formatDisplay(6, $("#qty-" + anNo).val(), true);
            selectedPartialCancelIdents[index].Price = formatDisplay(6, $("#pcPrice-" + anNo).val(), true);

            if (toNumber($("#qty-" + anNo).val()) === 0)
                $("#selected-" + anNo).attr("checked", false);
        } else {
            selectedPartialCancelIdents.push({
                AnNo: toNumber($("#selected-" + anNo).val()),
                Quantity: formatDisplay(6, $("#qty-" + anNo).val(), true),
                Price: formatDisplay(6, $("#pcPrice-" + anNo).val(), true),
            });
        }
    }

    function onPartialCancel() {
        $.get("@Url.Action("GetInvoiceAdvancePaymentConnections", "Move")" + "?acKey=" + $("#AcKey").val(), function (response) {
            if (response && response.length > 0) {
                $("#invoiceHasAdvancePaymentConnectionsModalTitle").text(stringFormat("@Loc.IRIS1006888DocumentHasAdvancePaymentCancel", $("#AcKeyDisplay").val()));
                $("#invoiceHasAdvancePaymentConnectionsModalMsg").text(stringFormat("@Loc.DocumentHasAdvancePaymentCancel", $("#AcKeyDisplay").val()));
                $("#continueInvoiceHasAdvancePaymentConnections").attr("onclick", "checkForCashExpenditureOrTransfer()");
                $("#cancelConnectionWithOriginalDocument").attr("onclick", "removeInvoiceAdvancePaymentConnections()");
                $("#invoiceHasAdvancePaymentConnectionsModal").modal("show");
            } else
                checkForCashExpenditureOrTransfer();
        });
    }

    function removeInvoiceAdvancePaymentConnections() {
        $.get("@Url.Action("RemoveInvoiceAdvancePaymentConnections", "Move")" + "?acKey=" + $("#AcKey").val(), function (response) {
            if (response)
                checkForCashExpenditureOrTransfer();
        });
    }

    function checkForCashExpenditureOrTransfer() {
        var type = $("#Type").val() === '@InvoiceType.ReceivedBills' ? '@AdvancePaymentMoveLinksType.Wholesale' : '@AdvancePaymentMoveLinksType.ReceivedBills';

        $.get("@Url.Action("InvoiceCheckForCashExpenditureOrTransfer", "Move")" + "?acKey=" + $("#AcKey").val() + "&type=" + type, function (response) {
            if (response === true) {
                $("#deleteWarningMessage").text(stringFormat("@Loc.AssociatedCashExpenditureOrTransfer", $("#AcKeyDisplay").val()));
                $("#deleteWarningModal").modal("show");
                $("#continueDeleteDocument").attr("onclick", "createPartialCancel()");
                $("#cancelDeleteDocument").attr("onclick", "");
                invoiceHasCashExpenditureOrTransfer = true;
            } else {
                invoiceHasCashExpenditureOrTransfer = false;
                createPartialCancel();
            }
        });
    }

    function openDeleteWarningHelp() {
        window.open('@SiteHelpAttributeHelper.GetHelpUrl(HelpIds.MoveHasConnectedAdvancePayment)', '_blank');
    }

    function createPartialCancel() {
        if (!$("#partialCancelCreateNewDoc").is(':checked')) {
            if (($("#Type").val() === '@InvoiceType.Wholesale'
                && ($("#partialCancelSubject").val() !== $("#ReceiverId").val() || $("#partialCancelDriver").val() !== $("#ThirdPartyId").val()))
                || ($("#Type").val() === '@InvoiceType.ReceivedBills'
                    && ($("#partialCancelSubject").val() !== $("#SupplierId").val() || $("#partialCancelDriver").val() !== $("#DriverId").val()))
                || ($("#Type").val() === '@InvoiceType.OrderBuyer'
                    && ($("#partialCancelSubject").val() !== $("#ConsigneeId").val() || $("#partialCancelDriver").val() !== $("#ReceiverId").val()))
                || ($("#Type").val() === '@InvoiceType.POS'
                    && ($("#partialCancelSubject").val() !== $("#PartnerId").val()))) {

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: "@Loc.FirstAndThirdPersonOnDocumentsDontMatch",
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: "@Loc.Confirm",
                            closeOnAction: true,
                            action: function () { return; },
                            type: 'primary'
                        }
                    ]
                });
            }
        }

        var url = '@Url.Action("PartialCancelInvoice", "Move")';
        if ($("#Type").val() === '@InvoiceType.OrderBuyer')
            url = '@Url.Action("PartialCancelOrder", "Order")';

        partialCancelSwapLoadingIcon(true, "btnPartialCancelCreate");
        $.post(url, {
            AcKey: $("#partialCancelCreateNewDoc").is(':checked') ? $("#partialCancelInvoiceAcKey").val() : $("#AcKey").val(),
            CancelFromAcKey: $("#partialCancelCreateNewDoc").is(':checked') ? "" : $("#partialCancelInvoiceAcKey").val(),
            CreateNewDoc: $("#partialCancelCreateNewDoc").is(':checked') ? "@Status.Active" : "@Status.Inactive",
            TransferDoc1: $("#Type").val() === '@InvoiceType.Wholesale' || $("#Type").val() === '@InvoiceType.ReceivedBills' ? ($("#partialCancelTransferDoc1").is(':checked') ? "@Status.Active" : "@Status.Inactive") : "",
            TransferDoc2: $("#Type").val() === '@InvoiceType.Wholesale' || $("#Type").val() === '@InvoiceType.ReceivedBills' ? ($("#partialCancelTransferDoc2").is(':checked') ? "@Status.Active" : "@Status.Inactive") : "",
            DeleteConnections: $("#Type").val() === '@InvoiceType.Wholesale' || $("#Type").val() === '@InvoiceType.ReceivedBills' ? ($("#partialCancelDeleteConnections").is(':checked') ? "@Status.Active" : "@Status.Inactive") : "",
            CorrType: $("#partialCancelCorrType option:selected").val(),
            CancelCash: invoiceHasCashExpenditureOrTransfer,
            PartialIdents: selectedPartialCancelIdents,
            PartialSerialNumbers: selectedPartialCancelSerialNumbers,
            DocType: $("#Type").val() === '@InvoiceType.OrderBuyer' ? $("#partialCancelDocTypeSelect option:selected").val() : ""
        }, function (data) {
            if (data.Success) {
                if ($("#Type").val() === '@InvoiceType.POS')
                    location.href = '@Url.Action("Index", "CashRegister")' + '?ackey=' + data.AcKey;
                else if ($("#Type").val() === '@InvoiceType.Wholesale')
                    location.href = '@Url.Action("Edit", "Wholesale")' + '?id=' + data.AcKey;
                else if ($("#Type").val() === '@InvoiceType.OrderBuyer')
                    location.href = '@Url.Action("EditBuyerOrder", "Order")' + '?id=' + data.AcKey;
                else
                    location.href = '@Url.Action("Edit", "ReceivedBills")' + '?id=' + data.AcKey;
            } else {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "alert",
                    text: data.Error,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: "@Loc.Confirm",
                            closeOnAction: true,
                            action: function () {
                                partialCancelSwapLoadingIcon(false, "btnPartialCancelCreate");
                                $("#partialCancelInvoiceModal").modal("hide")
                                if (data.Status === "24") {
                                    var costDrvElements = $(".costDrvSelect");
                                    if (costDrvElements && costDrvElements.length > 0) {
                                        costDrvElements.map(function () {
                                            if (this.value === "") {
                                                $(this).select2('focus');
                                            }
                                        })
                                    }
                                }
                            },
                            type: 'primary'
                        }
                    ]
                });
            }
        }, "json");
    }

    function openPartialCancelHelp() {
        if ($("#Type").val() === '@InvoiceType.POS')
            window.open($("#posPartialCancelHelp").val(), '_blank');
        else if ($("#Type").val() === '@InvoiceType.Wholesale')
            window.open('@SiteHelpAttributeHelper.GetHelpUrl(HelpIds.WholesaleCancel)', '_blank');
        else if ($("#Type").val() === '@InvoiceType.OrderBuyer')
            window.open('@SiteHelpAttributeHelper.GetHelpUrl(HelpIds.BuyerOrderCancel)', '_blank');
        else
            window.open('@SiteHelpAttributeHelper.GetHelpUrl(HelpIds.ReceivedBillsCancel)', '_blank');
    }

    function openUserManualHelpCancelInvoice() {
        if ($("#Type").val() === '@InvoiceType.POS')
            window.open($("#posPartialCancelUserManualHelp").val(), '_blank');
        else if ($("#Type").val() === '@InvoiceType.Wholesale')
            window.open('@SiteHelpAttributeHelper.GetHelpUrl(HelpIds.ExampleWholesaleCancel)', '_blank');
        else if ($("#Type").val() === '@InvoiceType.OrderBuyer')
            window.open('@SiteHelpAttributeHelper.GetHelpUrl(HelpIds.BuyerOrderCancel)', '_blank');
        else
            window.open('@SiteHelpAttributeHelper.GetHelpUrl(HelpIds.ExampleReceivedBillsCancel)', '_blank');
    }

    function partialCancelSwapLoadingIcon(loading, buttonId, icon) {
        var $button = $("#" + buttonId);
        var $buttonIcon = $button.find("i");
        var $buttonGroupButtons = $button.parent().find("button");

        if (loading) {
            $buttonIcon.removeClass(icon).addClass("fa fa-spinner fa-spin fa-fw");
            $buttonGroupButtons.attr("disabled", true);
        }
        else {
            $buttonIcon.removeClass("fa fa-spinner fa-spin fa-fw").addClass(icon);
            $buttonGroupButtons.removeAttr("disabled");
        }
    }

    function getPartialCancelInvoiceSerialNumbers() {
        if ($("#Type").val() !== '@InvoiceType.OrderBuyer') {
            $.ajax({
                type: "POST",
                data: JSON.stringify({
                    id: $("#partialCancelInvoiceAcKey").val()
                }),
                url: $("#partialCancelSerialNumbersGrid").attr('data-url'),
                contentType: "application/json"
            }).done(function (response) {
                if (response && response.length > 0) {
                    $("#liSerialNumbersTab").removeClass("hidden");
                    loadPartialCancelSerialNumbers(response);
                } else
                    $("#liSerialNumbersTab").addClass("hidden");
            });
        }
    }

    function loadPartialCancelSerialNumbers(partialCancelSerialNumbers) {
        selectedPartialCancelSerialNumbers = [];
        $partialCancelSerialNumbersDataTable = $('#partialCancelSerialNumbersGrid');
        if ($.fn.dataTable.isDataTable('#partialCancelSerialNumbersGrid'))
            $partialCancelSerialNumbersDataTable.DataTable().destroy();

        $partialCancelSerialNumbersDataTable.DataTable({
            serverSide: false,
            ajax: undefined,
            scroller: false,
            responsive: false,
            paging: false,
            info: false,
            data: partialCancelSerialNumbers,
            columns: [
                {
                    data: "",
                    className: 'dt-body-center',
                    render: function (data, type, full) {
                        selectedPartialCancelSerialNumbers.push({ AnNo: full.AnNo, Quantity: formatDisplay(6, full.Qty, true), SerialNo: full.SerialNo });
                        return '<input class="ackey" id="selectedSN-' + full.AnNo + '_' + full.SerialNo + '" onclick="selectedPartialCancelSN(\'' + full.AnNo + '\', \'' + full.SerialNo + '\')"  value="' + full.AnNo + '" type="checkbox" checked />'
                    }
                },
                { data: "AcKey" },
                { data: "AnNo" },
                { data: "Subject" },
                { data: "Ident" },
                { data: "IdentName" },
                {
                    data: "Qty",
                    className: 'dt-body-center',
                    render: function (data, type, full) {
                        return '<span class="control-label" id="qtySN-' + full.AnNo + '_' + full.SerialNo + '" />' + full.Qty + '</span'
                    }
                },
                { data: "SerialNo" },
                { data: "DateDue" }
            ],
            initComplete: function (settings, json) {
                $partialCancelSerialNumbersDataTable.DataTable().rows().recalcHeight().draw();
            }
        });

        initializeNumberInputs();
    }

    function selectedPartialCancelSN(anNo, serialNo) {
        var index = selectedPartialCancelSerialNumbers.findIndex(x => x.AnNo === toNumber(anNo) && x.SerialNo == serialNo);

        if ($("#selectedSN-" + anNo + "_" + serialNo).is(':checked')) {
            addPartialCancelSerialNumbersData(anNo, serialNo, index);
        } else {
            if (index !== -1)
                selectedPartialCancelSerialNumbers.splice(index, 1);
        }

        setSelectedPartialCancelIdentQty(anNo);
    }

    function addPartialCancelSerialNumbersData(anNo, serialNo, index) {
        if (index !== -1) {
            selectedPartialCancelSerialNumbers[index].Quantity = formatDisplay(6, $("#qtySN-" + anNo + "_" + serialNo).text(), true);
        } else {
            selectedPartialCancelSerialNumbers.push({
                AnNo: toNumber($("#selectedSN-" + anNo + "_" + serialNo).val()),
                Quantity: formatDisplay(6, $("#qtySN-" + anNo + "_" + serialNo).text(), true),
                SerialNo: serialNo
            });
        }
    }

    function setSelectedPartialCancelIdentQty(anNo) {
        var sum = selectedPartialCancelSerialNumbers.reduce(function (sum, serial) {
            if (serial.AnNo === toNumber(anNo))
                return sum + toNumber(serial.Quantity);
            else
                return sum;
        }, 0);

        $("#qty-" + toNumber(anNo)).val(sum);
        formatNumberInput($("#qty-" + anNo));

        var index = selectedPartialCancelIdents.findIndex(x => x.AnNo === toNumber(anNo));
        addPartialCancelIdentData(anNo, index);
    }
</script>
