@using AI.Platform.Page.Pages.Media.Model
@using System.Threading.Tasks
@using System.Text.Json
@using System.Net.Http.Headers

@if (IsVisible && Model != null)
{
    <div class="modal-overlay">
        <div class="modal-content filter_box">
            @if (Model?.Type == 1 || Model?.Type == 2)
            {
                <EditForm Model="@Model" style="width:100%" Context="editContext" @key="Model">
                    <DataAnnotationsValidator />

                    <div class="filter_row">

                        <div class="filter_colume">
                            <div class="filter_row_around">
                                <span>文件名</span><Input Placeholder="文件名" @bind-Value="Model.FileName" Style="width:80%" Disabled />
                            </div>
                            <ValidationMessage For="@(() => Model.FileName)" style="color:red"/>
                        </div>
                        

                        <div class="filter_colume">
                            <div class="filter_row_around">
                                <span>上传人</span><Input Placeholder="上传人" @bind-Value="Model.MediaUploader" Style="width:80%" Disabled />
                            </div>
                            <ValidationMessage For="@(() => Model.MediaUploader)" style="color:red" />
                        </div>
                        
                    </div>

                    <div class="filter_row">
                        <div class="filter_colume">
                            <div class="filter_row_around">
                                <span>广告状态</span>
                                <SimpleSelect DefaultValue="@Model.MediaState.ToString()" OnSelectedItemChanged="@(data => OnSelectItemChange(1, data, editContext))" Style="width:80%">
                                    <SelectOptions>
                                        <SimpleSelectOption Value="0" Label="禁用" style="width:80%" />
                                        <SimpleSelectOption Value="1" Label="可用" style="width:80%" />
                                    </SelectOptions>
                                </SimpleSelect>
                            </div>
                            <ValidationMessage For="@(() => Model.MediaState)" style="color:red" />
                        </div>
                        

                        <div class="filter_colume">
                            <div class="filter_row_around">
                                <span>油机状态</span>
                                <SimpleSelect DefaultValues="@Model.getMachineStateList()" OnSelectedItemsChanged="@(data => OnSelectItemsChange(data, editContext))" Mode="SelectMode.Multiple" style="width:80%">
                                    <SelectOptions>
                                        <SimpleSelectOption Value="idle" Label="空闲" />
                                        <SimpleSelectOption Value="lock" Label="锁枪" />
                                        <SimpleSelectOption Value="offline" Label="脱机" />
                                        <SimpleSelectOption Value="lift" Label="提枪" />
                                        <SimpleSelectOption Value="authorised" Label="授权" />
                                        <SimpleSelectOption Value="start" Label="开始" />
                                        <SimpleSelectOption Value="fueling" Label="加油中" />
                                    </SelectOptions>
                                </SimpleSelect>
                            </div>
                            <ValidationMessage For="@(() => Model.MachineStateList)" style="color:red" />
                        </div>
                        
                    </div>

                    <div class="filter_row">
                        <div class="filter_colume">
                            <div class="filter_row_around">
                                <span>有效时间段</span><RangePicker TValue="DateTime?[]" Value="EffecitiveTime" OnChange="@(date => onDateChage(date, 1))" />
                            </div>
                            <ValidationMessage For="@(() => Model.EffecitiveTime)" style="color:red" />
                        </div>
                        
                        <div class="filter_colume">
                            <div class="filter_row_around">
                                <span style="margin-right:5%">播放时段</span><RangePicker TValue="DateTime?[]" Value="playRange" Picker="DatePickerType.Time" Format="@("HH")" OnChange="@(date => onDateChage(date, 2))" />
                            </div>
                            <ValidationMessage For="@(() => Model.StartTime)" style="color:red" />
                        </div>
                        
                    </div>

                    <div class="filter_row">
                        <div class="filter_colume">
                            <div class="filter_row_around">
                                <span>下发油站</span>
                                <SimpleSelect DefaultValue="@Model.BusinessUnitID.ToString()" Disabled="@(Model.Type == 2)" OnSelectedItemChanged="@(data => OnSelectItemChange(2, data, editContext))" style="width:80%">
                                    <SelectOptions>
                                        @foreach (var department in Model.siteInfos)
                                        {
                                            <SimpleSelectOption Value="@department.Id.ToString()" Label="@department.Name" style="width:80%" />
                                        }
                                    </SelectOptions>
                                </SimpleSelect>
                            </div>
                            <ValidationMessage For="@(() => Model.BusinessUnitID)" style="color:red" />
                        </div>
                        

                        <div class="filter_colume">
                            <div class="filter_row_around">
                                <span>备注</span><Input Placeholder="备注" @bind-Value="Model.Remark" style="width:80%" />
                            </div>
                            <ValidationMessage For="@(() => Model.Remark)" style="color:red" />
                        </div>
                    </div>

                    @if (Model?.Type == 1)
                    {   
                        <div class="upload_box">
                            <div class="upload-container">
                                <div class="custom-upload-content">
                                    <Icon Type="upload" />
                                    <div>点击上传文件</div>
                                    @if (selectedFile != null)
                                    {
                                        <div class="file-name">@selectedFile.Name</div>
                                    }
                                </div>

                                <InputFile OnChange="OnFileSelected"
                                           Class="transparent-input-file" />
                            </div>
                        </div>
                    }

                    <div class="filter_row" style="justify-content:end;margin-top:1%;">
                        <button Icon="plus" type="button" @onclick="() => HandleSubmit(editContext)" style="margin-right:2%">确定</button>
                        <button Icon="reload" @onclick="Close" style="margin-right:2%">取消</button>
                    </div>
                </EditForm>
                
            }

            @if (isUploading)
            {
                <div style="position: absolute; inset: 0; background: rgba(255,255,255,0.6); z-index: 100;">
                    <Spin Tip="上传中..."
                          Style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);" />
                </div>
            }

            @if(Model?.Type == 3)
            {
                <h3>是否删除广告？@(Model.FileName)</h3>
                <div class="filter_row" style="justify-content:end;margin-top:5%;">
                    <Button Icon="plus" OnClick="onSure" Style="margin-right:2%">确定</Button>
                    <Button Icon="reload" OnClick="Close" Style="margin-right:2%">取消</Button>
                </div>
            }

            
        </div>
        
    </div>
}


