@page "/UploadData"

@using System.ComponentModel.DataAnnotations;
@using System.Text.Json;
@using System.ComponentModel
@using AntDesign.TableModels
@using AntDesign.Form
@using System.Linq
@using System.Net.Http.Headers
@using Microsoft.Extensions.Logging
@inject HttpClient Http
@inject ILogger<UploadData> Logger
@using wispro.sp.share


<style>
    .steps-content {
        margin-top: 16px;
        border: 1px dashed #e9e9e9;
        border-radius: 6px;
        background-color: #fafafa;
        min-height: 200px;
        text-align: center;
        padding-top: 80px;
    }

    .steps-action {
        margin-top: 24px;
    }
</style>

<Form Model="@model" LabelColSpan="10" WrapperColSpan="16" style="margin-left: 50px;margin-right:50px;">


    <wispro.sp.web.Share.SPStep CurrentStep="0" />


    <div class=" ant-upload ant-upload-select-text ant-upload-drag ant-upload-select">


        <FormItem>
            <p />
        </FormItem>
        <FormItem Label="绩效月份" LabelColSpan="10" WrapperColSpan="5">
            <DatePicker TValue="DateTime?" Picker="@DatePickerType.Month" @bind-Value="@context.Month" />
        </FormItem>


        <div tabindex="0" class="ant-upload" style="position:relative;" data-fileid="5c8e2c2b-92b2-4b57-bac4-89c3f44c64d4" role="button" _bl_1728="">
            <Upload Action="http://localhost:39476/api/AttachFiles/PostFile" Name="file">
                <p class="ant-upload-drag-icon">
                    <Icon Type="upload" />
                </p>
                <p class="ant-upload-text">请选择包括绩效事项记录的Excel文件</p>
                <p class="ant-upload-hint">
                    请从维德流程管理系统中导出上月的申请案件完成事项报表文件，并将其上传到系统开始绩效核算流程
                </p>
            </Upload>
            <div class="file-input-zone">
                <InputFile OnChange="OnInputFileChange" multiple />
                Get me a file!
            </div>
            
        </div>

        <p />
        <FormItem LabelColSpan="20" WrapperColSpan="16">
            <Button Type="@ButtonType.Primary" HtmlType="submit">
                上传
            </Button>
        </FormItem>
    </div>


</Form>

<style>
    .file-input-zone {
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: blue;
        color: white;
        cursor: pointer;
        position: relative;
        width: 120px;
        height: 30px;
    }

        .file-input-zone:hover {
            background-color: lightblue;
        }

        .file-input-zone input[type=file] {
            position: absolute;
            width: 100%;
            height: 100%;
            opacity: 0;
            cursor: pointer;
        }
</style>

@code {
    public class Model
    {
        public DateTime? Month { get; set; } = DateTime.Now.AddMonths(-1);

    }


    private Model model = new Model();

    private void OnFinish(EditContext editContext)
    {
    }

    private void OnFinishFailed(EditContext editContext)
    {
    }

    private List<File> files = new();
    private List<UploadResult> uploadResults = new();
    private int maxAllowedFiles = 3;
    private bool shouldRender;

    protected override bool ShouldRender() => shouldRender;

    private async void OnSingleCompleted(AntDesign.UploadInfo uploadInfo)
    {
        long maxFileSize = 1024 * 1024 * 15;

        //Stream fs = uploadInfo.File.OpenReadStream(maxFileSize);
        //await fs.CopyToAsync(memoryStream);
        //Assembly assembly = Assembly.Load(memoryStream.ToArray());
    }

    private async System.Threading.Tasks.Task OnInputFileChange(InputFileChangeEventArgs e)
    {
        shouldRender = false;
        long maxFileSize = 1024 * 1024 * 15;
        var upload = false;

        using var content = new MultipartFormDataContent();


        foreach (var file in  e.GetMultipleFiles(maxAllowedFiles))
        {
            if (uploadResults.SingleOrDefault(
                f => f.FileName == file.Name) is null)
            {
                try
                {
                    var fileContent =
                        new StreamContent(file.OpenReadStream(maxFileSize));

                    fileContent.Headers.ContentType =
                        new MediaTypeHeaderValue(file.ContentType);

                    files.Add(new() { Name = file.Name });

                    content.Add(
                        content: fileContent,
                        name: "\"files\"",
                        fileName: file.Name);

                    upload = true;
                }
                catch (Exception ex)
                {
                    Logger.LogInformation(
                        "{FileName} not uploaded (Err: 6): {Message}",
                        file.Name, ex.Message);

                    uploadResults.Add(
                        new()
                        {
                            FileName = file.Name,
                            ErrorCode = 6,
                            Uploaded = false
                        });
                }
            }
        }

        if (upload)
        {
            var response = await Http.PostAsync("http://localhost:39476/api/AttachFiles/PostFile", content);

            var newUploadResults = await response.Content
                .ReadFromJsonAsync<IList<UploadResult>>();

            uploadResults = uploadResults.Concat(newUploadResults).ToList();
        }

        shouldRender = true;


    }

    private static bool FileUpload(IList<UploadResult> uploadResults,
        string fileName, ILogger<UploadData> logger, out UploadResult result)
    {
        result = uploadResults.SingleOrDefault(f => f.FileName == fileName);

        if (result is null)
        {
            logger.LogInformation("{FileName} not uploaded (Err: 5)", fileName);
            result = new();
            result.ErrorCode = 5;
        }

        return result.Uploaded;
    }

    private class File
    {
        public string Name { get; set; }
    }
}
