@page "/system/role/permission/{RoleId:long}"
@inject ILogger<RoleList> Logger

<PageTitle>权限设置</PageTitle>
<Spin Spinning="loading">
    <Title Level="4">编辑角色权限</Title>
    <Card>
        <Form @ref="editForm" Model="model" LabelColSpan="2" WrapperColSpan="22" Class="search-form" OnFinish="OnFormFinishAsync">
            <FormItem Label="角色">
                为角色 <Text>@role?.Name</Text> 设置权限
            </FormItem>
            <FormItem Label="权限">
                <div class="ant-form-item-control-input-content">
                    @if (!PermissionGroups.Any())
                    {
                        <div>
                            <p>暂无权限可设置</p>
                        </div>
                    }
                    else
                    {
                        @foreach (var group in PermissionGroups)
                        {
                            <GridRow Style="padding-top:10px;">
                                <GridCol Span="24">
                                    <label class="ant-checkbox-wrapper">
                                        <span class="ant-checkbox @((@group.PermissionItems.Count(p => p.IsSelected) > 0 && @group.PermissionItems.Count(p => p.IsSelected) < @group.PermissionItems.Count) ? "ant-checkbox-indeterminate" : "")">
                                            <input class="ant-checkbox-input" type="checkbox"
                                                   @onchange="(e) => ToggleAllPermissions(group, (bool)e.Value!)"
                                                   checked="@group.PermissionItems.All(p => p.IsSelected)" />
                                            <span class="ant-checkbox-inner"></span>

                                        </span>
                                        <span>
                                            <span class="form-check-label fw-bold">
                                                @group.CategoryName
                                            </span>
                                            <small class="text-muted ms-2">
                                                (@group.PermissionItems.Count(p => p.IsSelected)/@group.PermissionItems.Count)
                                            </small>
                                        </span>
                                    </label>
                                </GridCol>
                            </GridRow>
                            <GridRow Style="margin-left:20px;margin-right:20px;">
                                @foreach (var permission in group.PermissionItems)
                                {
                                    <GridCol Span="6">
                                        <label class="ant-checkbox-wrapper">
                                            <span class="ant-checkbox">
                                                <input class="ant-checkbox-input" type="checkbox"
                                                       @bind="permission.IsSelected"
                                                       id="perm_@permission.Name" />
                                                <span class="ant-checkbox-inner"></span>

                                            </span>
                                            <span class="form-check-label" for="perm_@permission.Name">
                                                @permission.Description
                                                <small class="text-muted d-block">@permission.Name</small>
                                            </span>
                                        </label>
                                    </GridCol>
                                }
                            </GridRow>
                        }
                    }
                </div>
            </FormItem>
            <FormItem WrapperCol="new ColLayoutParam { Span = 24, Offset = 2 }">
                <Button Type="@ButtonType.Primary" HtmlType="submit" Loading="@isSaving">
                    @if (isSaving)
                    {
                        <span>保存中...</span>
                    }
                    else
                    {
                        <span>保存权限设置</span>
                    }

                </Button>
            </FormItem>
        </Form>

    </Card>
</Spin>
@code {
    [Parameter]
    public long RoleId { get; set; }

    bool loading = false;
    bool isSaving = false;
    Role role;
    List<RolePermissionGroup> PermissionGroups = new List<RolePermissionGroup>();

    [SupplyParameterFromForm]
    RoleModel model { get; set; } = new();
    Form<RoleModel> editForm = null!;


    protected override void OnInitialized()
    {
        base.OnInitialized();
    }

    protected override async Task OnParametersSetAsync()
    {
        loading = true;

        await LoadRoleAndPermission();

        loading = false;
        base.OnParametersSet();
    }

    async Task LoadRoleAndPermission()
    {
        var roleResult = await HttpService.Get<ApiResult<Role>>($"/api/role/{RoleId}");
        if (roleResult.Success)
        {
            if (roleResult.Data != null)
            {
                role = roleResult.Data;
                StateHasChanged();
            }
        }


        var apiResult = await HttpService.Get<ApiResult<List<RolePermissionGroup>>>($"/api/role/permission/{RoleId}");
        if (apiResult.Success)
        {
            if (apiResult.Data != null)
            {
                PermissionGroups = apiResult.Data;
                StateHasChanged();
            }
        }
    }

    private void ToggleAllPermissions(RolePermissionGroup group, bool isSelected)
    {
        foreach (var permission in group.PermissionItems)
        {
            permission.IsSelected = isSelected;
        }
        StateHasChanged();
    }

    async void OnFormFinishAsync()
    {
        isSaving = true;
        StateHasChanged();

        try
        {
            var selectedPermissions = PermissionGroups!
                .SelectMany(g => g.PermissionItems)
                .Where(p => p.IsSelected)
                .Select(p => p.Name)
                .ToList();

            model = role.Adapt<RoleModel>();
            model.Permission = string.Join(",", selectedPermissions);

            var url = $"api/role/edit";
            var result = await HttpService.Post<ApiResult<string>>(url, model);
            if (result.Success)
            {
                await ModalService.InfoAsync(new ConfirmOptions() { Title = "提示", Content = "权限设置保存成功!" });
            }
            else
            {
                await ModalService.InfoAsync(new ConfirmOptions() { Title = "提示", Content = "服务异常!" });
            }
            Navigation.NavigateTo("/system/role/list");
        }
        catch (Exception ex)
        {
            await ModalService.InfoAsync(new ConfirmOptions() { Title = "提示", Content = "保存权限设置失败!" });
        }
        finally
        {
            isSaving = false;
            StateHasChanged();
        }
    }
}
