@page "/manage/user"

@using log4net;

<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="nickname" />
                                </RadzenColumn>
                                <RadzenColumn Size="8">
                                    <RadzenTextBox @bind-Value="nickname" Style="width: 100%;" Name="nickname"></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="@(usersToInsert.Count() > 0)" Text="新增" />
                    </RadzenStack>
                </RadzenFieldset>
            </form>
        </div>
        <div class="col-12 mb-4">

            <RadzenDataGrid @ref="grid"
            LoadData="@LoadData"
            IsLoading="@isLoading"
            Count="@count"
            EmptyText="无数据"
            Data="@userList"
            Page="@Reset"
            EditMode="DataGridEditMode.Single"
            AllowColumnResize="true" AllowAlternatingRows="false"
            RowUpdate="@((Pojo.User u) => { OnUpdateRow(u); })" RowCreate="@((Pojo.User u) => { OnCreateRow(u); })"
            SelectionMode="DataGridSelectionMode.Single"
            AllowPaging="true" PageSize="10" PagerHorizontalAlign="HorizontalAlign.Left" ShowPagingSummary="true" PagingSummaryFormat="{0}/{1} 共{2}条数据">
                <Columns>
                    <RadzenDataGridColumn Title="ID" Property="Id"></RadzenDataGridColumn>
                    <RadzenDataGridColumn Title="用户名" Property="NickName">
                        <EditTemplate Context="user">
                            <RadzenTextBox Name="NickName" @bind-Value="user.NickName" Style="width:100%; display: block;" />
                            <RadzenRequiredValidator Text="请填写用户名" Component="NickName" Popup="true" />
                        </EditTemplate>
                    </RadzenDataGridColumn>
                    <RadzenDataGridColumn Title="账号" Property="Username">
                        <EditTemplate Context="user">
                            <RadzenTextBox Name="Username" @bind-Value="user.Username" Style="width:100%; display: block;" />
                            <RadzenRequiredValidator Text="请填写账号" Component="Username" Popup="true" />
                        </EditTemplate>
                    </RadzenDataGridColumn>
                    <RadzenDataGridColumn Title="权限" Property="role.RoleName">
                        <EditTemplate Context="user">
                            <RadzenDropDown Name="RoleId" @bind-Value="user.RoleId" Data="@roles" TextProperty="RoleName" ValueProperty="Id" Style="width:100%; display: block;"
                            InputAttributes="@(new Dictionary<string,object>(){ { "aria-label", "Select customer" }})" />
                            <RadzenRequiredValidator Text="请选择角色" Component="RoleId" Popup="true" />
                        </EditTemplate>

                    </RadzenDataGridColumn>

                    <RadzenDataGridColumn Context="user" Filterable="false" Sortable="false" TextAlign="TextAlign.Right" Frozen="true" FrozenPosition="FrozenColumnPosition.Right">
                        <Template Context="user">
                            <RadzenButton Icon="edit" ButtonStyle="ButtonStyle.Light" Variant="Variant.Flat" Size="ButtonSize.Medium" Click="@(args => EditRow(user))" @onclick:stopPropagation="true">
                            </RadzenButton>


                            <RadzenButton Icon="edit_document" ButtonStyle="ButtonStyle.Warning" Variant="Variant.Flat" Shade="Shade.Lighter" Size="ButtonSize.Medium" Click="@(args => Signatrue(user))" @onclick:stopPropagation="true">
                            </RadzenButton>

                            <RadzenButton Icon="fingerprint" ButtonStyle="ButtonStyle.Info" Variant="Variant.Flat" Size="ButtonSize.Medium" class="my-1 ms-1" Click="@(args => Reg2ZWJ(user))" @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(user))" @onclick:stopPropagation="true">
                            </RadzenButton>


                            <RadzenButton ButtonStyle="ButtonStyle.Danger" Icon="https" Variant="Variant.Flat" Shade="Shade.Lighter" Size="ButtonSize.Medium" class="my-1 ms-1" Click="@(args => ResetPasswordRow(user))" aria-label="ResetPassword">
                            </RadzenButton>

                        </Template>
                        <EditTemplate Context="user">
                            <RadzenButton Icon="check" ButtonStyle="ButtonStyle.Success" Variant="Variant.Flat" Size="ButtonSize.Medium" Click="@((args) => SaveRow(user))" aria-label="Save">
                            </RadzenButton>
                            <RadzenButton Icon="close" ButtonStyle="ButtonStyle.Light" Variant="Variant.Flat" Size="ButtonSize.Medium" class="my-1 ms-1" Click="@((args) => CancelEdit(user))" 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(user))" aria-label="Delete">
                            </RadzenButton>
                            <RadzenButton ButtonStyle="ButtonStyle.Danger" Icon="https" Variant="Variant.Flat" Shade="Shade.Lighter" Size="ButtonSize.Medium" class="my-1 ms-1" Click="@(args => ResetPasswordRow(user))" aria-label="ResetPassword">
                            </RadzenButton> 
                        </EditTemplate>
                    </RadzenDataGridColumn>
                </Columns>
            </RadzenDataGrid>
        </div>
    </div>
