@namespace MasaBlazorApp3
@using MasaBlazorApp3.Pojo.Config
@using MasaBlazorApp3.Util
@using log4net
@inherits LayoutComponentBase

<style>
    .my-tab-menu {
        padding: 10px 20px;
        flex-shrink: 0;
    }

        .my-tab-menu:hover {
            box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.7); /* 阴影效果 */
            text-decoration: none !important;
            background: #255dd6;
            border-radius: 20px;
        }

    a.active {
        background: #255dd4;
        border-radius: 20px;
    }

</style>

<RadzenLayout>
    <RadzenHeader Style="height: 75px;">
        <RadzenRow JustifyContent="JustifyContent.Start" AlignItems="AlignItems.Center" Style="height: 100%;">
            <RadzenColumn Size="1">
                <RadzenStack Orientation="Orientation.Horizontal" AlignItems="AlignItems.Center">
                    <RadzenIcon Icon="chevron_left" Style="font-size:3rem;cursor: pointer;padding: 0 10px;" @onclick="@(() => { backHome(); })" />
                </RadzenStack>
            </RadzenColumn>
            <RadzenColumn Size="10" Orientation="Orientation.Horizontal" AlignItems="AlignItems.Center" JustifyContent="JustifyContent.Start">
                @if (children.Count > 5)
                {

                    <RadzenStack Style="width: 100%; overflow-x: auto; white-space: nowrap; display: flex;" Orientation="Orientation.Horizontal" AlignItems="AlignItems.Center">
                        @foreach (Premission p in children)
                        {
                            if (childrenIds.Any(id => id == p.Id))
                            {
                                <RadzenLink Match="NavLinkMatch.All" class="my-tab-menu" Path="@p.PremissionPath">@p.PremissionName</RadzenLink>
                            }
                        }
                        @if (children.Any(c => c.PremissionPath.Contains("Box")))
                        {
                            <RadzenIcon Icon="card_travel" Style="font-size:2rem;cursor: pointer;" class="rz-ripple" IconColor="white" @onclick="@(() => { OpenStorage(); })" />
                        }
                    </RadzenStack>
                }
                else
                {


                    <RadzenStack Style="width: 100%; overflow-x: auto; white-space: nowrap; display: flex;" Orientation="Orientation.Horizontal" JustifyContent="JustifyContent.Center" AlignItems="AlignItems.Center">
                        @foreach (Premission p in children)
                        {
                            if (childrenIds.Any(id => id == p.Id))
                            {
                                <RadzenLink Match="NavLinkMatch.All" class="my-tab-menu" Path="@p.PremissionPath">@p.PremissionName</RadzenLink>
                            }
                        }
                        @if (children.Any(c => c.PremissionPath.Contains("Box")))
                        {
                            <RadzenIcon Icon="card_travel" Style="font-size:2rem;cursor: pointer;" class="rz-ripple" IconColor="white" @onclick="@(() => { OpenStorage(); })" />
                        }
                    </RadzenStack>
                }
            </RadzenColumn>
            <RadzenColumn Size="1">
                <RadzenStack Orientation="Orientation.Horizontal" AlignItems="AlignItems.Center" JustifyContent="JustifyContent.Center">
                    <RadzenIcon Icon="exit_to_app" Style="font-size:2rem;cursor: pointer;" class="rz-ripple" IconColor="white" @onclick="@(() => { logout(); })" />
                </RadzenStack>
            </RadzenColumn>
        </RadzenRow>
    </RadzenHeader>
    <RadzenBody>
        <div class="container-fluid rz-p-1">
            <RadzenCard>
                @Body
            </RadzenCard>
        </div>
    </RadzenBody>
    <RadzenNotification />
    <RadzenComponents />
</RadzenLayout>

