@model PantheonRA.Contracts.DataContracts.DocumentCreateData
@using PantheonRA.BackOffice.Models
@using PantheonRA.BackOffice.Enums
@{
    ViewBag.Title = Loc.Documents;
    var isPreviewOnly = ViewBag.IsPreviewOnly != null ? (bool)ViewBag.IsPreviewOnly : false;
}

<div class="wrapper wrapper-content">
    <div class="tabs-container">
        @Html.Partial("_DocumentsTabNavigation")
        <div class="tab-content">
            <form id="documentForm" method="post" enctype="multipart/form-data">
                @Html.HiddenFor(model => model.AcKey)
                <input type="hidden" value="@Model.Id" name="Id" id="Id" />

                <div class="row buttons-tabbed">
                    @Html.Partial("_FormButtons", new FormButtonsViewModel {
                   BackUrl = Url.Action("Index", "Documents"),
                   SaveButtonGroup = new FormButtonGroup
                   {
                       Buttons = new List<FormButton>
                            {
                                new FormButton { Text = Loc.Save, Icon = "fa fa-save fa-lg", IsSubmit = true }
                            }
                   }
               })

                    <button id="documentDelete" type="button" onclick="deleteDocument()" title="@Loc.DeleteWholeDocument"
                            class="btn btn-danger btn-outline pull-right @(string.IsNullOrEmpty(Model.AcKey) ? " hidden" : string.Empty)">
                        <i class="far fa-trash-alt m-r-xs"></i>
                        <span class="visible-lg-inline visible-md-inline">@Loc.Delete</span>
                    </button>

                    @if (!Model.IsWorkflowRun && Model.Id > 0)
                    {
                        <a href="@Url.Action("RunWorkflow", "Documents", new { id = Model.AcKey })" class="btn btn-primary btn-outline pull-right">
                            <i class="fa fa-sitemap"></i>
                            <span class="m-l-xs">@Loc.RunWorkflow</span>
                        </a>
                    }

                    <a title="@Loc.New" id="newDocumentButton" onclick="createNewInvoice('@Url.Action("Create", "Documents")', 'DocumentTypeId')"
                       class="btn btn-primary btn-outline pull-right @(string.IsNullOrEmpty(Model.AcKey) ? " hidden" : string.Empty)">
                        <i class="fas fa-plus m-r-xs"></i>
                        <span class="visible-lg-inline visible-md-inline hidden-xs hidden-sm">@Loc.New</span>
                    </a>
                </div>

                <div class="divided-content clearfix">
                    <div class="divided-content-main divided-content-main-documents">
                        <div class="row document-head">
                            <div class="col-md-3 col-sm-6 @(string.IsNullOrEmpty(Model.AcKey) ? string.Empty : " document-head-disabled-input")">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.DocumentTypeId, Loc.DocType, new { @class = "control-label" })
                                    @Html.DropDownListFor(model => model.DocumentTypeId, (List<SelectListItem>)ViewBag.DocumentTypes,
HtmlAttributesHelper.CreateInputAttributes("form-control obligatory-input form-input-required", "DocumentTypeId", isPreviewOnly || Model.IsTaskCompleted || Model.IsWorkflowRun, Loc.DocumentType))
                                    @Html.ValidationMessageFor(model => model.DocumentTypeId, "", new { @class = "text-danger" })
                                </div>
                            </div>

                            <div class="col-md-3 col-sm-6 @(string.IsNullOrEmpty(Model.AcKey) ? string.Empty : " document-head-disabled-input")">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.ClassificationName, Loc.Classification, new { @class = "control-label" })
                                    @Html.HiddenFor(model => model.ClassificationId)
                                    @Html.TextBoxFor(model => model.ClassificationName,
HtmlAttributesHelper.CreateInputAttributes("form-control typeahead_3 typeahead_wide obligatory-input form-input-required", "ClassificationName", isPreviewOnly || Model.IsTaskCompleted || Model.IsWorkflowRun, Loc.Classification))
                                    @Html.ValidationMessageFor(model => model.ClassificationId, "", new { @class = "text-danger" })
                                </div>
                            </div>

                            <div class="col-md-4 col-sm-6">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.PartnerName, Loc.Buyer + " / " + Loc.Payer, new { @class = "control-label", @title = Loc.Buyer + " / " + Loc.Payer })
                                    @Html.ValidationMessageFor(model => model.PartnerId, "", new { @class = "text-danger m-l-xs", @id = "PartnerId-validation" })
                                    @Html.HiddenFor(model => model.PartnerId)
                                    @Html.TextBoxFor(model => model.PartnerName,
HtmlAttributesHelper.CreateInputAttributes("form-control typeahead_3 typeahead_wide obligatory-input addable-input", "PartnerName", isPreviewOnly || Model.IsTaskCompleted, Loc.Partner, true, new { dataUrl = Url.Action("SearchPartners", "Documents") }))
                                    <div class="addable-button">
                                        <button type="button" title="@Loc.AddingNewPartner"
                                                id="NewPartner" class="btn createNewButton" onclick="openSubjectModal('Partner')">
                                            <i class="fas fa-building"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-2 col-sm-12 document-head-disabled-input">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.AcKey, Loc.Number, new { @class = "control-label m-t-xs" })
                                    @Html.HiddenFor(model => model.AcKey)
                                    @Html.HiddenFor(model => model.AcKeyView)
                                    @Html.HiddenFor(model => model.DocType)
                                    <h4 class="control-label" id="AcKeyDisplayContainer">
                                        @{
                                            Html.RenderPartial("~/Views/Shared/Components/_PrevNextKeyDisplay.cshtml",
                                            new PrevNextKeyDisplayViewModel
                                            {
                                                KeyDisplayValue = Model.AcKeyView,
                                                NextNavigation = Url.Action("Next", "Documents", new
                                                {
                                                    Id = string.IsNullOrEmpty(Model.AcKey) ? "{modelId}" : Model.AcKey,
                                                    DocType = string.IsNullOrEmpty(Model.AcKey) ? "{docTypeId}" : Model.DocType,
                                                    RedirectUrl = Url.Action("Edit", "Documents", new { id = "{id}" })
                                                }),
                                                PrevNavigation = Url.Action("Prev", "Documents", new
                                                {
                                                    Id = string.IsNullOrEmpty(Model.AcKey) ? "{modelId}" : Model.AcKey,
                                                    DocType = string.IsNullOrEmpty(Model.AcKey) ? "{docTypeId}" : Model.DocType,
                                                    RedirectUrl = Url.Action("Edit", "Documents", new { id = "{id}" })
                                                }),
                                                KeyNavigation = Url.Action("Index", "Documents", new { acKey = Model.AcKey, date = Model.Date.ToString(Loc.DateFormat) })
                                            });
                                        }
                                    </h4>
                                    @Html.ValidationMessageFor(model => model.AcKey, "", new { @class = "text-danger" })
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 col-sm-6">
                                <h3>@Loc.BasicData</h3>

                                @Html.Partial("CreateFormPartial", Model)
                            </div>
                        </div>
                        @{Html.RenderPartial("~/Views/Shared/Components/_TaskChatLog.cshtml");}
                    </div>
                    <div class="divided-content-side divided-content-side-documents">
                        <div class="tabs-container">
                            <ul class="nav nav-tabs horizontal-menu">
                                <li class="active divided-tab-2">
                                    <a data-toggle="tab" href="#home" class="local-tab">
                                        @Loc.Documents <span class="badge" id="filesCount">
                                            @(Model.Files != null ? Model.Files.Count() : 0)
                                        </span>
                                    </a>
                                </li>
                                <li class="divided-tab-2">
                                    <a data-toggle="tab" href="#connections" class="local-tab">
                                        @Loc.Connected <span class="badge" id="connectionsCount">
                                            @(Model.DocumentConnections != null ? Model.DocumentConnections.Count() : 0)
                                        </span>
                                    </a>
                                </li>
                            </ul>
                        </div>

                        <div class="tab-content no-padding">
                            <div id="home" class="tab-pane fade in active">
                                @Html.Partial("_FileDisplayPartial", Model.Files != null ? Model.Files : new List<PantheonRA.Contracts.DataContracts.FileData>(),
                                    new ViewDataDictionary(ViewData) {{ "uploadFiles", true }})
                                @Html.ValidationMessageFor(model => model.Files, "", new { @class = "text-danger" })
                            </div>
                            <div id="connections" class="tab-pane fade in">
                                <div class="project-list">
                                    <table id="connectionsGrid" class="list-table" data-url="@Url.Action("GetDocumentConnections", "Documents")">
                                        <thead>
                                            <tr>
                                                <th width="33%" data-url="@Url.Action("OpenFormByAcKey", "Documents")?acKey=">@Loc.ConnectionKey</th>
                                                <th width="30%">@Loc.SubjectCode</th>
                                                <th width="30%">@Loc.SubjectTitle</th>
                                                <th width="7%"></th>
                                            </tr>
                                        </thead>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal inmodal fade modal-scroller" id="subjectModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-xxl" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <a class="btn-transparent m-r-xs pull-right" href="@SiteHelpAttributeHelper.GetHelpUrl(HelpIds.ExampleSubjectsNewInModal)" target="_blank"><i class="fas fa-book-reader"></i></a>
                <h3 class="text-left container">@Loc.CreateNewSubject</h3>
            </div>
            <div class="">
                @{Html.RenderPartial("~/Views/Subjects/_CreateSubjectFormPartial.cshtml",
                      new SubjectCreateViewModel() { SubjectEditData = new SubjectEditData() { SelectedCountryId = PantheonRA.BackOffice.CurrentUser.Localization.ToString() }, Countries = ViewBag.Countries, ForCountry = PantheonRA.BackOffice.CurrentUser.Localization.ToString() });}
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="saveSubject()"><i class="fa fa-check m-r-xs"></i>@Loc.Add</button>
                <button type="button" data-dismiss="modal" class="btn btn-link"><i class="fa fa-times m-r-xs text-primary"></i>@Loc.Cancel</button>
            </div>
        </div>
    </div>
