@page "/StaffList"
@inject HttpClient Http
@using AntDesign.TableModels
@inject MessageService _message
@using System.ComponentModel
@using wispro.sp.share;
@attribute [Authorize(Roles ="Admin")]
<PageContainer>
    <Breadcrumb>
        <Breadcrumb>
            <BreadcrumbItem>
                <a href="/Home"><Icon Type="home"></Icon></a>
            </BreadcrumbItem>
            <BreadcrumbItem>
                <Icon Type="setting"></Icon><span>基本信息管理</span>
            </BreadcrumbItem>
            <BreadcrumbItem>
                <Icon Type="user"></Icon><span>账号管理</span>
            </BreadcrumbItem>
        </Breadcrumb>
    </Breadcrumb>
    <Content>
        <Button Type="primary" Icon="plus" OnClick="AddNew" Style="float:right">添加</Button>
    </Content>
    <ChildContent>
        @if (forecasts == null)
        {
            <center><Spin /></center>

        }
        else
        {

            <AntDesign.Table @ref="table" @bind-PageIndex="_pageIndex" @bind-PageSize="_pageSize"
                             TItem="Staff"
                             Loading="_loading"
                             DataSource="@forecasts"
                             Total="_total"
                             @bind-SelectedRows="selectedRows"
                             OnChange="OnChange"
                             OnRow="OnRow" RemoteDataSource
                             Bordered=@true
                             Size=@TableSize.Middle>
                <ChildContent>
                    <Selection Key="@(context.Name)" />
                    <AntDesign.Column Title="序号" TData="int">
                        @serialNumber(_pageIndex, _pageSize, context.Name)
                    </AntDesign.Column>
                    <AntDesign.Column Title="姓名" @bind-Field="@context.Name" Sortable Filterable />
                    <AntDesign.Column Title="入职日期" @bind-Field="@context.EntyDate" Format="yyyy-MM-dd" Sortable Filterable />
                    <AntDesign.Column Title="部门" @bind-Field="@context.Department" Sortable Filterable />
                    <AntDesign.Column Title="工作地" Field="@context.WorkPlace" Sortable Filterable />

                    <AntDesign.Column Title="备注" @bind-Field="@context.Memo" Sortable Filterable />
                    <ActionColumn>
                        <Space>
                            <SpaceItem><Button Danger OnClick="()=>Delete(context.Name)">编辑</Button></SpaceItem>
                        </Space>
                    </ActionColumn>
                </ChildContent>
                <PaginationTemplate>
                    <div style="display: flex; align-items: center">
                        <Pagination Class="my-custom-pagination"
                                    Total="@_total"
                                    PageSize="@_pageSize"
                                    Current="@_pageIndex"
                                    ShowSizeChanger="@true"
                                    OnChange="HandlePageChange" />
                    </div>
                </PaginationTemplate>
            </AntDesign.Table>

        }
    </ChildContent>
</PageContainer>


<Modal Title="修改"
       Visible="@_visible"
       OnOk="@HandleOk"
       OnCancel="@HandleCancel">

    <Form Model="EditingStaff" LabelColSpan="6"
          WrapperColSpan="16">
        <FormItem Label="姓名">
            <Input @bind-Value="@context.Name" />
        </FormItem>
        <FormItem Label="岗位状态">
            <Input @bind-Value="@context.Status" />
        </FormItem>

        <FormItem Label="是否计算绩效">
            <Switch @bind-Value="@context.IsCalPerformsnce" />
        </FormItem>

        <FormItem Label="工程师等级">
            <wispro.sp.web.Components.UserGradeSelect @bind-StaffGradeId="@EditingStaff.StaffGradeId" />
        </FormItem>
        
        <FormItem Label="部门">
            <Input @bind-Value="@context.Department" />
        </FormItem>


        <FormItem Label="工作地">
            <Select Mode="default"
                    DataSource="@_places"
                    @bind-Value="@context.WorkPlace">
            </Select>
        </FormItem>

        <FormItem Label="入职时间">
            <DatePicker @bind-Value="@context.EntyDate" />
        </FormItem>

        <FormItem Label="备注">
            <TextArea @bind-Value="@context.Memo" MinRows="4" />
        </FormItem>

        @if (_isAdd)
        {

            <FormItem Label="账号">
                <Input @bind-Value="@context.Account" />
            </FormItem>

            <FormItem Label="账号">
                <Input @bind-Value="@context.Password" Type="password" />
            </FormItem>
        }

    </Form>

</Modal>

<style>
    .my-custom-pagination {
        margin: 15px 0;
    }

        .my-custom-pagination .ant-pagination-item,
        .my-custom-pagination .ant-pagination-item-link {
            border-radius: 100%;
        }