@code {

    /// <summary>
    /// 信息回调
    /// </summary>
    [Parameter] public EventCallback<MediaDialogModel> ModelChanged { get; set; }

    /// <summary>
    /// 打开/关闭窗口回调
    /// </summary>
    [Parameter] public EventCallback<bool> IsVisibleChanged { get; set; }

    /// <summary>
    /// 信息回调
    /// </summary>
    [Parameter] public EventCallback<MediaDialogModel> onCallback { get; set; }

    /// <summary>
    /// 打开/关闭窗口回调
    /// </summary>
    [Parameter] public EventCallback<bool> onVisibleCallback { get; set; }

    /// <summary>
    /// 数据
    /// </summary>
    [Parameter] public MediaDialogModel Model { get; set; }

    /// <summary>
    /// 配置是否弹窗
    /// </summary>
    [Parameter] public bool IsVisible { get; set; }

    /// <summary>
    /// 上传文件
    /// </summary>
    private List<UploadFileItem> fileList = new List<UploadFileItem>();

    /// <summary>
    /// 用于显示当前有效时间范围
    /// </summary>
    private DateTime?[] EffecitiveTime = new DateTime?[2];

    /// <summary>
    /// 用于显示当前播放时段
    /// </summary>
    private DateTime?[] playRange = new DateTime?[2];

    private Dictionary<string, string> uploadFileHeader = new Dictionary<string, string>();

    [Inject] public HttpClient Http { get; set; } = default!;
    [Inject] public MessageService Message { get; set; } = default!;
    private ElementReference inputFileRef;
    private IBrowserFile? selectedFile;
    private bool isUploading = false;

    protected override void OnParametersSet()
    {
        fileList.Clear();
        selectedFile = null;
        uploadFileHeader["Authorization"] = Global.GetToken();
        EffecitiveTime = new DateTime?[]
        {
            Model?.EffecitiveTime,
            Model?.FailureTime
        };

        int startTimeInt = Math.Max(0, Math.Min(23, Model?.StartTime ?? 0));
        int endTimeInt = Math.Max(0, Math.Min(23, Model?.EndTime ?? 0));
        DateTime startTime = DateTime.Today.AddHours(startTimeInt);
        DateTime endTime = DateTime.Today.AddHours(endTimeInt);
        playRange = new DateTime?[]
        {
          startTime,endTime
        };
    }


    /// <summary>
    /// 关闭弹窗
    /// </summary>
    public async Task Close()
    {
        await OnlyClose();
        if(Model.SavePath.IsNotNullOrEmpty()) File.Delete(Model.SavePath);
    }
    /// <summary>
    /// 仅关闭弹窗
    /// </summary>
    /// <returns></returns>
    private async Task OnlyClose()
    {
        if (IsVisibleChanged.HasDelegate)
        {
            await IsVisibleChanged.InvokeAsync(false);
        }

        if (onVisibleCallback.HasDelegate)
        {
            await onVisibleCallback.InvokeAsync(false);
        }
    }

    private void OnFileSelected(InputFileChangeEventArgs e)
    {
        // if (e.Value is not IBrowserFile file) return;
        var siteinfo = Model.siteInfos.Find(it => it.Id == Model.BusinessUnitID);
        if (siteinfo != null && e.File.Size > siteinfo.MaxSize)
        {
            Message.Error("上传文件超过限制大小");
            return;
        }

        selectedFile = e.File;
        Model.FileName = e.File.Name;
    }

    private async Task UploadFile()
    {
        if (isUploading || selectedFile == null) return;

        isUploading = true;
        StateHasChanged();

        try
        {
            const long maxFileSize = 300 * 1024 * 1024; // 300 MB

            using var stream = selectedFile.OpenReadStream(maxFileSize);
            using var content = new MultipartFormDataContent();

            content.Add(new StreamContent(stream), "file", selectedFile.Name);
            content.Add(new StringContent(Model.BusinessUnitID.ToString()), "siteId");

            var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:5076/api/File/UploadMedia")
            {
                Content = content
            };
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Global.Token);

            // 发送请求
            var httpResponse = await Http.SendAsync(request);
            httpResponse.EnsureSuccessStatusCode();

            var responseJson = await httpResponse.Content.ReadAsStringAsync();
            var response = JsonSerializer.Deserialize<Service.Output.Response<Service.Output.MediaFileUploadOutput>>(responseJson);

            Model.FileName = response?.data.fileName ?? "";
            Model.SavePath = response?.data.savePath ?? "";
            Model.GuidFileName = response?.data.guidName ?? "";
            Model.FileExtension = response?.data.extension ?? "";


            // Message.Success("上传成功！");
            // selectedFile = null; // 清空
        }
        catch (Exception ex)
        {
            Message.Error( $"上传失败: {ex.Message}");
            Model.FileName = "";
        }
        finally
        {
            isUploading = false;
            StateHasChanged();
        }
    }

    /// <summary>
    /// 上传文件完毕
    /// </summary>
    /// <param name="info"></param>
    private void OnUploadCompleted(UploadInfo info)
    {
        // _upload.StartUpload()
        string responseJson =  info.File.Response;
        var response = JsonSerializer.Deserialize<Service.Output.Response<Service.Output.MediaFileUploadOutput>>(responseJson);

        Model.FileName = response?.data.fileName ?? "";
        Model.SavePath = response?.data.savePath ?? "";
        Model.GuidFileName = response?.data.guidName ?? "";
        Model.FileExtension = response?.data.extension ?? "";

    }

    /// <summary>
    /// 文件上传组件——删除事件
    /// </summary>
    /// <param name="fileItem"></param>
    /// <returns></returns>
    private async Task<bool> OnRemove(UploadFileItem fileItem)
    {
        Console.WriteLine(fileItem);
        if (Model.SavePath.IsNotNullOrEmpty()) File.Delete(Model.SavePath);
        return true;
    }

    /// <summary>
    /// 单选选择器选择事件
    /// </summary>
    /// <param name="type">1:油机状态；2：站点</param>
    /// <param name="value">选择的值</param>
    private void OnSelectItemChange(int type, string value, EditContext editContext)
    {
        Console.WriteLine(value);
        switch (type)
        {
            case 1:
                int state = -1;
                int.TryParse(value, out state);
                Model.MediaState = state;
                editContext.NotifyFieldChanged(FieldIdentifier.Create(() => Model.MediaState));
                break;
            case 2:
                var siteinfo = Model.siteInfos.Find(it => it.Id.ToString().Equals(value));
                if (siteinfo != null)
                {
                    if(selectedFile != null && selectedFile.Size > siteinfo.MaxSize)
                    {
                        Message.Error("上传文件超过限制大小");
                        selectedFile = null;
                        Model.FileName = "";
                    }
                    Model.GroupID = siteinfo.ParentId;
                    Model.BusinessUnitID = siteinfo.Id;

                    editContext.NotifyFieldChanged(FieldIdentifier.Create(() => Model.BusinessUnitID));
                }

                break;
        }

    }

    /// <summary>
    /// 多选选择器选择事件
    /// </summary>
    /// <param name="values">选择的值</param>
    private void OnSelectItemsChange(IEnumerable<string> values ,EditContext editContext)
    {
        Console.WriteLine(values);
        if (values.Count() <= 0)
        {
            Model.MachineStateList = Model.getAllMachineStateList();
        } else
        {
            Model.MachineStateList = values.ToList();
        }

        editContext.NotifyFieldChanged(FieldIdentifier.Create(() => Model.MachineStateList));
    }

    /// <summary>
    /// 日期选择器选择回调
    /// </summary>
    /// <param name="value">选择的日期</param>
    /// <param name="type">1：有效时间段；2：播放时段</param>
    private void onDateChage(DateRangeChangedEventArgs<DateTime?[]> value, int type)
    {
        switch (type)
        {
            case 1:
                Model.EffecitiveTime = value.Dates[0];
                Model.FailureTime = value.Dates[1];
                EffecitiveTime = new DateTime?[]
                {
                    value.Dates[0],value.Dates[1]
                };
                break;
            case 2:
                DateTime? startTime = value.Dates[0];
                DateTime? endTime = value.Dates[1];
                Model.StartTime = startTime?.Hour;
                Model.EndTime = endTime?.Hour;

                playRange = new DateTime?[]
                {
                     value.Dates[0], value.Dates[1]
                };

                break;
        }
    }

    private async Task HandleSubmit(EditContext editContext)
    {

        if(editContext.Validate())
        {
            if(Model.BusinessUnitID <= 0)
            {
                Message.Error("请绑定油站");
                return;
            }

            await UploadFile();
            await onSure();
            
        }
    }

    /// <summary>
    /// 确定按钮事件
    /// </summary>
    /// <returns></returns>
    private async Task onSure()
    {
        if (ModelChanged.HasDelegate)
        {
            await ModelChanged.InvokeAsync(Model);
        }

        if (onCallback.HasDelegate)
        {
            await onCallback.InvokeAsync(Model);
        }
        await OnlyClose();
    }



}


