@using PantheonRA.BackOffice.Helpers;
@using PantheonRA.BackOffice.Enums;
@using PantheonRA.BackOffice.Models
@model PantheonRA.Contracts.DataContracts.TaskCreateData
@{
    ViewBag.Title = Loc.Tasks;
}

<div class="wrapper wrapper-content">
    <div class="tabs-container">
        @Html.Partial("~/Views/Documents/_DocumentsTabNavigation.cshtml")
        <div class="tab-content">
            <form method="post" id="TaskForm" enctype="multipart/form-data">
                @Html.HiddenFor(model => model.Id)
                @Html.HiddenFor(model => model.Action)
                @Html.HiddenFor(model => model.IsRedirectTask)

                @for (int i = 0; i < Model.AvailableActions.Count; i++)
                {
                    @Html.HiddenFor(model => Model.AvailableActions[i])
                }

                <div class="row buttons-tabbed">
                    @Html.Partial("_FormButtons", new FormButtonsViewModel
                    {
                        BackUrl = Url.Action("Index", "Task")
                    })
                </div>

                <div class="divided-content">
                    <div class="divided-content-main divided-content-main-documents @(Model.Document == null ? "divided-content-full" : "" )">
                        <div class="row">
                            @if (Model.Document != null)
                            {
                                <div class="col-md-6 col-sm-6">
                                    <h2>@Loc.Task @(Model.Id > 0 ? Model.TaskName : string.Empty)</h2>

                                    @{ ViewBag.IsPreviewOnly = false; }
                                    @Html.Partial("~/Views/Documents/CreateFormPartial.cshtml", Model.Document, new ViewDataDictionary(Html.ViewData)
                                    {
                                        TemplateInfo = new TemplateInfo { HtmlFieldPrefix = ViewData.TemplateInfo.GetFullHtmlFieldName(Html.NameFor(m => m.Document).ToString()) },
                                    });
                                </div>
                            }

                                <div class="col-md-6 col-sm-6 task-main">
                                    <h2>@Model.TaskName</h2>
                                    @Html.HiddenFor(model => model.TaskName)

                                    @*TODO: remove after workflow in redesigned!*@
                                    @if (Model.TaskName == "Vnesite podatke za pripravo" && !Model.IsTaskCompleted)
                                    {
                                        <div class="form-horizontal form-md">
                                            <div class="form-group">
                                                @Html.LabelFor(model => model.ScanData.DocType, Loc.DocType, new { @class = "col-lg-3 control-label" })
                                                <div class="col-lg-9">
                                                    <select name="ScanData.DocType" class="form-control custom-select" id="DocTypeSelect" onchange="onDocumentTypeChange()">
                                                        @foreach (var item in ViewBag.DocumentTypes)
                                                        {
                                                            <option value="@item.Value"
                                                                    data-warehouse="@item.Warehouse"
                                                                    data-department="@item.Department"
                                                                    @((Model.ScanData != null ? Model.ScanData.DocType : null) == item.Value ? "selected" : string.Empty)>
                                                                @item.Name
                                                            </option>
                                                        }
                                                    </select>
                                                    @Html.ValidationMessageFor(model => model.ScanData.DocType, "", new { @class = "text-danger" })
                                                </div>
                                            </div>

                                            <div class="form-group">
                                                @Html.LabelFor(model => model.ScanData.ScanDate, Loc.Date, new { @class = "col-lg-3 control-label" })
                                                <div class="col-lg-9">
                                                    @if (Model.ScanData == null) { Model.ScanData = new PantheonRA.Contracts.DataContracts.ScanTaskCreateData { ScanDate = DateTime.Now.Date }; }
                                                    @Html.TextBoxFor(model => model.ScanData.ScanDate, (Model.ScanData != null ? Model.ScanData.ScanDate.ToString("dd.MM.yyyy") : DateTime.Now.Date.ToString(Loc.DateFormat)),
                                                     HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "Date", Model.IsTaskCompleted, Loc.Date))
                                                    @Html.ValidationMessageFor(model => model.ScanData.ScanDate, "", new { @class = "text-danger" })
                                                </div>
                                            </div>

                                            <div class="form-group">
                                                @Html.LabelFor(model => model.ScanData.ScanDate, Loc.Subject, new { @class = "col-lg-3 control-label" })
                                                <div class="col-lg-9">
                                                    <input autocomplete="off" class="form-control typeahead_3 typeahead_wide ltSubj" name="ScanData.SubjectName" id="subjectSelectTask"
                                                           value="@(Model.ScanData != null ? Model.ScanData.SubjectName : null)" type="text" @(Model.IsTaskCompleted ? "readonly" : string.Empty)>
                                                    <input value="@(Model.ScanData != null ? Model.ScanData.SubjectId : null)" name="ScanData.SubjectId" id="subjectIdTask" hidden />
                                                </div>
                                            </div>

                                            <div class="form-group">
                                                @Html.LabelFor(model => model.ScanData.WarehouseId, Loc.Warehouse, new
                                           {
                                               @class = "col-md-3 control-label",
                                               @title = Loc.ReceivingWarehouse
                                           })
                                                <div class="col-md-9">
                                                    <select class="form-control custom-select" id="WarehouseSelect" name="ScanData.WarehouseId">
                                                        <option></option>
                                                        @foreach (var item in ViewBag.Warehouses)
                                                        {
                                                            <option value="@item.Id" @((Model.ScanData != null ? Model.ScanData.WarehouseId : null) == item.Id ? "selected" : string.Empty)>
                                                                @item.Name
                                                            </option>
                                                        }
                                                    </select>
                                                    @Html.ValidationMessageFor(model => model.ScanData.WarehouseId, "", new { @class = "text-danger", @id = "IssuerId-validation" })
                                                </div>
                                            </div>

                                            <div class="form-group">
                                                @Html.LabelFor(model => model.ScanData.DepartmentId, Loc.Department, new
                                                {
                                                    @class = "col-md-3 control-label",
                                                    @title = Loc.Department
                                                })
                                                <div class="col-md-9">
                                                    <select name="ScanData.DepartmentId" class="form-control custom-select" id="DepartmentSelect">
                                                        <option></option>
                                                        @foreach (var item in ViewBag.Departments)
                                                        {
                                                            <option value="@item.Id" @((Model.ScanData != null ? Model.ScanData.DepartmentId : null) == item.Id ? "selected" : string.Empty)>
                                                                @item.Name
                                                            </option>
                                                        }
                                                    </select>
                                                    @Html.ValidationMessageFor(model => model.ScanData.DepartmentId, "", new { @class = "text-danger", @id = "Department-validation" })
                                                </div>
                                            </div>
                                        </div>
                                    }
                                    else
                                    {
                                        <div class="flat" style="margin-bottom:10px;">
                                            <textarea class="form-control" rows="7" readonly>@Model.Comment</textarea>
                                        </div>
                                    }

                                    @if (Model.IsTaskCompleted)
                                    {

                                        string alertType = "", textType = "", alertTitle = "", alertContent = "";
                                        switch (Model.Action.ToLower())
                                        {
                                            case TaskActionTypes.Forward:
                                                alertType = "alert-info";
                                                textType = "text-info";
                                                alertTitle = Loc.TaskForwarded;
                                                alertContent = Loc.TaskWasForwarded;
                                                break;
                                            case TaskActionTypes.Reject:
                                                alertType = "alert-danger";
                                                textType = "text-danger";
                                                alertTitle = Loc.TaskRejected;
                                                alertContent = Loc.TaskWasRejected;
                                                break;
                                            case TaskActionTypes.Confirm:
                                            default:
                                                alertType = "alert-success";
                                                textType = "text-success";
                                                alertTitle = Loc.TaskConfirmed;
                                                alertContent = Loc.TaskWasConfirmed;
                                                break;
                                        }
                                        <div class="alert @alertType">
                                            <div style="display:table-cell"><i class="fa fa-check fa-4x @textType"></i></div>
                                            <div style="display:table-cell; vertical-align:middle;padding-left:10px;">
                                                <h3 class="no-margins">@alertTitle</h3>
                                                <span class="task-explanation">@alertContent</span>
                                            </div>
                                        </div>
                                    }
                                    else
                                    {
                                        <div>
                                            <label>@Loc.ValidatorComment</label>
                                            <textarea class="form-control" name="Comment" style="margin: 2px 0 15px 0;" rows="5" placeholder="@Loc.WriteComment"></textarea>
                                        </div>
                                    }

                                    @if (Model.IsRedirectTask || Model.AvailableActions.Any(a => a == TaskActionTypes.Forward))
                                    {
                                        <div class="form-horizontal">
                                            <div class="form-group">
                                                <div class="col-lg-4"><label class="control-label">@Loc.SelectUser</label></div>
                                                <div class="col-lg-8">
                                                    @Html.HiddenFor(model => model.SubjectId)
                                                    @Html.TextBoxFor(model => model.SubjectName,
                                                            HtmlAttributesHelper.CreateInputAttributes("form-control typeahead_3", "SubjectName",
                                                                Model.IsTaskCompleted, Loc.User, true, new { dataUrl = Url.Action("SearchUsers", "Task") }))
                                                    @Html.ValidationMessageFor(model => model.SubjectId, "", new { @class = "text-danger" })
                                                </div>
                                            </div>
                                        </div>
                                    }

                                    @if (!Model.IsTaskCompleted)
                                    {
                                        @Html.Partial("~/Views/Task/_AvailableActions.cshtml", Model.AvailableActions)
                                    }
                                </div>
                        </div>
                        <div class="row m-t-sm">
                            @{Html.RenderPartial("~/Views/Shared/Components/_TaskChatLog.cshtml");}
                        </div>
                    </div>
                    @if (Model.Document != null)
                    {
                        <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-1">
                                        <a data-toggle="tab" href="#home" class="local-tab">
                                            @Loc.Attachments <span class="badge" id="filesCount">
                                                @(Model.Document.Files != null ? Model.Document.Files.Count() : 0)
                                            </span>
                                        </a>
                                    </li>
                                </ul>
                            </div>

                            <div class="tab-content no-padding">
                                <div id="home" class="tab-pane fade in active">
                                    @{
                                        var fileDisplayDictionary = new ViewDataDictionary(ViewData)
                                        {
                                            TemplateInfo = new TemplateInfo { HtmlFieldPrefix = ViewData.TemplateInfo.GetFullHtmlFieldName(Html.NameFor(m => m.Document.Files).ToString()) }
                                        };
                                        fileDisplayDictionary.Add("uploadFiles", true);
                                    }

                                    @Html.Partial("~/Views/Documents/_FileDisplayPartial.cshtml", Model.Document.Files != null ?
                                                     Model.Document.Files : new List<PantheonRA.Contracts.DataContracts.FileData>(),
                                                     fileDisplayDictionary)
                                </div>
                            </div>
                        </div>
                    }
                </div>
            </form>
        </div>
    </div>
