@page "/StaffList"
@inject HttpClient Http
@using AntDesign.TableModels
@inject MessageService _message
@using System.ComponentModel
@using wispro.sp.share; 



    @if (forecasts == null)
    {
        <center><Spin /></center>
        
    }
    else
    {
        <div>
            <Breadcrumb>
                <BreadcrumbItem>
                    <Icon Type="home"></Icon>
                </BreadcrumbItem>
                <BreadcrumbItem>
                    <a><Icon Type="user"></Icon><span>人员清单</span></a>
                </BreadcrumbItem>
            </Breadcrumb>
        </div>
        <p />
        <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>

    }


    <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="工程师等级">
                <Input @bind-Value="@context.StaffGrade.Grade" />
            </FormItem>

            <FormItem Label="等级系数">
                <Input @bind-Value="@context.StaffGrade.Coefficient" />
            </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>

        </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;

        string[] _places = new string[] { "深圳", "苏州", "南通" };

        protected override async Task OnInitializedAsync()
        {

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

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

        }

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

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

        public async Task OnChange(QueryModel<Staff> queryModel)
        {
            _loading = true;
            StaffApiResponse data = await Http.GetFromJsonAsync<StaffApiResponse>("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;
        }

        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];

                _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 =>
            {
                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 void HandleOk(MouseEventArgs e)
        {
            Console.WriteLine(e);
            _visible = false;
        }

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