@code
{
    @inject IJSRuntime JSRuntime
    @inject GlobalStateService globalStateService;
    @inject NavigationManager na;
    int selectedIndex = 0;
    Pojo.User Operator;
    List<int> childrenIds;
    List<Premission> children;
    @inject Microsoft.Extensions.Options.IOptions<Pojo.Config.SettingConfig> setting;
    @inject PortUtil _portUtil;
    @inject NotificationService _message
    private readonly ILog logger = LogManager.GetLogger(typeof(MainLayout));
    bool currentPage = true;

    protected override void OnInitialized()
    {
        string Uri = na.Uri;
        string[] s = Uri.Split("/");

        Operator = globalStateService.Operator;
        Premission parent = new Premission().getAdminPremission().Find(p => p.PremissionPath == s[3]);
        childrenIds = Operator.role.permissionIds.Where(id => id - (parent.Id * 10) < 10).ToList();
        children = parent.Items.ToList();

        if (setting.Value.autoOutLog > 0)
        {
            // 是否需要自动退出
            var promiseUtil = new PromiseUtil<object>();
            promiseUtil.taskAsyncLoop(500, null, async (data, next, stop) =>
           {
               if (globalStateService.Operator == null || !currentPage)
               {

                   logger.Info($"MainLayout页自动退出循环停止{globalStateService.Operator == null},{!currentPage}");
                   stop();
               }
               else
               {
                   try
                   {
                       //没有在操作抽屉
                       if (!_portUtil.Operate)
                       {
                           // 无人操作鼠标键盘
                           if ((DateTime.Now - _portUtil.dateTime).TotalSeconds > setting.Value.autoOutLog && (DateTime.Now - _portUtil.mouseClickTime).TotalSeconds > setting.Value.autoOutLog)
                           {
                               logger.Info($"设备{setting.Value.autoOutLog}内无人操作，用户【{Operator?.NickName}】自动退出登录,_portUtil.Operate:{_portUtil.Operate},totalSecond:{(DateTime.Now - _portUtil.dateTime).TotalSeconds},lastInputTime:{(DateTime.Now - _portUtil.mouseClickTime).TotalSeconds},autoOutLog:{setting.Value.autoOutLog}");
                               globalStateService.Operator = null;
                               globalStateService.Reviewer = null;
                               na.NavigateTo("");
                               stop();
                           }
                           else
                           {
                               next();
                           }
                       }
                       else
                       {
                           next();
                       }
                   }
                   catch (Exception ex)
                   {
                       logger.Info($"检查是否自动退出循环异常:{ex.Message}");
                       next();
                   }
               }
           });
        }

        base.OnInitialized();
    }



    void backHome()
    {
        PortUtil.speechSynthesizer.SpeakAsyncCancelAll();
        currentPage = false;
        na.NavigateTo("");
    }

    void logout()
    {
        PortUtil.speechSynthesizer.SpeakAsyncCancelAll();
        globalStateService.Operator = null;
        globalStateService.Reviewer = null;
        na.NavigateTo("");
    }
    async Task OpenStorage()
    {
        try
        {
            var b = await _portUtil.OpenStorage();
        }
        catch (Exception ex)
        {
            logger.Info($"开储物箱发生错误，{ex.Message}");
            _message.Notify(
                new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"开储物箱发生错误，{ex.Message}", Duration = 4000 }
            );
        }
    }
    private DotNetObjectReference<MainLayout>? dotNetObjectReference;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            dotNetObjectReference = DotNetObjectReference.Create(this);
            await JSRuntime.InvokeVoidAsync("registerMouseClickHandler", dotNetObjectReference);
        }
    }

    [JSInvokable]
    public void HandleMouseClick(int clientX, int clientY)
    {
        // 这里处理鼠标点击事件，例如记录日志或更新状态
        // Console.WriteLine($"Mouse clicked at: ({clientX}, {clientY})");
        _portUtil.mouseClickTime = DateTime.Now;
    }

    public void Dispose()
    {
        dotNetObjectReference?.Dispose();
    }
} 