@page "/system/user"
@attribute [ReuseTabsPage(Title = "用户管理")]

<Spin Spinning="Loading">
    <Table @ref="_Table"
           AutoHeight
           TItem="SystemUser"
           @bind-PageSize="Ps"
           @bind-PageIndex="Pi"
           Total="Total"
           DataSource="DataSource"
           @bind-SelectedRows="SelectedRows"
           ScrollX="1300"
           OnChange="OnChange">
        <TitleTemplate>
            <Flex Justify="FlexJustify.Start" Gap="@("10")">
                <Input Width="300" Placeholder="输入名称" @bind-Value="@Q_Account" />
                <Button OnClick="Search">搜索</Button>
                <Button OnClick="ResetQuery">重置</Button>

                <Button Type="ButtonType.Primary" Color="Color.Green6" OnClick="() => StartEdit(default)">新增</Button>
            </Flex>
        </TitleTemplate>
        <ColumnDefinitions Context="row">
            <PropertyColumn Align="ColumnAlign.Center" Property="c=>c.Id" Width="100" Title="ID" />
            <PropertyColumn Align="ColumnAlign.Center" Property="c=>c.Avatar" Width="100" Title="头像">
                <Image Src="@row.Avatar" Fallback="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMIAAADDCAYAAADQvc6UAAABRWlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGASSSwoyGFhYGDIzSspCnJ3UoiIjFJgf8LAwSDCIMogwMCcmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis7PPOq3QdDFcvjV3jOD1boQVTPQrgSkktTgbSf4A4LbmgqISBgTEFyFYuLykAsTuAbJEioKOA7DkgdjqEvQHEToKwj4DVhAQ5A9k3gGyB5IxEoBmML4BsnSQk8XQkNtReEOBxcfXxUQg1Mjc0dyHgXNJBSWpFCYh2zi+oLMpMzyhRcASGUqqCZ16yno6CkYGRAQMDKMwhqj/fAIcloxgHQqxAjIHBEugw5sUIsSQpBobtQPdLciLEVJYzMPBHMDBsayhILEqEO4DxG0txmrERhM29nYGBddr//5/DGRjYNRkY/l7////39v///y4Dmn+LgeHANwDrkl1AuO+pmgAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAA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CRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiEC/wGgKKC4YMA4TAAAAABJRU5ErkJggg==" />
            </PropertyColumn>
            <PropertyColumn Align="ColumnAlign.Center" Property="c=>c.Account" Width="200" Title="用户名" />
            <PropertyColumn Property="c=>c.NickName" Width="300" Title="用户信息">
                昵称：@row.NickName
                <br />
                手机：@row.Mobile
                <br />
                邮箱：@row.Email
            </PropertyColumn>
            <PropertyColumn Align="ColumnAlign.Center" Width="100" Property="c=>c.RoleName" Title="角色" />
            <PropertyColumn Align="ColumnAlign.Center" Width="100" Property="c=>c.DepartmentName" Title="部门" />
            <PropertyColumn Align="ColumnAlign.Center" Width="100" Property="c=>c.Enabled" Title="是否启用">
                <Switch Checked="@row.Enabled" @bind-Value="@row.Enabled" CheckedChildren="启用" UnCheckedChildren="禁用" OnChange="() => CheckedChanged(row)" />
            </PropertyColumn>
            <PropertyColumn Align="ColumnAlign.Center" Property="c => c.CreateTime" Width="200" Title="创建时间">
                @{
                    var formattedTime = row.CreateTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? "N/A";
                }
                @formattedTime
            </PropertyColumn>
            <PropertyColumn Align="ColumnAlign.Center" Width="250" Property="c=>c.Area" Title="地区" />
            <PropertyColumn Align="ColumnAlign.Center" Width="250" Property="c=>c.Signature" Title="签名" />
            <ActionColumn Width="180" Title="操作" Fixed="ColumnFixPlacement.Right">
                <Button Type="ButtonType.Primary" Color="Color.Blue6" OnClick="() => StartEdit(row)">编辑</Button>
                <Button Type="ButtonType.Primary" Color="Color.Red6" Danger OnClick="() => Delete(row)">删除</Button>
            </ActionColumn>
        </ColumnDefinitions>
        <PaginationTemplate>
            <Pagination Class="@(context.PaginationClass + " my-custom-pagination")"
                        Total="context.Total"
                        PageSize="context.PageSize"
                        Current="context.PageIndex"
                        ShowSizeChanger
                        ShowQuickJumper
                        ShowTotal="ShowTotal"
                        OnChange="context.HandlePageChange" />
        </PaginationTemplate>
    </Table>
</Spin>

@inject ModalService ModalService;
@inject ConfirmService ComfirmService;
@inject IMessageService MessageService;

