@using PantheonRA.BackOffice.Enums
@using PAW.Contracts.Enums

<div class="modal inmodal fade" id="connectDocWizardModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-xxl modal-connect-documents" role="document">
        <div class="modal-content connectDocWizardModalContent">
            <div class="modal-body connectDocWizardModalBody p-sm">
                @Html.Hidden("MoveConnectionType")
                @Html.Hidden("MoveConnectAcKey")
                @Html.Hidden("MoveConnectAcKeyDisplay")
                @Html.Hidden("MoveConnectFromAcKey")
                @Html.Hidden("MoveConnectSubject")
                @Html.Hidden("MoveConnectThirdParty")
                <div class="row border-bottom">
                    <div class="col-xs-10">
                        <h4 class="m-t-xs m-b-xs" id="connectDocWizardTitle"></h4>
                    </div>
                    <div class="col-xs-2 text-right">
                        <a class="btn-transparent m-r-xs" onclick="openUserManualHelpConnectDoc()" title="@Loc.CheckSamples"><i class="fas fa-book-reader"></i></a>
                        <a class="btn-transparent m-r-xs" href="@SiteHelpAttributeHelper.GetHelpUrl(HelpIds.MoveDocumentConnect)" target="_blank" title="@Loc.CheckInstructions"><i class="fas fa-question clickable-icon"></i></a>
                        <i class="fa fa-times pull-right clickable-icon m-t-xs m-b-xs" data-dismiss="modal" title="@Loc.Close"></i>
                    </div>
                </div>

                <div class="row document-head">
                    <div class="col-xs-2">
                        <div class="form-group">
                            <label class="control-label">@Loc.ConnectionType</label>
                            <select id="moveDocumentConnectionType" class="form-control">
                                @if (PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.ME)
                                {
                                    <option value="@MoveDocumentConnectionType.Document">@Loc.ConnectDocumentHead</option>
                                }
                                <option value="@MoveDocumentConnectionType.Items">@Loc.ConnectDocumentItems</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-xs-2">
                        <div class="form-group">
                            <label class="control-label">@Loc.DateFrom</label>
                            <div class="input-group">
                                <span class="input-group-addon">
                                    <i class="far fa-calendar alt"></i>
                                </span>
                                <input class="form-control datepicker datepicker-connWizard" id="moveConnectDateFrom" />
                            </div>
                        </div>
                    </div>
                    <div class="col-xs-2">
                        <div class="form-group">
                            <label class="control-label">@Loc.DateTo</label>
                            <div class="input-group">
                                <span class="input-group-addon">
                                    <i class="far fa-calendar alt"></i>
                                </span>
                                <input class="form-control datepicker datepicker-connWizard" id="moveConnectDateTo" />
                            </div>
                        </div>
                    </div>
                    <div class="col-xs-2" id="sameItemsOnlyContainer">
                        <div class="form-group">
                            <div class="row">
                                <label class="control-label col-xs-12 p-b-5">@Loc.SameItemsOnly</label>
                                <div class="col-xs-12">
                                    <input type="checkbox" class="form-control js-switch moveConnectSwitch" id="moveConnectSameItemsOnly" />
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-xs-2 document-head-disabled-input">
                        <div class="form-group">
                            <label id="moveConnectBuyerLabel" class="control-label">@Loc.Buyer</label>
                            <input class="form-control" id="moveConnectBuyer" />
                        </div>
                    </div>
                    <div class="col-xs-2 document-head-disabled-input">
                        <div class="form-group">
                            <label id="moveConnectRecipientLabel" class="control-label">@Loc.Recipient</label>
                            <input class="form-control" id="moveConnectRecipient" />
                        </div>
                    </div>
                </div>

                <div id="connectDocumentHeadContainer" class="row" hidden>
                    <div class="col-xs-12">
                        <div class="project-list m-t-xs">
                            <table id="moveConnectDocumentHeadGrid" class="list-table">
                                <thead>
                                    <tr>
                                        <th width="5%" class="dt-head-center"></th>
                                        <th width="40%">@Loc.Document</th>
                                        <th width="15%" class="dt-head-right">@Loc.Amount</th>
                                    </tr>
                                </thead>
                            </table>
                        </div>
                    </div>
                </div>

                <div id="connectDocumentItemsContainer" class="row">
                    <div class="col-xs-6">
                        <div class="row">
                            <div class="form-group">
                                <label class="control-label col-xs-4 m-t-xs">@Loc.SelectedDocument</label>
                                <div class="col-xs-8 p-l-0">
                                    <input id="moveConnectFromAcKeyDisplay" class="form-control" disabled />
                                </div>
                            </div>
                        </div>
                        <div class="project-list m-t-xs">
                            <table id="moveConnectDocumentItemsGrid" data-url="@Url.Action("MoveItemsList", "MoveItem")" class="list-table">
                                <thead>
                                    <tr>
                                        <th width="5%">@Loc.PositionShort</th>
                                        <th width="40%">@Loc.Ident</th>
                                        <th width="40%">@Loc.Title</th>
                                        <th width="15%" class="dt-head-right">@Loc.Quantity</th>
                                    </tr>
                                </thead>
                            </table>
                        </div>
                    </div>
                    <div class="col-xs-6">
                        <div class="row">
                            <div class="form-group">
                                <label class="control-label col-xs-4 p-r-0 m-t-xs">@Loc.ConnectedDocument</label>
                                <div class="col-xs-8 p-l-0">
                                    <input id="moveConnectAcKeyTypeahead" class="form-control typeahead_3 typeahead_wide" autocomplete="off" />
                                </div>
                            </div>
                        </div>
                        <div class="project-list m-t-xs">
                            <table id="moveDocumentSelectedItemsGrid" data-url="@Url.Action("MoveItemsList", "MoveItem")" data-height="calc(100vh - 330px)" class="list-table">
                                <thead>
                                    <tr>
                                        <th width="10%">@Loc.Document</th>
                                        <th width="5%">@Loc.PositionShort</th>
                                        <th width="30%">@Loc.Ident</th>
                                        <th width="40%">@Loc.Title</th>
                                        <th width="15%" class="dt-head-right">@Loc.Quantity</th>
                                    </tr>
                                </thead>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button id="connectMoveDocBtn" type="button" class="btn btn-primary" onclick="ConnectMoveDocuments()"><i class="m-r-xs"></i>@Loc.Connect</button>
            </div>
        </div>
    </div>
