using AntDesign;
using AntDesign.TableModels;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.JSInterop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using wispro.sp.entity;
using wispro.sp.share;
using wispro.sp.web.Services;

namespace wispro.sp.web.Pages.Organization
{
    public partial class Department
    {
        private List<wispro.sp.entity.Department> departments;
        Tree<wispro.sp.entity.Department> tree;
        bool _loading = false;

        entity.Department _editDepartment;
        [Inject] OrganizationService orgService { get; set; }

        [Inject] MessageService _message { get; set; }

        [Inject] protected NavigationManager NavigationManager { get; set; }

        [Inject] protected  IAuthService _authService { get; set; }

        [Inject] protected IUserService userService { get; set; }

        [Inject] protected IJSRuntime JSRuntime { get; set; }

        protected override async System.Threading.Tasks.Task OnInitializedAsync()
        {
            await _authService.CanVisitResource();
            
            

            _loading = true;

            departments =await orgService.GetDepartments();

            var data = await orgService.GetStaffs(null, 1, 10);
            _loading = false;
            forecasts = data.Results;
            _total = data.TotalCount;

            _StaffGrade = await orgService.GetStaffGrades();
            _allPositions = await orgService.getPositions(null);
            _loading = false;
        }

        #region 部门操作
        bool newModal = false;
        
        private void AddNew(entity.Department parentDept)
        {
            _editDepartment = new entity.Department();

            if (parentDept != null)
            {
                _editDepartment.parentId = parentDept.Id;
                //if(!string.IsNullOrEmpty(parentDept.ancestors))
                //{
                //    _editDepartment.ancestors = $"{parentDept.ancestors},{parentDept.Id}";
                //}
                //else
                //{
                //    _editDepartment.ancestors  = parentDept.Id.ToString();
                //}
                
                //_editDepartment.order_num = GetChildren(parentDept).Count + 1;
            }
            
            newModal = true; 
        }

        



        private void EditDept(entity.Department department)
        {
            _editDepartment = department;
            newModal = true;
        }

        private async Task DeleteDept(entity.Department department)
        {
            var result = await orgService.DeleteDept(department.Id);
            departments = await orgService.GetDepartments();
            StateHasChanged();
        }

        private async System.Threading.Tasks.Task NewOk(MouseEventArgs e)
        {
            newModal = false;
            var retObj = await orgService.SaveDept(_editDepartment);
            departments = await orgService.GetDepartments();
            StateHasChanged();
        }

        private void NewCancel(MouseEventArgs e)
        {
            newModal = false;
        }
        #endregion

        async Task OnSelect(TreeEventArgs<entity.Department> e)
        {
            _editDepartment = e.Node.DataItem;
            _loading = true;
            var data = await orgService.GetStaffs(_editDepartment, 1, 1000);
            forecasts = data.Results;
            _pageIndex = 1;
            _total = data.TotalCount;
            _loading = false;
            StateHasChanged();

        }

        

        private List<wispro.sp.entity.Department> GetChildren(wispro.sp.entity.Department dept)
        {
            if(dept == null)
            {
                var retList = departments.Where<wispro.sp.entity.Department>(x => x.parentId == null).OrderBy(x=>x.order_num).ToList();
                return retList;
            }
            else
            {
                var retList = departments.Where<wispro.sp.entity.Department>(x => x.parentId == dept.Id).OrderBy(x => x.order_num).ToList();
                return retList;
            }
            
        }


        #region 职员操作
        private List<Staff> forecasts;
        IEnumerable<Staff> selectedRows;
        ITable table;

        int _pageIndex = 1;
        int _pageSize = 10;
        int _total = 0;
        

        Staff EditingStaff = null;

        bool _isAdd = false;

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

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


        bool _newUserModal = false;
        private void AddNewUser()
        {
            if (_editDepartment == null)
            {

            }
            else
            {
                EditingStaff = new Staff();
                _isAdd = true;
                _newUserModal = true;
            }
        }

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

                if (sf.Name == name)
                {
                    break;
                }
            }

            return  iIndex;
        }

        private async Task Edit(Staff staff)
        {
            EditingStaff = staff;
            selectPosition = await orgService.getPosition(staff, _editDepartment);

            
            if(selectPosition == null)
            {
                selectPosition = new Position();
            }
            //Console.WriteLine($"Edit:{JsonSerializer.Serialize(selectPosition)}");
            PositionId = selectPosition.Id;
            _isAdd = false;
            _newUserModal  = true;
        }

        private void Delete(Staff staff)
        {

        }

        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 async System.Threading.Tasks.Task OnChange(QueryModel<Staff> queryModel)
        {
            if (!_loading)
            {
                _loading = true;
                ListApiResponse<Staff> data = await orgService.GetStaffs(_editDepartment, queryModel); //Http.GetFromJsonAsync<ListApiResponse<Staff>>("http://localhost:39476/api/Staff/Query?" + GetRandomuserParams(queryModel));


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

                _loading = false;
            }

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

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

        private List<Position> _allPositions;
        Position selectPosition= new Position();
        int PositionId;
        private async System.Threading.Tasks.Task HandleOk(MouseEventArgs e)
        {
            //selectPosition = new Position() { Id = PositionId };

            Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(_editDepartment));

            Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(EditingStaff));

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

            if (data.Success)
            {
                await _message.Success("数据已保存!");
                _newUserModal = false;
                _loading = true;
                var data1 = await orgService.GetStaffs(_editDepartment, 1, 1000);
                forecasts = data1.Results;
                _total = data1.TotalCount;
                _loading = false;
            }
            else
            {
                await _message.Error($"{data.ErrorMessage}");
            }

            //_newUserModal = false;
        }

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

        private void OnSelectedItemChangedHandler(Position value)
        {
            selectPosition  = value;
            //PositionIdChanged.InvokeAsync(_SelectedItem.Id);
        }

        void UserSelected(Staff staff)
        {
            EditingStaff = staff;
        }
        #endregion
    }
}
