@page "/manage/role"


<div class="container-fluid">
    <div class="row">
        <div class="col-12 mb-4">

            <form onsubmit="@(() => grid.Reload())">
                <RadzenFieldset Text="查询">
                    <RadzenStack Orientation="Orientation.Horizontal" JustifyContent="JustifyContent.SpaceBetween">
                        <RadzenStack Orientation="Orientation.Horizontal" Gap="1rem">
                            <RadzenRow AlignItems="AlignItems.Center">
                                <RadzenColumn Size="4">
                                    <RadzenLabel Text="角色名称" Component="RoleName" />
                                </RadzenColumn>
                                <RadzenColumn Size="8">
                                    <RadzenTextBox @bind-Value="RoleName" Style="width: 100%;" Name="RoleName"></RadzenTextBox>
                                </RadzenColumn>
                            </RadzenRow>

                            <RadzenRow AlignItems="AlignItems.Center">
                                <RadzenColumn Size="12">
                                    <RadzenButton Size="ButtonSize.Medium" ButtonType="ButtonType.Submit" IsBusy="isLoading" Icon="search" Text="查询" />
                                    <RadzenButton Size="ButtonSize.Medium" Click="reloadGrid" IsBusy="isLoading" Icon="refresh" Text="重置" ButtonStyle="ButtonStyle.Warning" />
                                </RadzenColumn>
                            </RadzenRow>
                        </RadzenStack>
                        <RadzenButton Size="ButtonSize.Medium" ButtonStyle="ButtonStyle.Success" Icon="add_circle_outline" Click="@(() => InsertRow())" Disabled="@(rolesToInsert.Count() > 0)" Text="新增" />
                    </RadzenStack>
                </RadzenFieldset>
            </form>
        </div>
        <div class="col-12 mb-4">
            <RadzenDataGrid @ref="grid"
            LoadData="@LoadData"
            IsLoading="@isLoading"
            Count="@count"
            EmptyText="无数据"
            Data="@roleList"
            AllowColumnResize="true" AllowAlternatingRows="false"
            RowUpdate="@((Pojo.Role r) => { OnUpdateRow(r); })" RowCreate="@((Pojo.Role r) => { OnCreateRow(r); })"
            SelectionMode="DataGridSelectionMode.Single"
            AllowPaging="true" PageSize="10" PagerHorizontalAlign="HorizontalAlign.Left" ShowPagingSummary="true" PagingSummaryFormat="{0}/{1} 共{2}条数据">
                <Columns>
                    <RadzenDataGridColumn Width="50px" Title="ID" Property="Id"></RadzenDataGridColumn>
                    <RadzenDataGridColumn Width="120px" Title="角色名称" Property="RoleName">
                        <EditTemplate Context="role">
                            <RadzenTextBox Name="RoleName" @bind-Value="role.RoleName" Style="width:100%; display: block;" />
                            <RadzenRequiredValidator Style="position: absolute;z-index: 9999;" Text="请填写角色名称" Component="RoleName" Popup="true" />
                        </EditTemplate>
                    </RadzenDataGridColumn>
                    <RadzenDataGridColumn Title="权限" Property="permissions">
                        <Template Context="role">
                            @string.Join(", ", allPremissions.Where(g => role.permissionIds?.Contains(g.Id) == true).Select(g => $"{g.PremissionName}"))
                        </Template>
                        <EditTemplate Context="role">
                            <RadzenDropDown @ref=dd @bind-Value=@role.permissionIds TValue="IEnumerable<int>" AllowClear="true" Name="Permissions"
                            Data=@allPremissions Style="width: 100%; max-width: 400px; display: block;" ItemRender="ItemRender">
                                <Template Context="p">
                                    <RadzenCheckBox TValue="bool?" TriState=false Value="@IsGroupSelected(role,p)" Change="@(args => SelectGroup(args, role, (Premission)p))" />
                                    <RadzenLabel Style=@($"margin-inline-start: 0.5rem; font-weight: {(p.Parent == null ? "bold" : "normal")}")
                                    Text="@(p.PremissionName)"
                                    onclick="event.target.previousElementSibling.querySelector('.rz-chkbox-box').click()" />
                                </Template>
                                <ValueTemplate Context="p">
                                    @string.Join(", ", allPremissions.Where(g => role.permissionIds?.Contains(g.Id) == true).Take(dd.MaxSelectedLabels).Select(g => $"{g.PremissionName}"))
                                </ValueTemplate>
                            </RadzenDropDown>
                            <RadzenRequiredValidator Style="position: absolute;z-index: 9999;" Text="请选择权限" Component="Permissions" Popup="true" />
                        </EditTemplate>
                    </RadzenDataGridColumn>


                    <RadzenDataGridColumn Width="200px" Context="role" Filterable="false" Sortable="false" TextAlign="TextAlign.Right" Frozen="true" FrozenPosition="FrozenColumnPosition.Right">
                        <Template Context="role">
                            <RadzenButton Icon="edit" ButtonStyle="ButtonStyle.Light" Variant="Variant.Flat" Size="ButtonSize.Medium" Click="@(args => EditRow(role))" @onclick:stopPropagation="true">
                            </RadzenButton>
                            <RadzenButton ButtonStyle="ButtonStyle.Danger" Icon="delete" Variant="Variant.Flat" Shade="Shade.Lighter" Size="ButtonSize.Medium" class="my-1 ms-1" Click="@(args => DeleteRow(role))" @onclick:stopPropagation="true">
                            </RadzenButton>
                        </Template>
                        <EditTemplate Context="role">
                            <RadzenButton Icon="check" ButtonStyle="ButtonStyle.Success" Variant="Variant.Flat" Size="ButtonSize.Medium" Click="@((args) => SaveRow(role))" aria-label="Save">
                            </RadzenButton>
                            <RadzenButton Icon="close" ButtonStyle="ButtonStyle.Light" Variant="Variant.Flat" Size="ButtonSize.Medium" class="my-1 ms-1" Click="@((args) => CancelEdit(role))" aria-label="Cancel">
                            </RadzenButton>
                            <RadzenButton ButtonStyle="ButtonStyle.Danger" Icon="delete" Variant="Variant.Flat" Shade="Shade.Lighter" Size="ButtonSize.Medium" class="my-1 ms-1" Click="@(args => DeleteRow(role))" aria-label="Delete">
                            </RadzenButton>
                        </EditTemplate>
                    </RadzenDataGridColumn>

                </Columns>
            </RadzenDataGrid>
        </div>
    </div>