@code {

    // <FormItem Label="用户类型" Required>
    //     <Select @bind-Value="@context.UserType"
    //             TItemValue="UserType"
    //             TItem="string"
    //             DefaultActiveFirstOption="true">
    //         <SelectOptions>
    //             @foreach (var userType in Enum.GetValues(typeof(UserType)).Cast<UserType>())
    //         {
    //             <SelectOption TItemValue="UserType" TItem="string" Value="@userType" Label="@userType.Description()" />
    //         }
    //         </SelectOptions>
    //     </Select>
    // </FormItem>

    private void StartEdit(SystemUser row)
    {
        var data = row ?? new();
        ModalRef<bool> modalRef = default;
        IForm form = default;
        modalRef = ModalService.CreateModal<bool>(new()
                {
                    DestroyOnClose = true,
                    MaskClosable = false,
                    Title = data.Id > 0 ? "编辑" : "新增",
                    Content =
    @<Form @ref="form" Model="data" OnFinish="()=> modalRef.OkAsync(true)" LabelColSpan="6" WrapperColSpan="18">
        @if (data.Id == 0)
    {
        <FormItem Label="用户名" Required>
            <Input @bind-Value="@data.Account" />
        </FormItem>
        <FormItem Label="密码" Required>
            <InputPassword @bind-Value="@data.Password" />
        </FormItem>
        <FormItem Label="确认密码" Required>
            <InputPassword @bind-Value="@data.ConfirmPassword" />
        </FormItem>
    }
        <FormItem Label="昵称" Required>
            <Input @bind-Value="@data.NickName" />
        </FormItem>
        <FormItem Label="手机" Required>
            <Input @bind-Value="@data.Mobile" />
        </FormItem>
        <FormItem Label="邮箱">
            <Input @bind-Value="@data.Email" />
        </FormItem>
        <FormItem Label="角色" Required>
            <Select @bind-Value="@data.RoleId"
                    TItemValue="long"
                    TItem="string"
                    DefaultActiveFirstOption="true" EnableSearch AllowClear>
                <SelectOptions>
                    @foreach (var role in Roles)
                {
                    <SelectOption TItemValue="long" TItem="string" Value="@role.Id" Label="@role.Name" />
                }
                </SelectOptions>
            </Select>
        </FormItem>
        <FormItem Label="部门" Required>
            <Select @bind-Value="@data.DepartmentId"
                    TItemValue="long"
                    TItem="string"
                    DefaultActiveFirstOption="true" EnableSearch AllowClear>
                <SelectOptions>
                    @foreach (var department in Departments)
                {
                    <SelectOption TItemValue="long" TItem="string" Value="@department.Id" Label="@department.Name" />
                }
                </SelectOptions>
            </Select>
        </FormItem>
        <FormItem Label="站点" Required>
            <Select @bind-Value="@data.SiteId"
                    TItemValue="long"
                    TItem="string"
                    DefaultActiveFirstOption="true" EnableSearch AllowClear>
                <SelectOptions>
                    @foreach (var department in Sites)
                    {
                        <SelectOption TItemValue="long" TItem="string" Value="@department.Id" Label="@department.Name" />
                    }
                </SelectOptions>
            </Select>
        </FormItem>
        <FormItem Label="是否启用" Required>
            <Select @bind-Value="@data.Enabled"
                    TItemValue="bool"
                    TItem="string"
                    DefaultActiveFirstOption="false">
                <SelectOptions>
                    <SelectOption TItemValue="bool" TItem="string" Value="true" Label="启用" />
                    <SelectOption TItemValue="bool" TItem="string" Value="false" Label="禁用" />
                </SelectOptions>
            </Select>
        </FormItem>
        <FormItem Label="地区">
            <Cascader Options="@Areas" @bind-Value="@data.LastAreadId" SelectedNodesChanged="OnChange" />
        </FormItem>
        <FormItem Label="地址">
            <Input @bind-Value="@data.Address" />
        </FormItem>
        <FormItem Label="签名">
            <TextArea ShowCount MaxLength="200" @bind-Value="@data.Signature" />
        </FormItem>
    </Form>,
            OnOk = async (e) =>
            {
                if (!form.Validate())
                {
                    return;
                }

                modalRef.SetConfirmLoading(true);

                var flag = await InsertOrUpdate(data);
                if (flag)
                {
                    MessageService.Success("操作成功");
                    await modalRef.CloseAsync();
                    _Table.ReloadData(Pi, Ps);
                    StateHasChanged();
                }
                else
                {
                    MessageService.Error("操作失败");
                }

                modalRef.SetConfirmLoading(false);
            },
            OnCancel = async (e) =>
            {
                if (form.IsModified && (!await Comfirm("已修改内容，确定退出吗?")))
                {
                    return;
                }
                await modalRef.CloseAsync();
            }
        });
    }

    private async Task<bool> Comfirm(string message)
    {
        return await ComfirmService.Show(message, "提示", ConfirmButtons.YesNo, ConfirmIcon.Warning) == ConfirmResult.Yes;
    }
}