</div>

@section pageScripts{
    @Scripts.Render("~/bundles/tasks")
    @Scripts.Render("~/bundles/fileDisplay")
    @Scripts.Render("~/bundles/subjects")

    <script type="text/javascript">
        $(document).ready(function () {
            initializeSubjectsEdit();
            $('.input-validation-error').parents('.form-group').addClass('has-error');
            $('.field-validation-error').addClass('text-danger');

            $('.datepicker').datepicker()
                .on('click', function (e) {
                $(this).select();
            }).on('changeDate', function () {
                $(this).datepicker('hide');
            });

            initializePartnerTypeahead($('#PartnerName').attr('dataUrl'), $('#PartnerName'), $("#PartnerId"));
            initializeDocumentLinksTypeahead($('#addDocConnection').attr('dataUrl'), $('#addDocConnection'), $("#addDocConnection"));

            let metadataUrls = {
                classifications: '@Url.Action("SearchClassifications", "Documents")',
                partners: '@Url.Action("SearchPartners", "Documents")',
                departments: '@Url.Action("SearchDepartments", "Wholesale")',
                docTypes: '@Url.Action("GetAll", "DocumentType")',
            }
            initializeTaskMetadataInputs(metadataUrls);
            initializeFileDisplay('@Model.PreviewImage', '@(Model.Files != null && Model.Files.Any() ? Model.Files[0].Id.ToString() : string.Empty)');
            initializeClassificationTypeahead('@Url.Action("SearchClassifications", "Documents")', $('#ClassificationName'), $('#ClassificationId'));
            dropifyUpload($("#documentForm"));

            $dataTable = $('#tasksGrid');
            $dataTable.DataTable({
                ajax: {
                    url: $dataTable.attr('data-url'),
                    data: function (d) {
                        d.Keywords = $("#Keywords").val();
                        d.DocumentId = $("#AcKey").val();
                    }
                },
                order: [[3, 'desc']],
                columns: [
                    {
                        data: "Name", name: "AcName", render: function (data, type, row, meta) {
                            if (row.IsTaskCompleted === true) {
                                return data;
                            }
                            return $.fn.dataTable.render.link("Id")(data, type, row, meta);
                        }
                    },
                    { data: "User", name: "User.AcName" },
                    { data: "IsTaskCompleted", name: "AcCompleted", render: $.fn.dataTable.render.toggle(true, true), className: 'dt-body-center' },
                    { data: "ChangeDate", name: "AdTimeChg" },
                    { data: "Comment", name: "AcTaskInstComments" }
                ]
            });

            getConnectionsTable();

            var searchDepartmentsUrl = '@Url.Action("SearchDepartments", "Documents")';
            $('#Department').typeahead({
                display: 'item.subject',
                source: function (request, response) {
                    $.post(searchDepartmentsUrl, { search: request })
                        .done(function (data) {
                            var items = [];
                            $.each(data, function (i, item) {
                                items.push({
                                    id: item.AcSubject,
                                    name: i + '|' + (item.AcSubject || '') + '|' + (item.AcName2 || '') + '|' + (item.AcName3 || ''),
                                    name2: item.AcName2,
                                    name3: item.AcName3,
                                    subject: item.AcSubject,
                                    row: i
                                });
                            });
                            response(items);
                        });
                },
                minLength: 1,
                items: 100,
                updater: function (item) {
                    $("#DepartmentId").val(item.id);
                    $("#Department").val(item.subject);
                    return item;
                },
                highlighter: Object,
                displayText: function (item) {
                    var row = "";
                    var pos = item.row;
                    if (pos === 0) {
                        row += '<table class="table">'
                        row += '<thead><tr class="row">'
                        row += '<th width="40%">Oddelek</th>'
                        row += '<th width="25%">Naziv 2</th>'
                        row += '<th width="15%">Naziv 3</th>'
                        row += '</tr></thead>'
                        row += '<tbody>'
                    }
                    else {
                        row += '<table class="table">'
                        row += '<tbody >'
                    }
                    row += '<tr class="row">'
                    row += '<td width="60%">' + item.subject + '</td>'
                    row += '<td width="20%">' + item.name2 + '</td>'
                    row += '<td width="20%">' + item.name3 + '</td>'
                    row += '</tr>'
                    row += '</tbody></table>'
                    return row;
                },
                afterSelect: function (item) {
                    this.$element[0].value = item.subject;
                },
                sorter: function (items) {
                    var beginswith = [];
                    var caseSensitive = [];
                    var caseInsensitive = [];
                    var item;
                    while (item = items.shift()) {
                        var it = this.displayText(item);
                        if (!it.toLowerCase().indexOf(this.query.toLowerCase()))
                            beginswith.push(item);
                        else if (~it.indexOf(this.query))
                            caseSensitive.push(item);
                        else
                            caseInsensitive.push(item)
                    }
                    var result = beginswith.concat(caseSensitive, caseInsensitive);
                    $.each(result, function (i, item) {
                        item.row = i;
                    });
                    return result;
                }
            });

            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                fixIframeAttachments();

                if ($(e.target).attr("href") === "#connections")
                    getConnectionsTable();
            });

            $(".form-input-required").on("change", function () {
                if ($("#AcKey").val())
                    return;

                var readyToSave = true;
                $(".form-input-required").each(function (index) {
                    if (!$(this).val())
                        readyToSave = false;
                });

                if (readyToSave) {
                    $('#Redirect').val('false');
                    $('#documentForm').submit();
                }
            })
        });

        function getConnectionsTable() {
            $.ajax({
                type: "POST",
                data: JSON.stringify({
                    DocumentId: $("#AcKey").val()
                }),
                url: $('#connectionsGrid').attr('data-url'),
                contentType: "application/json"
            }).done(function (response) {
                $("#connectionsCount").text(response && response.length > 0 ? response.length : 0);
                if (response) {
                    $connectionsDataTable = $('#connectionsGrid');
                    if ($.fn.dataTable.isDataTable('#connectionsGrid'))
                        $connectionsDataTable.DataTable().destroy();

                    $connectionsDataTable.DataTable({
                        serverSide: false,
                        ajax: undefined,
                        scroller: true,
                        responsive: false,
                        info: false,
                        data: response,
                        order: [[1, 'desc']],
                        columns: [
                            { data: "LnkKeyView", name: "LnkKeyView", render: $.fn.dataTable.render.link("LnkKey") },
                            { data: "Subject", name: "AcSubject" },
                            { data: "Name", name: "AcName2" },
                            {
                                data: "", render: function (data, type, full) {
                                    return '<button type="button" onclick="confirmRemoveConnectionFromDocument(\'' + full.LnkKey + '\')" class="btn btn-link editableInput"><span class="far fa-trash-alt"></span></button>';
                                }
                            }
                        ]
                    });
                }
            });
        }

        function addConnectionToDocument() {
            if ($("#Id").val() <= 0 || $("#addDocConnection").val() === "") {
                return;
            }

            $.ajax({
                type: "POST",
                data: JSON.stringify({
                    DocumentQid: $("#Id").val(),
                    AcKey: $("#addDocConnection").val(),
                    FormName: "PAW_Documentation"
                }),
                url: $('#AddConnectionUrl').val(),
                contentType: "application/json"
            }).done(function (response) {
                if (response === true) {
                    $("#addDocConnection").val("");
                    getConnectionsTable();
                } else
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "alert",
                        text: "@Loc.GeneralError",
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: "@Loc.Confirm",
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
            });
        }

        function confirmRemoveConnectionFromDocument(connectionId) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "question",
                text: "@Loc.ConfirmDeleteConnection",
                buttons: [
                    {
                        icon: 'fa fa-times',
                        text: '@Loc.No',
                        closeOnAction: true,
                        type: 'ghost'
                    },
                    {
                        icon: 'fa fa-check',
                        text: '@Loc.Yes',
                        action: function () {
                            removeConnectionFromDocument(connectionId);
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }

        function removeConnectionFromDocument(connectionId) {
            if ($("#Id").val() <= 0 || !connectionId) {
                return;
            }

            $.ajax({
                type: "POST",
                data: JSON.stringify({
                    DocumentQid: $("#Id").val(),
                    AcKey: connectionId,
                }),
                url: $('#DeleteConnectionUrl').val(),
                contentType: "application/json"
            }).done(function (response) {
                if (response === true) {
                    getConnectionsTable();
                } else
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "alert",
                        text: "@Loc.GeneralError",
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: "@Loc.Confirm",
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
            });
        }

        var subjectType;
        function openSubjectModal(subject) {
            clearValidationErrors();
            $('#subjectModal form')[0].reset();
            subjectType = subject;
            var id = $("#PartnerName").val();
            setSearchSubjectData(id);
            $("#subjectModal").modal('show');
        }

        function saveSubject() {
            var formData = $("#subjectForm").serializeArray();
            formData.push({ name: 'SubjectEditData.BankAccountsJsonString', value: JSON.stringify(subjectBankAccounts) });

            $.post('@Url.Action("CreateFromPartial", "Subjects")', formData)
                .done(function (response) {
                    if (response.Success) {
                        createSubjectSetValues("PartnerId", response.subject.Id);

                        clearValidationErrors();
                        $("#subjectModal").modal('hide');
                    }
                    else {
                        clearValidationErrors();

                        if (response.errors)
                            displayResponseValidationErrors(response);
                    }
                });
        }

        function deleteDocument() {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "question",
                text: '@Loc.ConfirmDeleteMessage',
                buttons: [
                    {
                        icon: 'fa fa-times',
                        text: '@Loc.Cancel',
                        closeOnAction: true,
                        type: 'ghost'
                    },
                    {
                        icon: 'fa fa-check',
                        text: '@Loc.Confirm',
                        action: function () {
                            $.get("@Url.Action("DeleteDocument", "Documents")?id=" + $("#Id").val(), function (response) {
                                if (response && response.IsDeleted === true)
                                    location.href = '@Url.Action("Index", "Documents")';
                                else
                                    $().customModal({
                                        destroyOnClose: true,
                                        showCloseButton: true,
                                        type: "alert",
                                        text: "@Loc.DeleteWasNotSuccessful",
                                        buttons: [
                                            {
                                                icon: 'fa fa-check',
                                                text: "@Loc.Confirm",
                                                closeOnAction: true,
                                                type: 'primary'
                                            }
                                        ]
                                    });
                            });
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }
    </script>
}
