@using ZelWiki.Models
@model ZelWiki.Models.ViewModels.Page.PageEditViewModel
@{
    Layout = "/Views/Shared/_Layout.cshtml";
    var sessionState = ViewData["SessionState"] as ZelWiki.SessionState ?? throw new Exception("Wiki State Context cannot be null.");
}

<link rel="stylesheet" href=@Url.Content("~/codemirror/codemirror.css")>
<link rel="stylesheet" href=@Url.Content("~/codemirror/theme/light.css")>
<link rel="stylesheet" href=@Url.Content("~/codemirror/theme/dark.css")>

<link rel="stylesheet" href=@Url.Content("~/codemirror/addon/scroll/simplescrollbars.css")>

<script src="@Url.Content("~/codemirror/codemirror.js")"></script>
<script src="@Url.Content("~/codemirror/addon/edit/matchbrackets.js")"></script>
<script src="@Url.Content("~/codemirror/mode/tightwiki/tightwiki.js")"></script>
<script src="@Url.Content("~/codemirror/addon/scroll/simplescrollbars.js")"></script>

<style type="text/css">
    .CodeMirror {
        border: 1px solid #eee;
        height: 50em;
    }

    .active {
        background-color: lightgreen !important;
    }

    #dropSection {
        width: 100%; 
        height: auto; 
        min-height: 150px; 
        border: 2px dashed #007bff;
        border-radius: 5px;
        text-align: center;
        font-size: 18px;
        color: #007bff;
        margin-bottom: 20px;
        padding: 20px;
        background-color: var(--bs-card-bg); 
        word-wrap: break-word; 
        white-space: normal; 
    }

        #dropSection span {
            display: inline-block; 
            max-width: 100%; 
            line-height: normal;
        }

        #dropSection.dragover {
            background-color: #e9ecef;
            border-color: #007bff;
            color: #007bff;
        }

</style>

<script>
    function readyFn(jQuery) {
        $("#uploadedFiles").load("@GlobalConfiguration.BasePath/File/PageAttachments/@sessionState.PageNavigationEscaped");
    }

    $(document).ready(readyFn);

    document.addEventListener("DOMContentLoaded", function () {
        const dropSection = document.getElementById('dropSection');
        const fileInput = document.getElementById('fileInput');
        const uploadStatus = document.getElementById('uploadStatus');
        
        dropSection.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropSection.classList.add('dragover');
            dropSection.textContent = "将文件放到此处";
        });

        dropSection.addEventListener('dragleave', () => {
            dropSection.classList.remove('dragover');
            dropSection.textContent = "通过将文件拖放到此处或在下面手动选择来附加文件:";
        });
        dropSection.addEventListener('drop', (e) => {
            e.preventDefault();
            dropSection.classList.remove('dragover');
            dropSection.textContent = "通过将文件拖放到此处或在下面手动选择来附加文件:";
            const files = e.dataTransfer.files;
            handleFileUpload(files);
        });
        
        dropSection.addEventListener('click', () => {
            fileInput.click();
        });
        
        fileInput.addEventListener('change', () => {
            const files = fileInput.files;
            handleFileUpload(files);
        });
        
        function handleFileUpload(files) {
            const formData = new FormData();
            for (let i = 0; i < files.length; i++) {
                formData.append('postedFiles', files[i]);
            }

            uploadFiles(formData);
        }
        
        function uploadFiles(formData) {
            fetch('@Url.Action("UploadDragDrop", "File")/@sessionState.PageNavigationEscaped', {
                method: 'POST',
                body: formData
            })
                .then(response => response.json())  
                .then(result => {
                    if (result.success) {
                        uploadStatus.innerHTML = `<p>Upload successful: ${result.message}</p>`;
                    } else {
                        uploadStatus.innerHTML = `<p>Error: ${result.message}</p>`;
                    }
                    $("#uploadedFiles").load("@GlobalConfiguration.BasePath/File/PageAttachments/@sessionState.PageNavigationEscaped");
                })
                .catch(error => {
                    uploadStatus.innerHTML = `<p>Unexpected Error: ${error.message}</p>`;
                });
        }
    });
</script>

<div class="bodyDiv">
    <div class="card">
        <div class="card-header"><h3>正文</h3></div>
        <div class="card-body">
            @if (!string.IsNullOrEmpty(Model.ErrorMessage))
            {
                <div class="alert alert-danger">@Html.Raw(Model.ErrorMessage)</div>
            }
            @if (!string.IsNullOrEmpty(Model.SuccessMessage))
            {
                <div class="alert alert-success">@Html.Raw(Model.SuccessMessage)</div>
            }

            @using (Html.BeginForm(null, null, FormMethod.Post, new { action = $"{GlobalConfiguration.BasePath}{Context.Request.Path}" }))
            {
                @Html.HiddenFor(x => x.Id)

                <div class="form-group">
                    <button type="submit" class="btn btn-primary rounded-0">保存</button>
                    <a href="@GlobalConfiguration.BasePath/@sessionState.PageNavigation" target="_blank" rel="noopener" class="btn btn-success rounded-0" role="button">预览</a>
                </div>
                <br />
                <strong>@Html.LabelFor(x => x.Name)</strong>

                <br />
                @Html.TextBoxFor(x => x.Name, new { style = "width:50%" })
                <div class="text-danger">@Html.ValidationMessageFor(m => m.Name)</div>
                <br />

                <strong>@Html.LabelFor(x => x.Description)</strong>

                <br />
                @Html.TextBoxFor(x => x.Description, new { style = "width:90%" })
                <div class="text-danger">@Html.ValidationMessageFor(m => m.Description)</div>
                <br />

                <strong>@Html.LabelFor(x => x.Body)</strong>

                <br />
                <div class="text-danger">@Html.ValidationMessageFor(m => m.Body)</div>
                <textarea id=Body name="Body">@Model.Body</textarea>
                <script>
                    var editor = CodeMirror.fromTextArea(document.getElementById("Body"), {
                        theme: "@sessionState.UserTheme.EditorTheme",
                        lineNumbers: true,
                        mode: "text/x-tightwiki",
                        matchBrackets: true,
                        viewportMargin: Infinity,
                        lineWrapping: true,
                        scrollbarStyle: "simple"
                    });
                </script>

                <br />

                <div class="form-group">
                    <button type="submit" class="btn btn-primary rounded-0">保存</button>
                    <a href="@GlobalConfiguration.BasePath/@sessionState.PageNavigation" target="_blank" rel="noopener" class="btn btn-success rounded-0" role="button">预览</a>
                </div>
            }
        </div>
    </div>
    <br />

    <div class="card">
        <div class="card-header"><h3>附件</h3></div>
        <div class="card-body">
            @if (Model?.Id > 0 && @sessionState.CanCreate == true)
            {
                <div id="dropSection" class="dropSection">
                    <span class="d-inline-block">将文件拖放到此处或单击手动上传.</span>
                </div>
                <input type="file" id="fileInput" style="display:none" multiple>
                <div id="uploadStatus"></div>
                <div id="uploadedFiles"></div>
            }
            else
            {
                <div>上传文件前,请先保存页面.</div>
            }
        </div>
    </div>
</div>
