using EasyTemplate.Tool;
using Microsoft.AspNetCore.Components;
using Org.BouncyCastle.Utilities;
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;

namespace EasyTemplate.Page.Pages.Report
{
    public partial class ShiftSettlementDailyReport : 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 FilterData Filter { get; set; } = new();
        protected List<RevenueItem> RevenueData { get; set; } = new();
        protected List<PaymentItem> PaymentData { get; set; } = new();
        protected List<OilSalesItem> OilSalesData { get; set; } = new();
        protected List<FleetStatItem> FleetStats { get; set; } = new();
        protected SummaryData Summary { get; set; } = new();
        protected List<string> ShiftName { get; set; } = new();
        protected override async Task OnInitializedAsync()
        {
            ShiftName = new List<string> { "早班", "晚班" };
            await  InitializeData();
        }
        private async Task InitializeData()
        {
            await Reset();
            var ShiftSettlementQuery = ShiftSettlementRepository.AsQueryable();
            if (Filter.Date != null)
            {
                var StartDate = DateTime.Parse(Filter.Date.Value.ToString("yyyy-MM-dd 00:00:00"));
                var EndDate = DateTime.Parse(Filter.Date.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 trxs = await TransactionRepository.AsQueryable().Where(_ => shifts.Contains(_.Shift)).ToListAsync();
            var Paytype = await PayTypeRepository.AsQueryable().ToListAsync();

            RevenueData = new List<RevenueItem>
        {
            new RevenueItem { Id = 1, Name = "油品销售", OrderCount = trxs.Count(), SalesQuantity = trxs.Sum(_ => _.OilVolume), SalesAmount =trxs.Sum(_ => _.PayableAmount) },
            new RevenueItem { Id = 2, Name = "合计", OrderCount = trxs.Count(), SalesQuantity =trxs.Sum(_ => _.OilVolume), SalesAmount = trxs.Sum(_ => _.PayableAmount) },
        };
            trxs.GroupBy(_ => _.PaymentMethod).ToList().ForEach(_ => {
                PaymentData.Add(new PaymentItem {
                    Name = Paytype.Where(a => a.Id == _.Key).FirstOrDefault()?.Name,
                    PaymentCount = _.Count(),
                    PaymentAmount = _.Sum(a => a.ActualAmount)
                });
            });

            trxs.GroupBy(_ => _.OilProduct).ToList().ForEach(_ =>
            {
                OilSalesData.Add(new OilSalesItem {
                    Name = _.Key,
                    OrderCount = _.Count(),
                    SalesQuantity = _.Sum(a => a.OilVolume),
                    SalesAmount = _.Sum(a => a.ActualAmount),
                    ActualAmount = _.Sum(a => a.ActualAmount),
                    Price = _.FirstOrDefault()?.OilPrice,
                    StartPumpCount = _.Min(a => a.PumpMeter),
                    EndPumpCount = _.Max(a => a.PumpMeter),
                    PumpCount = _.Max(a => a.PumpMeter) - _.Min(a => a.PumpMeter)
                });
            });

            trxs.GroupBy(_ => _.LicencePlate).ToList().ForEach(_ => {
                FleetStats.Add(new FleetStatItem {
                    DeviceId =_.FirstOrDefault()?.DeviceId,
                    LicencePlate = _.Key,
                    PaymentCount = _.Count(),
                    SalesQuantity = _.Sum(a => a.OilVolume),
                    ActualAmount = _.Sum(a => a.ActualAmount)
                });
            });

            Summary = new SummaryData
            {
                TotalOrders = trxs.Count(),
                TotalSales = 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 void HandleReset()
        {
            Filter.Date = DateTime.Parse("2025-12-01");
            Filter.EDate = null;
            Filter.CarNumber = "";
            Filter.PlateNumber = "";
            HandleQuery();
        }
        public async Task Reset()
        {
            PaymentData = new List<PaymentItem>();
            OilSalesData = new List<OilSalesItem>();
            FleetStats = new List<FleetStatItem>();
            Summary = new SummaryData();
        }

    }
    // 数据模型
    public class FilterData
    {
        public DateTime? Date { get; set; } = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd"));
        public DateTime? EDate { get; set; }
        public string CarNumber { get; set; } = "";
        public string PlateNumber { get; set; } = "";

        public string Shift { get; set; } = "";
    }

    public class RevenueItem
    {
        public int Id { get; set; }
        public string Name { get; set; } = "";
        public int OrderCount { get; set; }
        public decimal SalesQuantity { get; set; }
        public decimal SalesAmount { get; set; }
    }

    public class PaymentItem
    {
        public int Id { get; set; }
        public string Name { get; set; } = "";
        public int PaymentCount { get; set; }
        public decimal PaymentAmount { get; set; }
    }

    public class OilSalesItem
    {
        public int Id { get; set; }
        public string Name { get; set; } = "";
        public int OrderCount { get; set; }
        public decimal SalesQuantity { get; set; }
        public decimal SalesAmount { get; set; }
        public decimal ActualAmount { get; set; }
        public decimal? Price { get; set; }
        public long StartPumpCount { get; set; }
        public long EndPumpCount { get; set; }
        public long PumpCount { get; set; }
    }

    public class FleetStatItem
    {
        public int Id { get; set; }
        public string DeviceId { get; set; } = "";
        public string LicencePlate { get; set; } = "";
        public int PaymentCount { get; set; }
        public decimal SalesQuantity { get; set; }
        public decimal ActualAmount { get; set; }
    }

    public class SummaryData
    {
        public int TotalOrders { get; set; }
        public decimal TotalSales { get; set; }
        public decimal TotalActual { get; set; }
    }
}