</div>

@code {
    @inject IUserDao userDao;
    @inject IRoleDao roleDao;
    @inject DialogService dialogService;
    @inject NotificationService _message
    RadzenDataGrid<Pojo.User> grid;
    bool isLoading;
    int count;
    private IEnumerable<Pojo.User>? userList;
    string nickname;
    DateTime OrderDate;
    private readonly ILog logger = LogManager.GetLogger(typeof(Pages.User));

    List<Pojo.Role> roles;




    List<Pojo.User> usersToInsert = new List<Pojo.User>();
    List<Pojo.User> usersToUpdate = new List<Pojo.User>();

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        roles = await roleDao.GetAllRoles();
    }

    void Reset()
    {
        usersToInsert.Clear();
        usersToUpdate.Clear();
    }

    async Task Reg2ZWJ(Pojo.User user)
    {
        await dialogService.OpenAsync<FingerRegDialog>(
                $"录入指纹",
              new Dictionary<string, object>() { { "userId", user.Id } },
              new DialogOptions() { Width = "55vw", Resizable = true, Draggable = true, ShowClose = false }
        );
    }

    async Task Signatrue(Pojo.User user)
    {
        var flag = await dialogService.OpenAsync<SignatureDialog>(
                $"签名-{user.NickName}",
              new Dictionary<string, object>() { { "user", user } },
              new DialogOptions() { Width = "55vw", Resizable = true, Draggable = true, ShowClose = true }
        );
        if(flag != null && flag)
        {
            await reloadGrid();
        }
    }


    void Reset(Pojo.User user)
    {
        usersToInsert.Remove(user);
        usersToUpdate.Remove(user);
    }

    void OnCurrentDateChanged(DateTime args)
    {
        OrderDate = new DateTime(args.Year, args.Month, args.Day);
    }

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

        var result = await userDao.GetAllByNickname(nickname, args.Top, args.Skip);
        // Update the Data property
        userList = result.Desserts;
        // Update the count
        count = result.TotalDesserts;

        isLoading = false;
    }

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

    async Task EditRow(Pojo.User user)
    {

        Reset();

        usersToUpdate.Add(user);
        await grid.EditRow(user);
    }

    void OnUpdateRow(Pojo.User user)
    {
        Reset(user);

        // 数据库更新
        userDao.UpdateUser(user);
        if(user.role.Id != user.RoleId)
        {
            grid.Reload();
        }
    }

    async Task SaveRow(Pojo.User user)
    {
        await grid.UpdateRow(user);
    }

    void CancelEdit(Pojo.User user)
    {
        Reset(user);

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

    async Task DeleteRow(Pojo.User user)
    {
        Reset(user);

        if (userList.Contains(user))
        {
            //弹出确认提示框
            var b = await dialogService.OpenAsync<ConfirmDialog>(
               $"删除确认",
             new Dictionary<string, object>() { { "confirmInfo", "确认要删除用户："+user.Username+"吗？" } },
             new DialogOptions() { Width = "45vw", Resizable = true, Draggable = true, ShowClose = false });
            if (b)
            {
                // 数据库删除
                userDao.DeleteeUser(user.Id);
            }
            await grid.Reload();
        }
        else
        {
            grid.CancelEditRow(user);
            await grid.Reload();
        }
    }
    //重置密码
    async Task ResetPasswordRow(Pojo.User user)
    {
        Reset(user);

        if (userList.Contains(user))
        {
            //弹出确认提示框
            var b = await dialogService.OpenAsync<ConfirmDialog>(
               $"密码重置确认",
             new Dictionary<string, object>() { { "confirmInfo", "确认要重置用户：" + user.Username+" 的密码吗？" } },
             new DialogOptions() { Width = "45vw", Resizable = true, Draggable = true, ShowClose = false });
            if (b)
            {
                // 数据库重置密码
                userDao.ResetPassword(user.Id);
                //提示密码已重置，下次登录请使用重置后的密码
                _message.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = "提示", Detail = $"密码已重置，下次登录请使用重置后的密码", Duration = 4000 });
            }
            await grid.Reload();
        }
        else
        {
            grid.CancelEditRow(user);
            await grid.Reload();
        }
    }

    async Task InsertRow()
    {
        
        Reset();
        var user = new Pojo.User()
        {
            RoleId = roles[0].Id,
        };
        usersToInsert.Add(user);
        await grid.InsertRow(user);
    }

    void OnCreateRow(Pojo.User user)
    {
        // 数据库添加用户
        userDao.InsertUser(user);
        usersToInsert.Remove(user);
        grid.Reload();
    }






}