</style>

@using System.Text.Json;
@code {
    private List<Staff> forecasts;
    IEnumerable<Staff> selectedRows;
    ITable table;

    int _pageIndex = 1;
    int _pageSize = 10;
    int _total = 0;
    bool _loading = false;

    Staff EditingStaff = null;
    bool _visible = false;

    bool _isAdd = false;

    List<wispro.sp.entity.StaffGrade> _StaffGrade;

    string[] _places = new string[] { "深圳", "苏州", "南通", "西安", "北京", "杭州", "武汉" };

    int _SelectGradeId;

    protected override async System.Threading.Tasks.Task OnInitializedAsync()
    {

        _loading = true;

        ListApiResponse<Staff> data = await Http.GetFromJsonAsync<ListApiResponse<Staff>>($"http://localhost:39476/api/Staff/Query?pageIndex={_pageIndex}&pageSize={_pageSize}");

        _loading = false;
        forecasts = data.Results;
        _total = data.TotalCount;

        _StaffGrade = await Http.GetFromJsonAsync<List<wispro.sp.entity.StaffGrade>>($"http://localhost:39476/api/StaffGrade/GetAll");


    }

    private void HandlePageChange(PaginationEventArgs args)
    {
        if (_pageIndex != args.Page)
        {
            _pageIndex = args.Page;
        }

        if (_pageSize != args.PageSize)
        {
            _pageSize = args.PageSize;
        }
    }

    public async System.Threading.Tasks.Task OnChange(QueryModel<Staff> queryModel)
    {
        _loading = true;
        ListApiResponse<Staff> data = await Http.GetFromJsonAsync<ListApiResponse<Staff>>("http://localhost:39476/api/Staff/Query?" + GetRandomuserParams(queryModel));

        _loading = false;
        forecasts = data.Results;
        _total = data.TotalCount;

    }

    public int serialNumber(int pageIndex, int pageSize, string name)
    {
        int iIndex = 0;
        foreach (Staff sf in forecasts)
        {
            iIndex++;

            if (sf.Name == name)
            {
                break;
            }
        }
        return (pageIndex - 1) * pageSize + iIndex;
    }

    Dictionary<string, object> OnRow(RowData<Staff> row)
    {
        Dictionary<string, object> ret = new Dictionary<string, object>();

        ret.Add("id", row.RowIndex);
        ret.Add("onclick", ((Action)delegate
        {
            //_message.Info($"row {row.Data.Name} was clicked");
        }));


        return ret;
    }

    private void AddNew()
    {
        EditingStaff = new entity.Staff();
        _isAdd = true;
        _visible = true;
    }

    public void RemoveSelection(string name)
    {
        var selected = selectedRows.Where(x => x.Name != name);
        selectedRows = selected;
    }

    private void Delete(string name)
    {
        var rList = forecasts.Where(x => x.Name == name).ToList();

        if (rList.Count() > 0)
        {
            EditingStaff = rList[0];
            _isAdd = false;
            _visible = true;
        }
        else
        {

        }
        //_total = forecasts.Length;
    }

    string GetRandomuserParams(QueryModel<Staff> queryModel)
    {
        List<string> query = new List<string>()
        {
                $"pageSize={queryModel.PageSize}",
                $"pageIndex={queryModel.PageIndex}",
            };

        queryModel.SortModel.ForEach(x =>
        {
            if (x.Sort != null)
            {
                query.Add($"sortField={x.FieldName.ToLower()}");
                query.Add($"sortOrder={x.Sort}");
            }
        });

        queryModel.FilterModel.ForEach(filter =>
        {
            filter.SelectedValues.ForEach(value =>
            {
                query.Add($"{filter.FieldName.ToLower()}={value}");
            });
        });

        return string.Join('&', query);
    }

    private async System.Threading.Tasks.Task HandleOk(MouseEventArgs e)
    {

        var data = await Http.PostAsJsonAsync<wispro.sp.entity.Staff>($"http://localhost:39476/api/Staff/Save", EditingStaff);

        if (data.IsSuccessStatusCode)
        {
            ApiSaveResponse result = await data.Content.ReadFromJsonAsync<ApiSaveResponse>();
            //await Task.Delay(1000);

            if (result.Success)
            {
                await _message.Success("数据已保存!");
                _visible = false;

                await OnChange((QueryModel<Staff>)table.GetQueryModel());
            }
            else
            {
                await _message.Error($"{result.ErrorMessage}");
            }

        }
        else
        {
            await _message.Error($"请求发生错误 {data.StatusCode}");
        }


    }

    private void HandleCancel(MouseEventArgs e)
    {
        _visible = false;
    }
}