</div>

<script>
    var $moveConnectDocumentDataTable;
    var $moveDocumentSelectedDataTable;
    var selectedDocumentIdents = [];
    var selectedDocumentHeadItems = [];
    var originalDocumentIdents = [];
    var connectDocumentIdents = [];

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

        $(".datepicker-connWizard").on("change", function () {
            getDocumentHeadInvoices();
        });

        $("#moveConnectSameItemsOnly").on("change", function () {
            getSelectedDocumentInvoiceIdents();
        });

        $("#moveDocumentConnectionType").on("change", function () {
            if ($("#moveDocumentConnectionType option:selected").val() === "@MoveDocumentConnectionType.Document") {
                $("#connectDocumentHeadContainer").prop("hidden", false);
                $("#connectDocumentItemsContainer").prop("hidden", true);
                $("#sameItemsOnlyContainer").prop("hidden", true);
                $("#moveConnectBuyer").val($("#MoveConnectSubject").val());
                $("#moveConnectRecipient").val($("#MoveConnectThirdParty").val());
                getDocumentHeadInvoices();
            } else {
                $("#connectDocumentHeadContainer").prop("hidden", true);
                $("#connectDocumentItemsContainer").prop("hidden", false);
                $("#sameItemsOnlyContainer").prop("hidden", false);
                $("#moveConnectBuyer").val("");
                $("#moveConnectRecipient").val("");
            }
        });

        $('.connectDocWizardModalContent').resizable({
            alsoResize: ".modal-connect-documents",
            minHeight: 500
        });

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

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

        $(".connectDocWizardModalContent").resize(function () {
            jsRenderDataTable("moveConnectDocumentItemsGrid", "connectDocWizardModalBody");
            jsRenderDataTable("moveDocumentSelectedItemsGrid", "connectDocWizardModalBody");
            jsRenderDataTable("moveConnectDocumentHeadGrid", "connectDocWizardModalBody");
        });
    });

    function setTitle() {
        $("#connectDocWizardTitle").text(stringFormat("@Loc.ConnectDocumentsWith", $("#MoveConnectAcKeyDisplay").val()));
    }

    function initConnectDocumentWizardTypeaheads() {
        var url = '@Url.Action("GetFiltered", "Move")';
        if ($("#AcKey").val())
            var url = '@Url.Action("GetAvailableMoveConnections", "Move")?SubjectId=' + encodeURIComponent($("#MoveConnectSubject").val())
                + '&ThirdPartyId=' + encodeURIComponent($("#MoveConnectThirdParty").val())
                + '&AcKey=' + $("#MoveConnectAcKey").val()
                + '&MoveType=' + $("#MoveConnectionType").val();

        initializeInvoiceTypeahead(
            url,
            $('#moveConnectAcKeyTypeahead'),
            $("#MoveConnectFromAcKey"),
            $("#MoveConnectionType").val() === '@DtType.Wholesale' ? '@InvoiceType.Wholesale' : '@InvoiceType.ReceivedBills',
            $("#moveConnectDateFrom"), $("#moveConnectDateTo"),
            null,
            function (item) {
                $("#MoveConnectFromAcKey").val(item.id);
                $("#moveConnectBuyer").val($("#MoveConnectionType").val() === '@DtType.ReceivedBills' ? item.issuer : item.receiver);
                $("#moveConnectRecipient").val(item.prsn3);
                getSelectedDocumentInvoiceIdents();
                return { selected: true, value: item.name };
            });
    }

    function openConnectDocWizardModal() {
        if ($("#MoveConnectionType").val() === '@DtType.ReceivedBills') {
            $("#moveConnectBuyerLabel").text("@Loc.Supplier");
            $("#moveConnectRecipientLabel").text("@Loc.Driver");
        }

        setTitle();
        initConnectDocumentWizardTypeaheads();
        getDocumentConnectInvoiceIdents();
        resetForm();
        $("#moveConnectFromAcKeyDisplay").val($("#MoveConnectAcKeyDisplay").val());
        var date = new Date();
        $("#moveConnectDateTo").datepicker('setDate', 'now');
        $("#moveConnectDateFrom").datepicker("setDate", new Date(date.getFullYear(), date.getMonth() - 1, date.getDate()));
        $("#moveDocumentConnectionType").trigger("change");
        $("#connectDocWizardModal").modal("show");
    }

    function resetForm() {
        $("#moveConnectAcKeyTypeahead").val("");
        $("#moveConnectBuyer").val("");
        $("#moveConnectRecipient").val("");
        if ($.fn.dataTable.isDataTable('#moveDocumentSelectedItemsGrid'))
            $('#moveDocumentSelectedItemsGrid').DataTable().clear().draw();
    }

    function getDocumentConnectInvoiceIdents() {
        $.ajax({
            type: "POST",
            data: JSON.stringify({
                id: $("#MoveConnectAcKey").val()
            }),
            url: $("#moveConnectDocumentItemsGrid").attr('data-url'),
            contentType: "application/json"
        }).done(function (response) {
            if (response && response.length > 0) {
                loadDocumentConnectIdents(response);
            }
        });
    }

    function loadDocumentConnectIdents(documentConnectIdents) {
        $moveConnectDocumentDataTable = $('#moveConnectDocumentItemsGrid');
        if ($.fn.dataTable.isDataTable('#moveConnectDocumentItemsGrid'))
            $moveConnectDocumentDataTable.DataTable().destroy();

        originalDocumentIdents = documentConnectIdents;
        $moveConnectDocumentDataTable.DataTable({
            serverSide: false,
            ajax: undefined,
            scroller: true,
            responsive: false,
            info: false,
            data: documentConnectIdents,
            columns: [
                { 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 + '" value="' + full.Quantity + '" type="text" autocomplete="off" disabled />'
                    },
                    className: 'dt-body-right'
                }
            ]
        });

        initializeNumberInputs();
    }

    function getSelectedDocumentInvoiceIdents() {
        $.ajax({
            type: "POST",
            data: JSON.stringify({
                id: $("#MoveConnectFromAcKey").val()
            }),
            url: $("#moveDocumentSelectedItemsGrid").attr('data-url'),
            contentType: "application/json"
        }).done(function (response) {
            if (response && response.length > 0) {
                if ($("#moveConnectSameItemsOnly").is(":checked")) {
                    var matchingIdents = [];
                    response.forEach(ident => {
                        var identExist = originalDocumentIdents.some(x => x.Ident === ident.Ident);
                        if (identExist === true)
                            matchingIdents.push(ident);
                    });

                    loadSelectedDocumentIdents(matchingIdents);
                }
                else {
                    loadSelectedDocumentIdents(response);
                }
            }
        });
    }

    function loadSelectedDocumentIdents(documentConnectIdents) {
        selectedDocumentIdents = [];
        $moveDocumentSelectedDataTable = $('#moveDocumentSelectedItemsGrid');
        if ($.fn.dataTable.isDataTable('#moveDocumentSelectedItemsGrid'))
            $moveDocumentSelectedDataTable.DataTable().destroy();

        connectDocumentIdents = documentConnectIdents;
        $moveDocumentSelectedDataTable.DataTable({
            serverSide: false,
            ajax: undefined,
            scroller: true,
            responsive: false,
            info: false,
            data: documentConnectIdents,
            columns: [
                {
                    data: "",
                    className: 'dt-body-center',
                    render: function (data, type, full) {
                        return '<input class="ackey" id="selectedMoveWizIdent-' + full.AnNo + '" onclick=selectedDocumentIdent("' + full.AnNo + '")  value="' + full.AnNo + '" type="checkbox" />'
                    }
                },
                { 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 + '" value="' + full.Quantity + '" type="text" autocomplete="off" disabled />'
                    },
                    className: 'dt-body-right'
                }
            ]
        });

        initializeNumberInputs();
    }

    function selectedDocumentIdent(anNo) {
        var index = selectedDocumentIdents.findIndex(x => x === toNumber(anNo));

        if ($("#selectedMoveWizIdent-" + anNo).is(':checked')) {
            selectedDocumentIdents.push(toNumber($("#selectedMoveWizIdent-" + anNo).val()));
        } else {
            if (index !== -1)
                selectedDocumentIdents.splice(index, 1);
        }
    }

    function getDocumentHeadInvoices() {
        $.ajax({
            type: "POST",
            data: JSON.stringify({
                AcKey: $("#MoveConnectAcKey").val(),
                Subject: $("#moveConnectBuyer").val(),
                DateFrom: $("#moveConnectDateFrom").val(),
                DateTo: $("#moveConnectDateTo").val(),
            }),
            url: "@Url.Action("DocumentsLinkHeaderWiz", "Move")",
            contentType: "application/json"
        }).done(function (response) {
            if (response && response.length > 0) {
                loadMoveDocumentHeadItems(response);
            }
        });
    }

    function loadMoveDocumentHeadItems(documentConnectHeadItems) {
        selectedDocumentHeadItems = [];
        $moveDocumentHeadDataTable = $('#moveConnectDocumentHeadGrid');
        if ($.fn.dataTable.isDataTable('#moveConnectDocumentHeadGrid'))
            $moveDocumentHeadDataTable.DataTable().destroy();

        $moveDocumentHeadDataTable.DataTable({
            serverSide: false,
            ajax: undefined,
            scroller: true,
            responsive: false,
            info: false,
            data: documentConnectHeadItems,
            columns: [
                { data: "AcKey", orderable: false, render: $.fn.dataTable.render.checkbox("moveDocumentHeadSelectionChanged"), className: 'dt-body-center' },
                { data: "AcKeyView" },
                {
                    data: "ForPay",
                    render: function (data, type, full) {
                        return '<input class="form-control numberInput text-right" value="' + full.ForPay + '" type="text" autocomplete="off" disabled />'
                    },
                    className: 'dt-body-right'
                }
            ]
        });

        initializeNumberInputs();
    }

    function moveDocumentHeadSelectionChanged(cb) {
        if (!cb)
            return;

        var index = selectedDocumentHeadItems.indexOf(cb.value);
        if (cb.checked && index === -1) {
            selectedDocumentHeadItems.push(cb.value);
        } else if (!cb.checked) {
            if (index !== -1)
                selectedDocumentHeadItems.splice(index, 1);
        }
    }

    function ConnectMoveDocuments() {
        var errText = "";
        if ($("#moveDocumentConnectionType option:selected").val() === "@MoveDocumentConnectionType.Items" && (!selectedDocumentIdents || selectedDocumentIdents.length <= 0))
            errText = "@Loc.ConnectionNotPossibleNoPositionSelected";
        else if ($("#moveDocumentConnectionType option:selected").val() === "@MoveDocumentConnectionType.Document" && (!selectedDocumentHeadItems || selectedDocumentHeadItems.length <= 0))
            errText = "@Loc.ConnectionNotPossibleNoDocumentSelected";

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

            return;
        }

        if ($("#moveDocumentConnectionType option:selected").val() === "@MoveDocumentConnectionType.Document")
            CreateMoveDocumentsConnectionAjax();
        else {
            var orgIdentsQtySum = originalDocumentIdents.map(item => item.Quantity).reduce((prev, next) => prev + next);
            var connIdentsQtySum = connectDocumentIdents.map(item => item.Quantity).reduce((prev, next) => prev + next);

            if (orgIdentsQtySum < 0 || connIdentsQtySum < 0) {
                $().customModal({
                    title: "",
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "alert",
                    text: "@Loc.PriceForEvaluationOnConnectedDocumentWillBeFixed",
                    buttons: [
                        {
                            icon: 'fa fa-times',
                            text: '@Loc.Cancel',
                            closeOnAction: true,
                            type: 'ghost'
                        },
                        {
                            icon: 'fa fa-check',
                            text: '@Loc.Confirm',
                            closeOnAction: true,
                            action: function () {
                                CreateMoveDocumentsConnectionAjax();
                            },
                            type: 'primary'
                        }
                    ]
                });
            } else
                CreateMoveDocumentsConnectionAjax();
        }
    }

    function CreateMoveDocumentsConnectionAjax() {
        var createUrl;
        var jsonData;

        $("#connectMoveDocBtn").find("i").addClass("fa fa-spinner fa-spin");

        if ($("#moveDocumentConnectionType option:selected").val() === "@MoveDocumentConnectionType.Document") {
            createUrl = "@Url.Action("DocumentsLinkHeaderWizCreate", "Move")";
            jsonData = JSON.stringify({
                AcKey: $("#MoveConnectAcKey").val(),
                Subject: $("#moveConnectBuyer").val(),
                DateFrom: $("#moveConnectDateFrom").val(),
                DateTo: $("#moveConnectDateTo").val(),
                Documents: selectedDocumentHeadItems
            });
        } else {
            createUrl = "@Url.Action("DocumentsLinkWiz", "Move")";
            jsonData = JSON.stringify({
                AcKey: $("#MoveConnectAcKey").val(),
                ConnectAcKey: $("#MoveConnectFromAcKey").val(),
                Idents: selectedDocumentIdents
            });
        }

        $.ajax({
            type: "POST",
            data: jsonData,
            url: createUrl,
            contentType: "application/json"
        }).done(function (response) {
            $("#connectMoveDocBtn").find("i").removeClass("fa fa-spinner fa-spin fa-fw");

            if (response && response.length > 0) {
                AddInvoiceDocumentConnections(response);
            }

            $().customModal({
                title: "",
                destroyOnClose: true,
                showCloseButton: true,
                type: "success",
                text: "@Loc.OperationFinished",
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: '@Loc.Confirm',
                        closeOnAction: true,
                        action: function () {
                            $("#connectDocWizardModal").modal("hide");
                        },
                        type: 'primary'
                    }
                ]
            });
        });
    }

    function openUserManualHelpConnectDoc() {
        if ($("#MoveConnectionType").val() === '@DtType.Wholesale')
            window.open('@PantheonRA.BackOffice.Helpers.SiteHelpAttributeHelper.GetHelpUrl(HelpIds.ExampleWholesaleConnectDoc)', '_blank');
        else
            window.open('@PantheonRA.BackOffice.Helpers.SiteHelpAttributeHelper.GetHelpUrl(HelpIds.ExampleReceivedBillsConnectDoc)', '_blank');
    }
</script>