using AntDesign;
using AntDesign.ProLayout;
using AntDesign.TableModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.Extensions.Configuration;
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.Models;
using wispro.sp.web.Services;


namespace wispro.sp.web.Pages.AppCase
{
    [Authorize]
    public partial class MyCaselist
    {
        const string strAgentFeedbackMemo = "AgentFeedbackMemo";
        const string strDoItemCoefficient = "DoItemCoefficient";
        const string strReturnCasseNo = "ReturnCasseNo";
        const string strCaseCoefficient = "CaseCoefficient";
        const string strWordCount = "WordCount";

        public TableFilter<string>[] CaseCoeFilters = new TableFilter<string>[] {
            new() { Text = "S", Value = "S" },
            new() { Text = "A", Value = "A" },
            new() { Text = "B", Value = "B" },
            new() { Text = "C", Value = "C" },
            new() { Text = "D", Value = "D" }
        };

        [Inject]
        protected AppealTypeService apTypeService { get; set; }
        private List<CalMonth> calMonthList;
        private List<PerformanceItem> _Datas;
        private List<StaffStatistics> MyStatistics;
        IEnumerable<PerformanceItem> selectedItems = new List<PerformanceItem>();

        private CalMonth HandlingCalMonth;
        

        int _pageIndex = 1;
        int _pageSize = 10;
        int _total;
        bool _loading = false;
        PerformanceItem EditingItem = null;
        int DoingOrReview = 0;
        int SelectedCalMonthId = 0;

        List<TabPaneItem> tabList = new List<TabPaneItem>() {
            new TabPaneItem(){ Key ="myListDoing", Tab ="本月待确认绩效" },
            new TabPaneItem(){  Key ="myAll", Tab ="往期已计算绩效"},
        };

        [Inject] public PerformanceItemServices _ItemService { get; set; }
        [Inject] public MessageService _message { get; set; }
        [Inject] protected NavigationManager NavigationManager { get; set; }
        [Inject] protected IUserService _userService { get; set; }

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

        [Inject] IConfiguration configuration{get;set;}


        private bool isFirstInit = true;
        private Table<PerformanceItem> table;
        private CurrentUser _user;
        private string strAddProjectJX = "";

        class SelectItem
        {
            public int Value { get; set; }
            public string Name { get; set; }
        }

        List<SelectItem> _Items = new List<SelectItem>()
        {
            new SelectItem(){Value =0,Name ="我处理的案件"},
            new SelectItem(){Value =1,Name ="我审核的案件"}
        };

        private void OnSelectedItemChangedHandler(SelectItem value)
        {
            //_selectedItem = value;
            //Console.WriteLine($"selected: ${value?.Name}");
            _pageIndex = 1;
            table.ReloadData();
            StateHasChanged();
        }

        private async void OnSelectedCalMonthChangedHandler(CalMonth calMonth)
        {
            _pageIndex = 1;
            await RefreshMyStatistics(calMonth);
            table.ReloadData();
            StateHasChanged();
        }

        protected async override Task OnInitializedAsync()
        {
            if (isFirstInit)
            {
                _loading = true;
                await RefreshMyStatistics();
                _Datas = new List<PerformanceItem>();// data.Results;
                _total = 0;//data.TotalCount;
                _loading = false;
            }

            isFirstInit = false;

            calMonthList = await _CalMonthService.GetAll();
            if (calMonthList != null)
            {
                calMonthList = calMonthList.Where(c => c.Status != 0).ToList();
            }

            await apTypeService.GetItems();
            _user = await _userService.GetUser();
            StateHasChanged();
        }


