@model ShoppingCartModel
@using System.Text
@using Nop.Core
@using Nop.Core.Domain.Catalog
@using Nop.Core.Domain.Media
@using Nop.Services.Media
@inject IDownloadService downloadService
@inject CatalogSettings catalogSettings

@if (Model.CheckoutAttributes.Count > 0)
{
    var attributeChangeScriptsBuilder = new StringBuilder();
    <div class="checkout-attributes">
        @foreach (var attribute in Model.CheckoutAttributes)
        {
            var controlId = $"checkout_attribute_{attribute.Id}";
            var textPrompt = !string.IsNullOrEmpty(attribute.TextPrompt) ? attribute.TextPrompt : attribute.Name;
            <div class="row mb-3">
                <div id="@($"checkout_attribute_label_{attribute.Id}")" class="col-sm-12 col-md-5 col-lg-5 col-xl-5">
                    <label class="col-form-label pt-0">
                        @textPrompt
                    </label>
                    @if (attribute.IsRequired)
                    {
                        <span class="required">*</span>
                    }
                </div>

                <div id="@($"checkout_attribute_input_{attribute.Id}")" class="col-sm-12 col-md-5 col-lg-5 col-xl-5">
                    @switch (attribute.AttributeControlType)
                    {
                        case AttributeControlType.DropdownList:
                            {
                                <select class="form-control custom-select" name="@(controlId)" id="@(controlId)">
                                    @if (!attribute.IsRequired)
                                    {
                                        <option value="0">---</option>
                                    }
                                    @foreach (var attributeValue in attribute.Values)
                                    {
                                        var attributeName = string.IsNullOrEmpty(attributeValue.PriceAdjustment) ?
                                            attributeValue.Name :
                                            T("ShoppingCart.CheckoutAttributes.PriceAdjustment", attributeValue.Name, attributeValue.PriceAdjustment).Text;
                                        <option selected="@attributeValue.IsPreSelected" value="@attributeValue.Id">@attributeName</option>
                                    }
                                </select>
                                attributeChangeScriptsBuilder.AppendFormat("$('#{0}').on('change', function(){{checkoutAttributeChange();}});\n", controlId);
                            }
                            break;
                        case AttributeControlType.RadioList:
                            {
                                <ul class="option-list">
                                    @foreach (var attributeValue in attribute.Values)
                                    {
                                        var attributeName = string.IsNullOrEmpty(attributeValue.PriceAdjustment) ?
                                            attributeValue.Name :
                                            T("ShoppingCart.CheckoutAttributes.PriceAdjustment", attributeValue.Name, attributeValue.PriceAdjustment).Text;
                                        <li>
                                            <div class="custom-control custom-radio">
                                                <input class="custom-control-input" id="@(controlId)_@(attributeValue.Id)" type="radio" name="@(controlId)" value="@attributeValue.Id" checked="@attributeValue.IsPreSelected" />
                                                <label class="custom-control-label" for="@(controlId)_@(attributeValue.Id)">@attributeName</label>
                                            </div>
                                        </li>
                                        attributeChangeScriptsBuilder.AppendFormat("$('#{0}_{1}').on('click', function(){{checkoutAttributeChange();}});\n", controlId, attributeValue.Id);
                                    }
                                </ul>
                            }
                            break;
                        case AttributeControlType.Checkboxes:
                        case AttributeControlType.ReadonlyCheckboxes:
                            {
                                <ul class="option-list">
                                    @foreach (var attributeValue in attribute.Values)
                                    {
                                        var attributeName = string.IsNullOrEmpty(attributeValue.PriceAdjustment) ?
                                            attributeValue.Name :
                                            T("ShoppingCart.CheckoutAttributes.PriceAdjustment", attributeValue.Name, attributeValue.PriceAdjustment).Text;
                                        <li>
                                            <div class="form-check">
                                                <input class="form-check-input" id="@(controlId)_@(attributeValue.Id)" type="checkbox" name="@(controlId)" value="@attributeValue.Id" checked="@attributeValue.IsPreSelected" @(attribute.AttributeControlType == AttributeControlType.ReadonlyCheckboxes ? Html.Raw(" disabled=\"disabled\"") : null) />
                                                <label class="form-check-label" for="@(controlId)_@(attributeValue.Id)">@attributeName</label>
                                            </div>
                                        </li>
                                        attributeChangeScriptsBuilder.AppendFormat("$('#{0}_{1}').on('click', function(){{checkoutAttributeChange();}});\n", controlId, attributeValue.Id);
                                    }
                                </ul>
                            }
                            break;
                        case AttributeControlType.TextBox:
                            {
                                <input name="@(controlId)" type="text" class="textbox form-control" id="@(controlId)" value="@(attribute.DefaultValue)" />
                            }
                            break;
                        case AttributeControlType.MultilineTextbox:
                            {
                                <textarea id="@(controlId)" class="form-control" name="@(controlId)">@(attribute.DefaultValue)</textarea>
                            }
                            break;
                        case AttributeControlType.Datepicker:
                            {
                                <nop-date-picker asp-day-name="@(controlId + "_day")"
                                                 asp-month-name="@(controlId + "_month")"
                                                 asp-year-name="@(controlId + "_year")"
                                                 asp-begin-year="@DateTime.UtcNow"
                                                 asp-end-year="@DateTime.UtcNow.AddYears(catalogSettings.CountDisplayedYearsDatePicker)"
                                                 asp-selected-date="@CommonHelper.ParseDate(attribute.SelectedYear, attribute.SelectedMonth, attribute.SelectedDay)" />
                            }
                            break;
                        case AttributeControlType.FileUpload:
                            {
                                Download download = null;
                                if (!string.IsNullOrEmpty(attribute.DefaultValue))
                                {
                                    download = await downloadService.GetDownloadByGuidAsync(new Guid(attribute.DefaultValue));
                                }

                                //register CSS and JS
                                <link rel="stylesheet" href="~/lib_npm/fine-uploader/fine-uploader/fine-uploader.min.css" />
                                <script asp-exclude-from-bundle="true" src="~/lib_npm/fine-uploader/jquery.fine-uploader/jquery.fine-uploader.min.js" asp-location="Footer"></script>

                                //ex. ['jpg', 'jpeg', 'png', 'gif'] or []
                                var allowedFileExtensions = string.Join(", ", attribute.AllowedFileExtensions.Select(x => "'" + x.Trim() + "'").ToList());

                                if (download != null)
                                {
                                    <input id="@(controlId)" name="@(controlId)" type="hidden" value="@download.DownloadGuid" />
                                }
                                else
                                {
                                    <input id="@(controlId)" name="@(controlId)" type="hidden" />
                                }

                                @*fine uploader container*@
                                <div id="@(controlId)uploader"></div>
                                @*fine uploader template (keep it synchronized to \Content\fineuploader\templates\default.html)*@
                                <script type="text/template" asp-location="Footer" id="@(controlId)-qq-template">
                                    <div class="qq-uploader-selector qq-uploader">
                                        <div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>
                                            <span>@T("Common.FileUploader.DropFiles")</span>
                                        </div>
                                        <div class="qq-upload-button-selector qq-upload-button">
                                            <div>@T("Common.FileUploader.Upload")</div>
                                        </div>
                                        <span class="qq-drop-processing-selector qq-drop-processing">
                                            <span>@T("Common.FileUploader.Processing")</span>
                                            <span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>
                                        </span>
                                        <ul class="qq-upload-list-selector qq-upload-list">
                                            <li>
                                                <div class="qq-progress-bar-container-selector">
                                                    <div class="qq-progress-bar-selector qq-progress-bar"></div>
                                                </div>
                                                <span class="qq-upload-spinner-selector qq-upload-spinner"></span>
                                                <span class="qq-edit-filename-icon-selector qq-edit-filename-icon"></span>
                                                <span class="qq-upload-file-selector qq-upload-file"></span>
                                                <input class="qq-edit-filename-selector qq-edit-filename" tabindex="0" type="text">
                                                <span class="qq-upload-size-selector qq-upload-size"></span>
                                                <a class="qq-upload-cancel-selector qq-upload-cancel" href="#">@T("Common.FileUploader.Cancel")</a>
                                                <a class="qq-upload-retry-selector qq-upload-retry" href="#">@T("Common.FileUploader.Retry")</a>
                                                <a class="qq-upload-delete-selector qq-upload-delete" href="#">@T("Common.FileUploader.Delete")</a>
                                                <span class="qq-upload-status-text-selector qq-upload-status-text"></span>
                                            </li>
                                        </ul>
                                    </div>
                                </script>
                                <script asp-location="Footer">
                                    $(function () {
                                        $("#@(controlId)uploader").fineUploader({
                                            request: {
                                                endpoint: '@(Url.RouteUrl("UploadFileCheckoutAttribute", new {attributeId = attribute.Id}))'
                                            },
                                            template: "@(controlId)-qq-template",
                                            multiple: false,
                                            validation: {
                                                allowedExtensions: [@Html.Raw(allowedFileExtensions)]
                                            }
                                        }).on("complete", function(event, id, name, responseJSON, xhr) {
                                            $("#@(controlId)").val(responseJSON.downloadGuid);
                                            if (responseJSON.success) {
                                                $("#@(controlId + "downloadurl")").html("<a href='" + responseJSON.downloadUrl + "'>@T("Common.FileUploader.DownloadUploadedFile")</a>");
                                                $("#@(controlId + "remove")").show();
                                            }
                                            if (responseJSON.message) {
                                                alert(responseJSON.message);
                                            }
                                        });

                                        $("#@(controlId + "remove")").on("click", function(e) {
                                            $("#@(controlId + "downloadurl")").html("");
                                            $("#@(controlId)").val('');
                                            $(this).hide();
                                        });
                                    });
                                </script>
                                <div id="@(controlId + "downloadurl")">
                                    @if (download != null)
                                    {
                                        <a href="@(Url.RouteUrl("DownloadGetFileUpload", new { downloadId = download.DownloadGuid }))" class="download-uploaded-file">@T("Common.FileUploader.DownloadUploadedFile")</a>
                                    }
                                </div>
                                <div>
                                    @if (download != null)
                                    {
                                        <a id="@(controlId + "remove")" class="remove-download-button">@T("Common.FileUploader.RemoveDownload")</a>
                                    }
                                    else
                                    {
                                        <a id="@(controlId + "remove")" class="remove-download-buttonn" style="display:none;">@T("Common.FileUploader.RemoveDownload")</a>
                                    }
                                </div>
                            }
                            break;
                        case AttributeControlType.ColorSquares:
                            {
                                <ul class="option-list attribute-squares color-squares" id="color-squares-@(attribute.Id)">
                                    @foreach (var attributeValue in attribute.Values)
                                    {
                                        var attributeName = string.IsNullOrEmpty(attributeValue.PriceAdjustment) ?
                                            attributeValue.Name :
                                            T("ShoppingCart.CheckoutAttributes.PriceAdjustment", attributeValue.Name, attributeValue.PriceAdjustment).Text;
                                        <li @(attributeValue.IsPreSelected ? @Html.Raw(" class=\"selected-value\"") : null)>
                                            <label for="@(controlId)_@(attributeValue.Id)">
                                                <span class="attribute-square-container" title="@attributeName">
                                                    <span class="attribute-square" style="background-color:@(attributeValue.ColorSquaresRgb);">&nbsp;</span>
                                                </span>
                                                <input id="@(controlId)_@(attributeValue.Id)" type="radio" name="@(controlId)" value="@attributeValue.Id" checked="@attributeValue.IsPreSelected" />
                                                @*uncomment below to display attribute value name*@
                                                @*<span class="name">@attributeName</span>*@
                                            </label>
                                        </li>
                                        attributeChangeScriptsBuilder.AppendFormat("$('#{0}_{1}').on('click', function(){{checkoutAttributeChange();}});\n", controlId, attributeValue.Id);
                                    }
                                </ul>
                                <script asp-location="Footer">
                                   $(function () {
                                        $('.checkout-attributes #color-squares-@(attribute.Id)').on('click', 'input', function (event) {
                                            $('.checkout-attributes #color-squares-@(attribute.Id)').find('li').removeClass('selected-value');
                                            $(this).closest('li').addClass('selected-value');
                                        });
                                   });
                                </script>
                            }
                            break;
                        case AttributeControlType.ImageSquares:
                            {
                                //not support attribute type
                            }
                            break;
                    }
                </div>

            </div>
        }
    </div>
    <script asp-location="Footer">
        $(function () {
            checkoutAttributeChange();
            @Html.Raw(attributeChangeScriptsBuilder.ToString())
        });

        function checkoutAttributeChange() {
            $.ajax({
                cache: false,
                url: "@Html.Raw(Url.RouteUrl("CheckoutAttributeChange", new { isEditable = Model.IsEditable }))",
                data: $('#shopping-cart-form').serialize(),
                type: "POST",
                success: function (data, textStatus, jqXHR) {
                    if (data.ordetotalssectionhtml) {
                        $('.total-info').replaceWith(data.ordetotalssectionhtml);
                    }
                    if (data.selectedcheckoutattributesssectionhtml) {
                        $('.selected-checkout-attributes').replaceWith(data.selectedcheckoutattributesssectionhtml);
                    }
                    if (data.enabledattributeids) {
                        for (var i = 0; i < data.enabledattributeids.length; i++) {
                            $('#checkout_attribute_label_' + data.enabledattributeids[i]).show();
                            $('#checkout_attribute_input_' + data.enabledattributeids[i]).show();
                        }
                    }
                    if (data.disabledattributeids) {
                        for (var i = 0; i < data.disabledattributeids.length; i++) {
                            $('#checkout_attribute_label_' + data.disabledattributeids[i]).hide();
                            $('#checkout_attribute_input_' + data.disabledattributeids[i]).hide();
                        }
                    }
                    $(document).trigger({ type: "checkout_attributes_changed", changedData: data });
                }
            });
        }
    </script>
}