</div>

@code {
    @inject IRoleDao roleDao;
    @inject DialogService dialogService;
    RadzenDataGrid<Pojo.Role> grid;
    bool isLoading;
    int count;
    private IEnumerable<Pojo.Role>? roleList;


    RadzenDropDown<IEnumerable<int>> dd;
    IEnumerable<Premission> allPremissions;

    string RoleName;

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        List<Premission> t = new Premission().getAdminPremission();
        IEnumerable<Premission> t2 = Enumerable.Empty<Premission>();
        for (var i = 0; i < t.Count; i++)
        {
            t2 = t2.Concat(new Premission[] { t[i] });
            t2 = t2.Concat(t[i].Items);
        }

        allPremissions = t2;
    }



    async Task LoadData(LoadDataArgs args)
    {
        isLoading = true;

        var result = await roleDao.GetRolesByName(RoleName, args.Top, args.Skip);
        // Update the Data property
        roleList = result.Desserts;
        // Update the count
        count = result.TotalDesserts;

        isLoading = false;
    }

    async Task reloadGrid()
    {
        RoleName = "";
        await grid.Reload();
    }


    List<Pojo.Role> rolesToInsert = new List<Pojo.Role>();
    List<Pojo.Role> rolesToUpdate = new List<Pojo.Role>();

    void Reset()
    {
        rolesToInsert.Clear();
        rolesToUpdate.Clear();
    }

    void Reset(Pojo.Role role)
    {
        rolesToInsert.Remove(role);
        rolesToUpdate.Remove(role);
    }

    async Task EditRow(Pojo.Role role)
    {

        Reset();

        rolesToUpdate.Add(role);
        await grid.EditRow(role);
    }

    void OnUpdateRow(Pojo.Role role)
    {
        Reset(role);

        // 数据库更新
        roleDao.UpdateRole(role);
    }

    async Task SaveRow(Pojo.Role role)
    {
        await grid.UpdateRow(role);
    }

    void CancelEdit(Pojo.Role role)
    {
        Reset(role);

        grid.CancelEditRow(role);
        grid.Reload();
    }

    async Task DeleteRow(Pojo.Role role)
    {
        Reset(role);

        if (roleList.Contains(role))
        {
            //弹出确认提示框
            var b = await dialogService.OpenAsync<ConfirmDialog>(
               $"删除确认",
             new Dictionary<string, object>() { { "confirmInfo", "确认要删除角色：" + role.RoleName+"吗？" } },
             new DialogOptions() { Width = "45vw", Resizable = true, Draggable = true, ShowClose = false });
            if (b)
            {
                // 数据库删除
                roleDao.DeleteRole(role.Id);
            }
            await grid.Reload();
        }
        else
        {
            grid.CancelEditRow(role);
            await grid.Reload();
        }
    }

    async Task InsertRow()
    {

        Reset();
        var role = new Pojo.Role();
        rolesToInsert.Add(role);
        await grid.InsertRow(role);
    }

    void OnCreateRow(Pojo.Role role)
    {
        // 数据库添加用户
        int id = roleDao.InsertRole(role);
        rolesToInsert.Remove(role);
        grid.Reload();
    }

    void ItemRender(DropDownItemRenderEventArgs<IEnumerable<int>> args)
    {
        // Use this code to prevent default item selection.
        args.Disabled = true;
        args.Attributes.Add("style", $"opacity:1;{(((Premission)args.Item).Parent == null ? "" : "margin-inline-start:1rem")}");
    }





    bool? IsGroupSelected(Pojo.Role role,Premission p)
    {
        IEnumerable<int> permissionIds = role.permissionIds;
        if (p.Parent == null)
        {
            return p.Items.Any() && p.Items.All(i => permissionIds?.Contains(i.Id) == true) ? true :
                p.Items.Any(i => permissionIds?.Contains(i.Id) == true) ? null : false;
        }

        return permissionIds?.Contains(p.Id) == true;
    }

    void SelectGroup(bool? value, Pojo.Role role, Premission p)
    {
        IEnumerable<int> permissionIds = role.permissionIds;
        var newValues = permissionIds ?? Enumerable.Empty<int>();
        var items = p.Parent == null ? p.Items.Select(i => i.Id) : new int[] { p.Id };
        role.permissionIds = value == true ? newValues.Concat(items) : newValues.Except(items);
    }




}
