using EasyTemplate.Tool;
using Microsoft.AspNetCore.Components;
using Org.BouncyCastle.Asn1.X509;
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.Transaction;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace EasyTemplate.Page.Pages.Report
{
    public partial class RevenueReport : ComponentBase
    {
        [Inject] private SqlSugarRepository<TransactionEntity> TransactionRepository { get; set; } = default!;
        [Inject] private SqlSugarRepository<PayTypeEntity> PayTypeRepository { get; set; } = default!;
        [Inject] private SqlSugarRepository<RechargeRecordEntity> _RechargeRecordPository { get; set; }
        private RevenueReportViewModel ViewModel { get; set; } = new();

        protected override async Task OnInitializedAsync()
        {
            base.OnInitialized();
            await ViewModel.InitializeData(TransactionRepository, PayTypeRepository, _RechargeRecordPository);
        }

        // 格式化货币显示
        private string FormatCurrency(decimal? value, bool withoutSymbol = false)
        {
            return ViewModel.FormatCurrency(value, withoutSymbol);
        }

        // 格式化数字显示
        private string FormatNumber(decimal? value)
        {
            return ViewModel.FormatNumber(value);
        }

        // 查询处理
        private async Task HandleQuery()
        {
            await ViewModel.HandleQuery();
            StateHasChanged();
        }

        // 重置处理
        private void HandleReset()
        {
            ViewModel.HandleReset();
            StateHasChanged();
        }
    }

    // ViewModel 类
    public class RevenueReportViewModel
    {
        // 筛选条件模型
        public class FilterData
        {
            public DateTime? Date { get; set; } = DateTime.Parse("2025-12-01");
            public DateTime? EDate { get; set; } = DateTime.Parse("2025-12-31");
            public string CarNumber { get; set; } = "";
            public string PlateNumber { get; set; } = "";
        }

        // 营业收入（车）数据模型
        public class CarRevenueItem
        {
            public int Id { get; set; }
            public string CarNumber { get; set; } = "";
            public decimal? UnitPrice { get; set; }
            public int OrderCount { get; set; }
            public decimal SalesLiters { get; set; }
            public decimal ReceivableAmount { get; set; }
            public decimal ActualAmount { get; set; }
            public string OilType { get; set; } = "";
        }

        // 营业收入（油品）数据模型
        public class OilRevenueItem
        {
            public int Id { get; set; }
            public string OilType { get; set; } = "";
            public decimal UnitPrice { get; set; }
            public int OrderCount { get; set; }
            public decimal SalesLiters { get; set; }
            public decimal ReceivableAmount { get; set; }
            public decimal ActualAmount { get; set; }
        }

        // 营业收入（充值）数据模型
        public class RechargeRevenueItem
        {
            public int Id { get; set; }
            public string RechargeType { get; set; } = "";
            public int RechargeCount { get; set; }
            public decimal RechargeAmount { get; set; }
        }

        // 营业收支款项明细数据模型
        public class PaymentDetailItem
        {
            public int Id { get; set; }
            public string PaymentMethod { get; set; } = "";
            public string Category { get; set; } = "";
            public int OrderCount { get; set; }
            public decimal SalesLiters { get; set; }
            public decimal ReceivableAmount { get; set; }
            public decimal ActualAmount { get; set; }
        }

        // 统计摘要模型
        public class SummaryData
        {
            public int TotalOrders { get; set; }
            public decimal TotalReceivable { get; set; }
            public decimal TotalActual { get; set; }
            public decimal TotalRecharge { get; set; }
        }

        // 合计模型 - 修改类名以避免冲突
        public class CarRevenueSummary
        {
            public int OrderCount { get; set; }
            public decimal SalesLiters { get; set; }
            public decimal ReceivableAmount { get; set; }
            public decimal ActualAmount { get; set; }
        }

        public class OilRevenueSummary
        {
            public int OrderCount { get; set; }
            public decimal SalesLiters { get; set; }
            public decimal ReceivableAmount { get; set; }
            public decimal ActualAmount { get; set; }
        }

        public class RechargeRevenueSummary
        {
            public int RechargeCount { get; set; }
            public decimal RechargeAmount { get; set; }
        }

        public class PaymentDetailSummary
        {
            public int OrderCount { get; set; }
            public decimal SalesLiters { get; set; }
            public decimal ReceivableAmount { get; set; }
            public decimal ActualAmount { get; set; }
        }

        // 公共属性
        public FilterData Filter { get; set; } = new();
        public List<CarRevenueItem> CarRevenue { get; set; } = new();
        public List<OilRevenueItem> OilRevenue { get; set; } = new();
        public List<RechargeRevenueItem> RechargeRevenue { get; set; } = new();
        public List<PaymentDetailItem> PaymentDetails { get; set; } = new();
        public SummaryData Summary { get; set; } = new();

        // 计算属性 - 合计 - 修改属性名以避免冲突
        public CarRevenueSummary CarRevenueTotalResult => CalculateCarRevenueTotal();
        public OilRevenueSummary OilRevenueTotalResult => CalculateOilRevenueTotal();
        public RechargeRevenueSummary RechargeRevenueTotalResult => CalculateRechargeRevenueTotal();
        public PaymentDetailSummary PaymentDetailsTotalResult => CalculatePaymentDetailsTotal();

        public SqlSugarRepository<TransactionEntity> _TransactionRepository;
        public SqlSugarRepository<PayTypeEntity> _PayTypeRepository;
        public SqlSugarRepository<RechargeRecordEntity> _RechargeRepository;
        // 初始化数据
        public async Task InitializeData(SqlSugarRepository<TransactionEntity> TransactionRepository,
            SqlSugarRepository<PayTypeEntity> PayTypeRepository,
            SqlSugarRepository<RechargeRecordEntity> _RechargeRecordPository)
        {
            _TransactionRepository = TransactionRepository;
            _PayTypeRepository = PayTypeRepository;
            _RechargeRepository = _RechargeRecordPository;
          await  Query();
        }
        public async Task Query()
        {
            await Reset();
            var trxQuery = _TransactionRepository.AsQueryable().Where(_ => _.OrderStatus == 1);
            if (Filter.Date.HasValue && Filter.EDate.HasValue)
            {
                trxQuery = trxQuery.Where(_ => _.TransactionTime >= Filter.Date.Value
                                       && _.TransactionTime <= Filter.EDate.Value);
            }
            if (!string.IsNullOrEmpty(Filter.CarNumber))
            {
                trxQuery = trxQuery.Where(_ => _.DeviceId == Filter.CarNumber);
            }
            if (!string.IsNullOrEmpty(Filter.PlateNumber))
            {
                trxQuery = trxQuery.Where(_ => _.LicencePlate == Filter.PlateNumber);
            }
            var trxs = await trxQuery.ToListAsync();

            var Paytype = await _PayTypeRepository.AsQueryable().ToListAsync();

            var RechargeQuery = _RechargeRepository.AsQueryable().Where(_ => _.OrderStatus == 1);
            var Recharge = new List<RechargeRecordEntity>();
            if (Filter.Date.HasValue && Filter.EDate.HasValue)
            {
                RechargeQuery = RechargeQuery.Where(_ => _.TransactionTime >= Filter.Date.Value
                                       && _.TransactionTime <= Filter.EDate.Value);
            }
            if (string.IsNullOrEmpty(Filter.CarNumber) && string.IsNullOrEmpty(Filter.PlateNumber))
            {
                Recharge = await RechargeQuery.ToListAsync();
            }
            // 初始化营业收入（车）数据
            trxs.GroupBy(_ => _.LicencePlate).ToList().ForEach(_ => {
                CarRevenue.Add(new CarRevenueItem
                {
                    CarNumber = _.Key,
                    UnitPrice = _.FirstOrDefault()?.OilPrice,
                    OrderCount = _.Count(),
                    SalesLiters = _.Sum(a => a.OilVolume),
                    ReceivableAmount = _.Sum(a => a.PayableAmount),
                    ActualAmount = _.Sum(a => a.PayableAmount),
                    OilType = _.FirstOrDefault()?.OilProduct
                });
            });

            // 初始化营业收入（油品）数据
            trxs.GroupBy(_ => _.OilProduct).ToList().ForEach(_ => {
                OilRevenue.Add(new OilRevenueItem
                {
                    OilType = _.Key,
                    UnitPrice = _.FirstOrDefault().OilPrice,
                    OrderCount = _.Count(),
                    SalesLiters = _.Sum(a => a.OilVolume),
                    ReceivableAmount = _.Sum(a => a.ActualAmount),
                    ActualAmount = _.Sum(a => a.ActualAmount)
                });
            });

            // 初始化营业收入（充值）数据
            Recharge.GroupBy(_ => _.PaymentMethod).ToList().ForEach(_ => {
                var payName = Paytype.Where(a => a.Id == _.Key).FirstOrDefault()?.Name;
                RechargeRevenue.Add(new RechargeRevenueItem
                {
                    RechargeType = payName,
                    RechargeCount = _.Count(),
                    RechargeAmount = _.Sum(a => a.OriginalAmount)
                });
            });


            // 初始化营业收支款项明细数据
            var PaymentMethod = trxs.GroupBy(x => x.PaymentMethod).ToList();
            foreach (var item in PaymentMethod)
            {
                trxs.Where(_ => _.PaymentMethod == item.Key).ToList().GroupBy(_ => _.OilProduct).ForEach(a => {
                    PaymentDetails.Add(new PaymentDetailItem
                    {
                        PaymentMethod = Paytype.Where(_ => _.Id == item.Key).FirstOrDefault()?.Name,
                        Category = a.Key,
                        OrderCount = a.Count(),
                        SalesLiters = a.Sum(_ => _.OilVolume),
                        ReceivableAmount = a.Sum(_ => _.PayableAmount),
                        ActualAmount = a.Sum(_ => _.PayableAmount)
                    });
                });

            }

            // 初始化统计摘要
            Summary = new SummaryData
            {
                TotalOrders = trxs.Count() + Recharge.Count(),
                TotalReceivable = trxs.Sum(_ => _.PayableAmount),
                TotalActual = trxs.Sum(_ => _.PayableAmount),
                TotalRecharge = Recharge.Sum(_ => _.OriginalAmount)
            };
        }
        // 计算合计方法 - 修改返回类型
        private CarRevenueSummary CalculateCarRevenueTotal()
        {
            var total = new CarRevenueSummary();
            foreach (var item in CarRevenue)
            {
                total.OrderCount += item.OrderCount;
                total.SalesLiters += item.SalesLiters;
                total.ReceivableAmount += item.ReceivableAmount;
                total.ActualAmount += item.ActualAmount;
            }
            return total;
        }

        private OilRevenueSummary CalculateOilRevenueTotal()
        {
            var total = new OilRevenueSummary();
            foreach (var item in OilRevenue)
            {
                total.OrderCount += item.OrderCount;
                total.SalesLiters += item.SalesLiters;
                total.ReceivableAmount += item.ReceivableAmount;
                total.ActualAmount += item.ActualAmount;
            }
            return total;
        }

        private RechargeRevenueSummary CalculateRechargeRevenueTotal()
        {
            var total = new RechargeRevenueSummary();
            foreach (var item in RechargeRevenue)
            {
                total.RechargeCount += item.RechargeCount;
                total.RechargeAmount += item.RechargeAmount;
            }
            return total;
        }

        private PaymentDetailSummary CalculatePaymentDetailsTotal()
        {
            var total = new PaymentDetailSummary();
            foreach (var item in PaymentDetails)
            {
                total.OrderCount += item.OrderCount;
                total.SalesLiters += item.SalesLiters;
                total.ReceivableAmount += item.ReceivableAmount;
                total.ActualAmount += item.ActualAmount;
            }
            return total;
        }

        // 格式化货币显示
        public string FormatCurrency(decimal? value, bool withoutSymbol = false)
        {
            if (value == null) return "-";

            if (withoutSymbol)
            {
                return value.Value.ToString("N2", CultureInfo.CreateSpecificCulture("zh-CN"));
            }

            return value.Value.ToString("C", CultureInfo.CreateSpecificCulture("zh-CN"));
        }

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

        // 查询处理
        public async Task HandleQuery()
        {
            await Query();
        }
        public async Task Reset()
        {
            CarRevenue = new List<CarRevenueItem>();
            OilRevenue = new List<OilRevenueItem>();
            RechargeRevenue = new List<RechargeRevenueItem>();
            PaymentDetails = new List<PaymentDetailItem>();
            Summary = new SummaryData();
        }
        // 重置处理
        public void HandleReset()
        {
            Filter.Date = DateTime.Parse("2025-12-01");
            Filter.EDate = DateTime.Parse("2025-12-31");
            Filter.CarNumber = "";
            Filter.PlateNumber = "";
            HandleQuery();
        }
    }
}