<style>
    /* 遮罩层：全屏、半透明 */
    .modal-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100vw;
        height: 100vh;
        background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色遮罩 */
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 1000;
    }

    /* 弹窗内容：白色卡片，居中由父容器控制 */
    .modal-content {
        background: white;
        border-radius: 8px;
        width: 80%;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
        /* 注意：不要设 height: 100vh，否则会拉满全屏 */
    }

    .filter_box {
        display: flex;
        flex-direction: column;
        align-items: center;
        background: #ffffff;
        padding: 2%;
    }

    .filter_row {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        margin-top: 2%;
    }

    .filter_row_around {
        display: flex;
        flex-direction: row;
        justify-content: space-around;
        align-items: center;
        width: 100%;
        margin-top: 2%;
    }

    .filter_colume {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: end;
        width: 100%;
        margin-top: 2%;
    }

    .upload_box{
        display:flex;
        flex-direction:column;
        justify-content:center;
        align-items:center;
        margin-top:1%;
    }

    .upload-container {
        position: relative;
        display: inline-block;
        width: 50%;
        height:160px;
        padding:3%;
    }

    .custom-upload-content {
        width: 100%;
        height: 100%;
        border: 2px dashed #d9d9d9;
        border-radius: 8px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        background-color: #fafafa;
        z-index: 1;
        position: relative;
    }

    .transparent-input-file {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        opacity: 0;
        cursor: pointer;
        z-index: 2;
    }
</style>
