using AntDesign;
using EasyTemplate.Tool;
using EasyTemplate.Tool.Dto.RechargeRecords;
using EasyTemplate.Tool.Entity.System.VehicleTerminal.BusinessUnitInfo;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using SharpCompress.Writers;
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 ZhonTai.Admin.Contracts.Domain.VehicleTerminal.UserInfo;
using static EasyTemplate.Page.Pages.Report.FuelTransactionReport;

namespace EasyTemplate.Page.Pages.Report
{
    public partial class RechargeRecords : ComponentBase
    {
        [Inject] private SqlSugarRepository<RechargeRecordEntity> _RechargeRecordPository { get; set; }
        protected FilterModel Filter { get; set; } = new();
        protected List<TransactionItem> TransactionData { get; set; } = new();
        protected List<RechargeRecordDto> rechargeRecordDtos { 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();
        protected override void OnInitialized()
        {
            base.OnInitialized();
            InitializeData();
            _ = LoadDataAsync();
        }

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

        private void InitializeData()
        {
            // 初始化选项数据
            PaymentMethodOptions = new List<string> { "微信支付", "支付宝支付", "现金", "银联" };
            OrderStatusOptions = new List<string> { "未支付", "已完成", "已取消" };
            PaymentStatusOptions = 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()
        {
            var payStatus = Filter.PaymentStatus == "待支付" ? 0 :
                    Filter.PaymentStatus == "支付成功" ? 1 :
                    Filter.PaymentStatus == "支付失败" ? 2 : 3;
            var OStatus = Filter.OrderStatus == "未支付" ? 0 :
                          Filter.OrderStatus == "已完成" ? 1 :
                           Filter.OrderStatus == "已取消" ? 2 : 3;
            var query = _RechargeRecordPository.AsQueryable()
                          .LeftJoin<UserInfoEntity>((a, b) => a.UserId == b.Id)
                          .LeftJoin<BusinessUnitInfoEntity>((a, b, c) => a.SiteId == c.Id)
                          .LeftJoin<PayTypeEntity>((a, b, c, e) => a.PaymentMethod == e.Id);
            if (!string.IsNullOrEmpty(Filter.OrderNo))
            {
                query = query.Where((a, b, c, e) => a.PaymentNo == Filter.OrderNo);
            }
            if (!string.IsNullOrEmpty(Filter.Mobile))
            {
                query = query.Where((a, b, c, e) => b.Mobile  == Filter.Mobile);
            }
            if (!string.IsNullOrEmpty(Filter.PaymentMethod))
            {
                query = query.Where((a, b, c, e) => e.Name == Filter.PaymentMethod);
            }
            if (payStatus != 3)
            {
                query = query.Where((a, b, c, e) => a.PaymentStatus == payStatus);
            }
            if (OStatus != 3)
            {
                query = query.Where((a, b, c, e) => a.OrderStatus == OStatus);
            }
            if (Filter.StartTime != null)
            {
                query = query.Where((a, b, c, e) => a.TransactionTime > Filter.StartTime && a.TransactionTime < Filter.EndTime);
            }
            rechargeRecordDtos = await query.Select((a, b, c, e) => new RechargeRecordDto
            {
                Station = c.Name,
                OrderNo = a.PaymentNo,
                RechargeAmount = a.OriginalAmount,
                PaymentMethod = e.Name,
                RechargeType = a.Type == 1 ? "充值" : "退款",
                UserPhone = b.Mobile,
                UserName = b.UserName,
                WxNickname = b.WxName,
                UserAvatar = b.AvatarUrl,
                TransactionTime = a.TransactionTime,
                PaymentStatus = a.PaymentStatus == 0 ? "待支付" : a.PaymentStatus == 1 ? "支付成功" : "",
                OrderStatus = a.OrderStatus == 0 ? "未支付" : a.OrderStatus == 1 ? "已支付" : "",
            }).ToListAsync();
            //rechargeRecordDtos = await _RechargeRecordPository.AsQueryable()
            //              .LeftJoin<UserInfoEntity>((a, b) => a.UserId == b.Id)
            //              .LeftJoin<BusinessUnitInfoEntity>((a, b, c) => a.SiteId == c.Id)
            //              .LeftJoin<PayTypeEntity>((a, b, c,e) => a.PaymentMethod == e.Id)
            //              .Where((a, b, c, e) => a.PaymentMethod == e.Id)
            //              .Select((a, b, c,e) => new RechargeRecordDto {
            //                  Station =c.Name,
            //                  OrderNo = a.PaymentNo,
            //                  RechargeAmount = a.OriginalAmount,
            //                  PaymentMethod = e.Name,
            //                  RechargeType = a.Type == 1 ? "充值" : "退款",
            //                  UserPhone = b.Mobile,
            //                  UserName =b.UserName,
            //                  WxNickname = b.WxName,
            //                  UserAvatar = b.AvatarUrl,
            //                  TransactionTime = a.TransactionTime,
            //                  PaymentStatus = a.PaymentStatus == 0 ? "待支付" : a.PaymentStatus == 1 ? "支付成功" : "",
            //                  OrderStatus = a.OrderStatus == 0 ? "未支付" : a.OrderStatus == 1 ? "已支付" : "",
            //              })
            //              .ToListAsync();
            var data = new List<TransactionItem>();
            var random = new Random();
            var startIndex = (CurrentPage - 1) * PageSize;
            return data;
        }

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

        // 格式化货币显示
        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();
        }
    }
}