using EasyTemplate.Page.Pages.SiteConfiguration;
using EasyTemplate.Tool;
using EasyTemplate.Tool.Entity.System.VehicleTerminal.CardInfo;
using Masuit.Tools;
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.Device;
using ZhonTai.Admin.Contracts.Domain.VehicleTerminal.Driver;
using ZhonTai.Admin.Contracts.Domain.VehicleTerminal.Payment;
using ZhonTai.Admin.Contracts.Domain.VehicleTerminal.Transaction;
using ZhonTai.Admin.Contracts.Domain.VehicleTerminal.UserInfo;

namespace EasyTemplate.Page.Pages.Report
{
    public partial class FuelTransactionReport : ComponentBase
    {
        [Inject] private SqlSugarRepository<TransactionEntity> _TransactionPository { get; set; }
        // ========== 数据模型 ==========

        // 筛选条件模型
        public class FilterModel
        {
            public string DeviceId { get; set; } = "";
            public string PlateNumber { get; set; } = "";
            public string OilType { get; set; } = "";
            public string PaymentMethod { get; set; } = "";
            public string PaymentStatus { get; set; } = "";
            public string OrderStatus { get; set; } = "";
            public string Driver { get; set; } = "";
            public string OrderNo { get; set; } = "";
            public string Mobile { get; set; } = "";
            public DateTime? StartTime { get; set; }
            public DateTime? EndTime { get; set; }
        }

        // 交易数据模型
        public class TransactionItem
        {
            public string Id { get; set; } = "";
            public string DeviceId { get; set; } = "";
            public string PlateNumber { get; set; } = "";
            public DateTime TransactionTime { get; set; }
            public string OilProductName { get; set; } = "";
            public decimal OilPrice { get; set; }
            public decimal OilVolume { get; set; }
            public string PaymentMethod { get; set; } = "";
            public string DriverName { get; set; } = "";
            public string OrderNo { get; set; } = "";
            public decimal PayableAmount { get; set; }
            public string Mobile { get; set; } = "";
            public string UserName { get; set; } = "";
            public string WxName { get; set; } = "";
            public string PaymentStatus { get; set; }
            public string OrderStatus { get; set; } = "";
        }

        // ========== 公共属性 ==========

        protected FilterModel Filter { get; set; } = new();
        protected List<TransactionItem> TransactionData { get; set; } = new();

        protected bool Loading { get; set; }
        protected int TotalCount { get; set; }
        protected int CurrentPage { get; set; } = 1;
        protected int PageSize { get; set; } = 20;

        // ========== 选项数据 ==========

        protected List<string> DeviceOptions { get; set; } = new();
        protected List<string> PlateNumberOptions { get; set; } = new();
        protected List<string> OilTypeOptions { get; set; } = new();
        protected List<string> PaymentMethodOptions { get; set; } = new();
        protected List<string> PaymentStatusOptions { get; set; } = new();
        protected List<string> OrderStatusOptions { get; set; } = new();
        protected List<string> DriverOptions { get; set; } = new();


        public string DeviceId { get; set; } = "";
        public string PlateNumber { get; set; } = "";
        public string OilType { get; set; } = "";
        public string PaymentMethod { get; set; } = "";
        public string PaymentStatus { get; set; } = "";
        public string OrderStatus { get; set; } = "";
        public string Driver { get; set; } = "";
        public string OrderNo { get; set; } = "";
        public string Mobile { get; set; } = "";
        public DateTime? StartTime { get; set; }
        public DateTime? EndTime { get; set; }

        // ========== 生命周期方法 ==========

        protected override void OnInitialized()
        {
            base.OnInitialized();
            InitializeData();
            _ = LoadDataAsync();
        }

        // ========== 初始化方法 ==========

        private void InitializeData()
        {
            // 初始化选项数据
            DeviceOptions = new List<string> { "粤B67890" };
            PlateNumberOptions = new List<string> { "粤ACD0045", "粤ACD0046", "粤ACD0047", "粤ACD0048" };
            OilTypeOptions = new List<string> { "92#", "95#", "0#" };
            PaymentMethodOptions = new List<string> { "微信支付", "支付宝支付", "现金", "银联" };
            PaymentStatusOptions = new List<string> { "待支付", "支付成功", "支付失败" };
            OrderStatusOptions = new List<string> { "未支付", "已完成", "已取消" };
            DriverOptions = new List<string> { "张三", "李四", "王五" };

            // 设置默认时间范围（最近7天）
            Filter.StartTime = DateTime.Today.AddDays(-7);
            Filter.EndTime = DateTime.Today;
        }

        // ========== 数据操作 ==========

        // 重置筛选条件
        protected void ResetFilter()
        {
            Filter = new FilterModel
            {
                StartTime = DateTime.Today.AddDays(-7),
                EndTime = DateTime.Today
            };
            CurrentPage = 1;
        }

