using EasyTemplate.Tool;
using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using ZhonTai.Admin.Contracts.Domain.VehicleTerminal.Payment;
using ZhonTai.Admin.Contracts.Domain.VehicleTerminal.ShiftSettlement;
using ZhonTai.Admin.Contracts.Domain.VehicleTerminal.Transaction;
using static EasyTemplate.Page.Pages.Report.RevenueReportViewModel;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace EasyTemplate.Page.Pages.Report
{
    public partial class ShiftSalesReport : ComponentBase
    {
        [Inject] private SqlSugarRepository<TransactionEntity> TransactionRepository { get; set; } = default!;
        [Inject] private SqlSugarRepository<PayTypeEntity> PayTypeRepository { get; set; } = default!;
        [Inject] private SqlSugarRepository<ShiftSettlementEntity> ShiftSettlementRepository { get; set; } = default!;
        // 公共属性，供页面使用
        protected FilterData1 Filter { get; set; } = new();
        protected List<OperatingIncomeItem> OperatingIncome { get; set; } = new();
        protected List<IncomeCategoryItem> IncomeCategory { get; set; } = new();
        protected SummaryData1 Summary { get; set; } = new();
        protected List<string> ShiftName { get; set; } = new();

        protected override async Task OnInitializedAsync()
        {
            ShiftName = new List<string> { "早班", "晚班" };
            Filter.StartDate = DateTime.Today;
            await InitializeData();
        }

        private async Task InitializeData()
        {
            await Reset();
            var ShiftSettlementQuery = ShiftSettlementRepository.AsQueryable();
            if (Filter.StartDate != null)
            {
                var StartDate =DateTime.Parse(Filter.StartDate.Value.ToString("yyyy-MM-dd 00:00:00"));
                var EndDate = DateTime.Parse(Filter.StartDate.Value.ToString("yyyy-MM-dd 23:59:59"));
                ShiftSettlementQuery = ShiftSettlementQuery.Where(a => a.StartTime >= StartDate && a.StartTime <= EndDate);
            }
            if (!string.IsNullOrEmpty(Filter.Shift))
            {
                ShiftSettlementQuery = ShiftSettlementQuery.Where(a => a.Name == Filter.Shift);
            }
            if (!string.IsNullOrEmpty(Filter.PlateNumber))
            {
                ShiftSettlementQuery = ShiftSettlementQuery.Where(a => a.DeviceId == Filter.PlateNumber);
            }

            var ShiftSettlement = await  ShiftSettlementQuery.ToListAsync();
            var shifts = ShiftSettlement.GroupBy(_ => _.ShiftId).Select(_ => _.Key).ToList();
            var payType = await PayTypeRepository.AsQueryable().ToListAsync();
            var trxs = await TransactionRepository.AsQueryable().Where(_ => shifts.Contains(_.Shift)).ToListAsync();
            // 初始化营业收入数据
            trxs.GroupBy(_ => _.OilProduct).ToList().ForEach(_ => {
                var shiftId = _.FirstOrDefault()?.Shift;
                var DeviceId = _.FirstOrDefault()?.DeviceId;
                var MorningShift = ShiftSettlement.Where(a => a.Name == "早班").Select(a => a.ShiftId).ToList();
                var NightShift = ShiftSettlement.Where(a => a.Name == "晚班").Select(a => a.ShiftId).ToList();
                var Morning = trxs.Where(a => MorningShift.Contains(a.Shift) && a.OilProduct == _.Key).ToList();
                var Night = trxs.Where(a => NightShift.Contains(a.Shift) && a.OilProduct == _.Key).ToList();
                OperatingIncome.Add(new OperatingIncomeItem {
                    Name =_.Key,
                    MorningSalesQuantity = Morning.Sum(a => a.OilVolume),
                    EveningSalesQuantity = Night.Sum(a => a.OilVolume),
                    TotalSalesQuantity = Morning.Sum(a => a.OilVolume) + Night.Sum(a => a.OilVolume),
                    MorningReceivable = Morning.Sum(a => a.ActualAmount),
                    EveningReceivable = Night.Sum(a => a.ActualAmount),
                    TotalReceivable = Morning.Sum(a => a.ActualAmount) + Night.Sum(a => a.ActualAmount),
                    MorningActual = Morning.Sum(a => a.ActualAmount),
                    EveningActual = Night.Sum(a => a.ActualAmount),
                    TotalActual = Morning.Sum(a => a.ActualAmount) + Night.Sum(a => a.ActualAmount),
                });
            });
            if (OperatingIncome.Count() > 0)
            {
                OperatingIncome.Add(new OperatingIncomeItem {
                    Name = "油品合计",
                    MorningSalesQuantity = OperatingIncome.Sum(_ => _.MorningSalesQuantity),
                    EveningSalesQuantity = OperatingIncome.Sum(_ => _.EveningSalesQuantity),
                    TotalSalesQuantity = OperatingIncome.Sum(_ => _.TotalSalesQuantity),
                    MorningReceivable = OperatingIncome.Sum(_ => _.MorningReceivable),
                    EveningReceivable = OperatingIncome.Sum(_ => _.EveningReceivable),
                    TotalReceivable = OperatingIncome.Sum(_ => _.TotalReceivable),
                    MorningActual = OperatingIncome.Sum(_ => _.MorningActual),
                    EveningActual = OperatingIncome.Sum(_ => _.EveningActual),
                    TotalActual = OperatingIncome.Sum(_ => _.TotalActual),
                });
            }
            // 初始化收入类别数据
            trxs.GroupBy(_ => _.PaymentMethod).ToList().ForEach(_ => {
                var shiftId = _.FirstOrDefault()?.Shift;
                var DeviceId = _.FirstOrDefault()?.DeviceId;
                var MorningShift = ShiftSettlement.Where(a => a.Name == "早班").Select(a => a.ShiftId).ToList();
                var NightShift = ShiftSettlement.Where(a => a.Name == "晚班").Select(a => a.ShiftId).ToList();
                var Morning = trxs.Where(a => MorningShift.Contains(a.Shift) && a.PaymentMethod == _.Key).ToList();
                var Night = trxs.Where(a => NightShift.Contains(a.Shift) && a.PaymentMethod == _.Key).ToList();
                IncomeCategory.Add(new IncomeCategoryItem {
                    Name = payType.Where(a => a.Id == _.Key).FirstOrDefault()?.Name,
                    MorningCount = Morning.Count(),
                    EveningCount = Night.Count(),
                    TotalCount = Morning.Count() + Night.Count(),
                    MorningReceivable = Morning.Sum(a => a.ActualAmount),
                    EveningReceivable = Night.Sum(a => a.ActualAmount),
                    TotalReceivable = Morning.Sum(a => a.ActualAmount) + Night.Sum(a => a.ActualAmount),
                    MorningActual = Morning.Sum(a => a.ActualAmount),
                    EveningActual = Night.Sum(a => a.ActualAmount),
                    TotalActual = Morning.Sum(a => a.ActualAmount) + Night.Sum(a => a.ActualAmount),
                });
            });

            if (IncomeCategory.Count() > 0)
            {
                IncomeCategory.Add(new IncomeCategoryItem
                {
                    Name = "合计",
                    MorningCount = IncomeCategory.Sum(_ => _.MorningCount),
                    EveningCount = IncomeCategory.Sum(_ => _.EveningCount),
                    TotalCount = IncomeCategory.Sum(_ => _.TotalCount),
                    MorningReceivable = IncomeCategory.Sum(_ => _.MorningReceivable),
                    EveningReceivable = IncomeCategory.Sum(_ => _.EveningReceivable),
                    TotalReceivable = IncomeCategory.Sum(_ => _.TotalReceivable),
                    MorningActual = IncomeCategory.Sum(_ => _.MorningActual),
                    EveningActual = IncomeCategory.Sum(_ => _.EveningActual),
                    TotalActual = IncomeCategory.Sum(_ => _.TotalActual)
                });
            }

            // 初始化统计摘要
            Summary = new SummaryData1
            {
                TotalSalesQuantity =trxs.Sum(_ => _.OilVolume).ToString(),
                TotalReceivable = trxs.Sum(_ => _.ActualAmount),
                TotalActual = trxs.Sum(_ => _.ActualAmount)
            };
        }

        // 格式化货币显示
        protected string FormatCurrency(decimal? value)
        {
            if (value == null) return "-";
            return value.Value.ToString("C", CultureInfo.CreateSpecificCulture("zh-CN"));
        }

        // 格式化数字显示
        protected string FormatNumber(decimal? value)
        {
            if (value == null) return "-";
            return value.Value.ToString("N2", CultureInfo.CreateSpecificCulture("zh-CN"));
        }

        // 查询处理
        protected async Task HandleQuery()
        {
            await InitializeData();
        }

        // 重置处理
        protected async Task HandleReset()
        {
            Filter.StartDate = DateTime.Today;
            Filter.EndDate = DateTime.Today.AddDays(1);
            Filter.CarNumber = "";
            Filter.PlateNumber = "";
            HandleQuery();
        }
        public async Task Reset()
        {
            OperatingIncome = new List<OperatingIncomeItem>();
            IncomeCategory = new List<IncomeCategoryItem>();
        }
    }

    // 数据模型
    public class FilterData1
    {
        public DateTime? StartDate { get; set; }
        public DateTime? EndDate { get; set; }
        public string CarNumber { get; set; } = "";
        public string PlateNumber { get; set; } = "";
        public string Shift { get; set; } = "";
    }

    public class OperatingIncomeItem
    {
        public int Id { get; set; }
        public string Name { get; set; } = "";
        public decimal? MorningSalesQuantity { get; set; }
        public decimal? EveningSalesQuantity { get; set; }
        public decimal? TotalSalesQuantity { get; set; }
        public decimal MorningReceivable { get; set; }
        public decimal EveningReceivable { get; set; }
        public decimal TotalReceivable { get; set; }
        public decimal MorningActual { get; set; }
        public decimal EveningActual { get; set; }
        public decimal TotalActual { get; set; }
    }

    public class IncomeCategoryItem
    {
        public int Id { get; set; }
        public string Name { get; set; } = "";
        public int MorningCount { get; set; }
        public int EveningCount { get; set; }
        public int TotalCount { get; set; }
        public decimal MorningReceivable { get; set; }
        public decimal EveningReceivable { get; set; }
        public decimal TotalReceivable { get; set; }
        public decimal MorningActual { get; set; }
        public decimal EveningActual { get; set; }
        public decimal TotalActual { get; set; }
    }

    public class SummaryData1
    {
        public string TotalSalesQuantity { get; set; } = "0";
        public decimal TotalReceivable { get; set; }
        public decimal TotalActual { get; set; }
    }

}