        private bool ShowMenu()
        {
            var strlfd = configuration.GetValue<string>("Latest_feedback_date");

            if (string.IsNullOrEmpty(strlfd))
            {
                return true;
            }
            else
            {
                if(DateTime.Now.Day <= int.Parse(strlfd))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        private async Task RefreshMyStatistics()
        {
            var HandlingCalMonth = await _CalMonthService.GetHandlingMonth();
            await RefreshMyStatistics(HandlingCalMonth);

        }

        private async Task RefreshMyStatistics(CalMonth calMonth)
        {
            if (calMonth != null)
            {
                var _user = await _userService.GetUser(); ;
                if (_user.Userid != null)
                {
                    MyStatistics = await _ItemService.CalMyStatistics(calMonth.Year, calMonth.Month, _user.Userid.Value);
                }
                else
                {
                    NavigationManager.NavigateTo("/LoginPages");
                }
            }

        }

        private string GetStatistics(string strType, bool isBasePoint = false)
        {
            
            Console.WriteLine(strType);
            try
            {
                if (strType != "ALL")
                {

                    var tem = MyStatistics.Where<StaffStatistics>(s => s.jxType == strType).FirstOrDefault();

                    if (isBasePoint)
                    {
                        if (tem != null)
                        {
                            return (tem.FinianlPoint .HasValue ? tem.totalBasePoint.Value.ToString("0.00") : "");
                        }
                        else
                        {
                            return "";
                        }
                    }
                    else
                    {
                        if (tem != null)
                        {
                            return (tem.FinianlPoint.HasValue ? tem.FinianlPoint.Value.ToString("0.00") : "");
                        }
                        else
                        {
                            return "";
                        }
                    }

                }
                else
                {
                    if (isBasePoint)
                    {
                        return MyStatistics.Select(s => s.totalBasePoint.Value).Sum().ToString("0.00");
                    }
                    else
                    {
                        return MyStatistics.Select(s => s.FinianlPoint.Value).Sum().ToString("0.00");
                    }
                }
            }
            catch
            {
                return "";
            }
        }

        private int serialNumber(int pageIndex, int pageSize, int id)
        {
            int iIndex = 0;
            foreach (PerformanceItem sf in _Datas)
            {
                iIndex++;

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


        private async Task HandleTableChange(QueryModel<PerformanceItem> queryModel)
        {
            var _user = await _userService.GetUser();
            
            if (_CurrentKey == tabList[0].Key)
            {
                _loading = true;

                HandlingCalMonth = await _CalMonthService.GetHandlingMonth();
                await RefreshMyStatistics();

                if (HandlingCalMonth != null)
                {
                    var data = await _ItemService.Query(HandlingCalMonth.Id, _user.Userid.Value, jxType.doing, queryModel, DoingOrReview);

                    _Datas = data.Results;
                    _total = data.TotalCount;
                }
                _loading = false;
                StateHasChanged();
            }
            else
            {
                
                _loading = true;

                if(SelectedCalMonthId == 0 && calMonthList !=null && calMonthList.Count >0)
                {
                    SelectedCalMonthId = calMonthList[0].Id;
                    await RefreshMyStatistics(calMonthList[0]);
                }

                var data = await _ItemService.Query(SelectedCalMonthId, _user.Userid.Value, jxType.finished, queryModel,DoingOrReview);

                _Datas = data.Results;
                _total = data.TotalCount;
                _loading = false;
                StateHasChanged();
                
            }


        }
        
        [Inject] IConfiguration _configuration { get; set; }

        bool isDownloading = false;
        private async Task ExportDataAsync(jxType jxType)
        {
            isDownloading = true;

            FileProcessTask fileData = null;
            if (jxType == jxType.doing)
            {
                fileData = await _ItemService.ExportData(HandlingCalMonth.Id, _user.Userid.Value, jxType, DoingOrReview);
            }
            else
            {
                fileData = await _ItemService.ExportData(SelectedCalMonthId, _user.Userid.Value, jxType, DoingOrReview);
            }

            while(!fileData.Finished)
            {
                fileData =await  _ItemService.getExportDataProcessing(fileData.Id);
                await Task.Delay(20);
            }

            NavigationManager.NavigateTo($"{_configuration.GetValue<string>("APIUrl")}FileProcesTask/Download?Id={fileData.Id}");

            isDownloading = false;

        }

        bool _visible = false;
        private void OnsubShensu(PerformanceItem Item)
        {
            EditingItem = Item;
            _visible = true;

            //return new EventCallback();
        }

        bool _ShowJXModal = false;
        private void OnJXCal(PerformanceItem Item)
        {
            EditingItem = Item;
            _ShowJXModal = true;
        }

        private async void menuYSJXClick(PerformanceItem Item)
        {
            var respone = await _ItemService.SaveFieldChange(Item.Id, strAgentFeedbackMemo, "已算绩效");
            var item = await _ItemService.GetPerformancItem(Item.Id);
            Item.BasePoint = item.BasePoint;
            _ = RefreshMyStatistics();
        }

        private shensuType _SelectedItem;
        private void OnSelectedItemChangedHandler(shensuType value)
        {
            _SelectedItem = value;
            //StaffGradeIdChanged.InvokeAsync(_SelectedItem.Id);
        }

        #region 特殊绩效字段选择框变更时处理代码
        async void SelectChanged(Reason  value)
        {
            if (!_loading && EditingItem != null)
            {
                var respone =await _ItemService.SaveFieldChange(EditingItem.Id, strAgentFeedbackMemo, EditingItem.AgentFeedbackMemo);
                var item = await _ItemService.GetPerformancItem(EditingItem.Id) ;
                EditingItem.BasePoint = item.BasePoint;
                _ = RefreshMyStatistics();
                
                EditingItem = null;
                //table.ReloadData();
            }
        }

        void ClearSelect(int itemId)
        {
            var respone = _ItemService.SaveFieldChange(itemId, strAgentFeedbackMemo,"");
            EditingItem = null;

            _ = RefreshMyStatistics();
            table.ReloadData();
        }
        #endregion

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

            
            ret.Add("onclick", ((Action)delegate
            {
                EditingItem = row.Data;
            }));


            return ret;
        }

        void OnFocus(PerformanceItem item)
        {
            EditingItem = item;
        }

        string _CurrentKey = "myListDoing";
        void OnTabChange(string key)
        {
            _CurrentKey = key;
            _pageIndex = 1;
            //table.PageIndex = 1;
            table.ReloadData();
            StateHasChanged();
        }

        private ModalRef _modalRef;
        [Inject] ModalService _ModalService { get; set; }
        [Inject]protected AppealTypeService _atService { get; set; }

        
        async Task ShowModel(PerformanceItem Item,AppealType appealType)
        {
            var templateOptions = new Models.CreateAppealModel();
            await templateOptions.Init(_atService,Item, appealType);

            var modalConfig = new ModalOptions();
            modalConfig.Title = appealType.Name;
            modalConfig.Width = 650;
            //modalConfig.Footer = null;
            modalConfig.DestroyOnClose = true;
            modalConfig.MaskClosable = false;


            _modalRef = await _ModalService
                .CreateModalAsync<Components.CreateAppeal, Models.CreateAppealModel>(modalConfig, templateOptions);

            _modalRef.OnOpen = () =>
            {
                return Task.CompletedTask;
            };

            _modalRef.OnOk = async () =>
            {
                try
                {
                    await _atService.CreateAppeal(templateOptions);
                    await _modalRef.CloseAsync();

                    StateHasChanged();

                    var SuccessConfig = new ConfirmOptions()
                    {
                        Content = @"保存申诉信息成功！"
                    };

                    //modalConfig.Footer = null;
                    modalConfig.DestroyOnClose = true;
                    _ModalService.Success(SuccessConfig);

                }
                catch (Exception ex)
                {
                    _ModalService.Error(new ConfirmOptions()
                    {
                        Title = "保存申诉信息错误",
                        Content = ex.Message,
                    });
                    //_ErrorMessage = ex.Message;
                }

                //return Task.CompletedTask;
            };

            _modalRef.OnCancel = () =>
            {
                return Task.CompletedTask;
            };

            _modalRef.OnClose = () =>
            {
                return Task.CompletedTask;
            };
            StateHasChanged();
        }

        
    }
}