        // 加载数据
        protected async Task LoadDataAsync()
        {
            Loading = true;

            try
            {
                // 模拟API调用延迟
                await Task.Delay(300);

                // 生成模拟数据
                TransactionData = await GenerateMockData();
                TotalCount = TransactionData.Count(); // 模拟总记录数
            }
            finally
            {
                Loading = false;
                StateHasChanged();
            }
        }

        // 生成模拟数据
        private async Task<List<TransactionItem>> GenerateMockData()
        {
            try
            {
                var payStatus = PaymentStatus == "待支付" ? 0 :
                                   PaymentStatus == "支付成功" ? 1 :
                                   PaymentStatus == "支付失败" ? 2 : 3;
                var OStatus = OrderStatus == "未支付" ? 0 :
                              OrderStatus == "已完成" ? 1 :
                               OrderStatus == "已取消" ? 2 : 3;
                var query = _TransactionPository.AsQueryable()
                            .LeftJoin<DeviceEntity>((a, b) => a.DeviceId == b.DeviceId)
                            .LeftJoin<PayTypeEntity>((a, b, c) => a.PaymentMethod == c.Id)
                            .LeftJoin<DriverEntity>((a, b, c, e) => a.EmployeeId == e.Id)
                            .LeftJoin<UserInfoEntity>((a, b, c, e, f) => a.UserId == f.Id);

                // 使用条件判断代替三元运算符
                if (!string.IsNullOrEmpty(DeviceId))
                    query = query.Where((a, b, c, e, f) => b.DeviceId == DeviceId);

                if (!string.IsNullOrEmpty(PlateNumber))
                    query = query.Where((a, b, c, e, f) => a.LicencePlate == PlateNumber);

                if (!string.IsNullOrEmpty(OilType))
                    query = query.Where((a, b, c, e, f) => a.OilProduct == OilType);

                if (!string.IsNullOrEmpty(PaymentMethod))
                    query = query.Where((a, b, c, e, f) => c.Name == PaymentMethod);

                if (payStatus != 3)
                    query = query.Where((a, b, c, e, f) => a.PaymentStatus == payStatus);

                if (OStatus != 3)
                    query = query.Where((a, b, c, e, f) => a.OrderStatus == OStatus);

                if (!string.IsNullOrEmpty(Driver))
                    query = query.Where((a, b, c, e, f) => e.Name == Driver);

                if (!string.IsNullOrEmpty(OrderNo))
                    query = query.Where((a, b, c, e, f) => a.BillNumber == OrderNo);

                if (!string.IsNullOrEmpty(Mobile))
                    query = query.Where((a, b, c, e, f) => a.Mobile == Mobile);

                if (StartTime != null)
                    query = query.Where((a, b, c, e, f) =>
                        a.TransactionTime > StartTime && a.TransactionTime < EndTime);

                return await query
                    .Select((a, b, c, e, f) => new TransactionItem
                    {
                        Id = a.Id.ToString(),
                        DeviceId = b.DeviceId,
                        PlateNumber = a.LicencePlate,
                        TransactionTime = a.TransactionTime,
                        OilProductName = a.OilProduct,
                        OilPrice = a.OilPrice,
                        OilVolume = a.OilVolume,
                        PaymentMethod = c.Name,
                        DriverName = e.Name,
                        OrderNo = a.BillNumber,
                        PayableAmount = a.PayableAmount,
                        Mobile = a.Mobile,
                        UserName = f.UserName,
                        WxName = f.WxName,
                        PaymentStatus = a.PaymentStatus == 0 ? "待支付" :
                                       a.PaymentStatus == 1 ? "支付成功" :
                                       a.PaymentStatus == 2 ? "支付失败" : "",
                        OrderStatus = a.OrderStatus == 0 ? "未支付" :
                                     a.OrderStatus == 1 ? "已完成" : ""
                    })
                    .ToListAsync();
            }
            catch (Exception ex) 
            {
            
            }
            return null;
          
        }

        // ========== 格式化方法 ==========

        // 格式化货币显示
        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 string FormatDateTime(DateTime? value)
        {
            if (value == null) return "-";
            return value.Value.ToString("yyyy-MM-dd HH:mm:ss");
        }

        // 格式化支付状态
        protected string FormatPaymentStatus(bool? status)
        {
            if (status == null) return "-";
            return status.Value ? "成功" : "失败";
        }

        // 格式化订单状态
        protected string FormatOrderStatus(string status)
        {
            return string.IsNullOrEmpty(status) ? "-" : status;
        }

        // ========== 事件处理方法 ==========

        // 查询处理
        protected async Task HandleQuery()
        {
            CurrentPage = 1;
            await LoadDataAsync();
        }

        // 重置处理
        protected async Task HandleReset()
        {
            ResetFilter();
            await LoadDataAsync();
        }

        // 页码变化
        protected async Task OnPageChange(int page)
        {
            CurrentPage = page;
            await LoadDataAsync();
        }

        // 每页大小变化
        protected async Task OnPageSizeChange(int pageSize)
        {
            PageSize = pageSize;
            CurrentPage = 1;
            await LoadDataAsync();
        }
    }
}