</div>

@Scripts.Render("~/bundles/tasks")
@section pageScripts{
    @Scripts.Render("~/bundles/fileDisplay")
    <script src="~/Scripts/custom/initializers.js"></script>

    <script type="text/javascript">
        function RunTaskAction(action) {
            $("#Action").val(action);
            $("#TaskForm")[0].checkValidity();
            $("#TaskForm").submit();
        }

        $(document).ready(function () {
            initializeUserTypeahead($('#SubjectName').attr('dataUrl'), $('#SubjectName'), $("#SubjectId"));

            onDocumentTypeChange();
            let $firstSubj = $($(".ltSubj")[0]);
            if ($firstSubj && $firstSubj.length > 0) {
                $("#subjectSelectTask").val($firstSubj.val());
                $("#subjectIdTask").val($firstSubj.next().val());
            }

            initializeNumberInputs();

            let metadataUrls = {
                classifications: '@Url.Action("SearchClassifications", "Documents")',
                partners: '@Url.Action("SearchPartners", "Documents")',
                departments: '@Url.Action("SearchDepartments", "Wholesale")',
            }
            initializeTaskMetadataInputs(metadataUrls);

            @{
                var previewImage = Model.Document != null && Model.Document.PreviewImage != null ? Model.Document.PreviewImage : null;
                var files = Model.Document != null && Model.Document.Files != null && Model.Document.Files.Any() ? Model.Document.Files[0].Id.ToString() : string.Empty;
            }

            initializeFileDisplay('@previewImage', '@files');

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

            $('#DocumentPreview').attr('src', `data:image/png;base64,${'@(Model.Document != null ? Model.Document.PreviewImage : string.Empty)'}`);
            dropifyUpload($("#TaskForm"));
        });

        function switchButtons() {
            $(".task-buttons-row > .task-buttons-div > button").addClass("hidden");
            $(".task-buttons-row").addClass("buttons-left");
            $(".task-redirect > button").removeClass("hidden");
            $(".task-redirect > button").addClass("margin-left-10");
            $(".task-redirect").addClass("task-redirect-left");
        }

        function onDocumentTypeChange() {
            let docTypeWarehouse = $("#DocTypeSelect option:selected").attr("data-warehouse");
            let docTypeDepartment = $("#DocTypeSelect option:selected").attr("data-department");
            $("#WarehouseSelect").val(docTypeWarehouse);
            $("#DepartmentSelect").val(docTypeDepartment);
        }
    </script>
}
