using System.Text.Json;
using HoneyBox.Core.Interfaces;
using HoneyBox.Model.Data;
using HoneyBox.Model.Entities;
using HoneyBox.Model.Models.Payment;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace HoneyBox.Core.Services;

/// <summary>
/// 充值服务实现
/// Requirements: 2.1-2.6
/// </summary>
public class RechargeService : IRechargeService
{
    private readonly HoneyBoxDbContext _dbContext;
    private readonly IWechatPayService _wechatPayService;
    private readonly IPaymentService _paymentService;
    private readonly ILogger<RechargeService> _logger;

    /// <summary>
    /// 默认最低充值金额
    /// </summary>
    private const decimal DEFAULT_MIN_RECHARGE = 10m;

    public RechargeService(
        HoneyBoxDbContext dbContext,
        IWechatPayService wechatPayService,
        IPaymentService paymentService,
        ILogger<RechargeService> logger)
    {
        _dbContext = dbContext;
        _wechatPayService = wechatPayService;
        _paymentService = paymentService;
        _logger = logger;
    }

    /// <inheritdoc />
    public async Task<RechargeResult> CreateRechargeOrderAsync(int userId, decimal money)
    {
        try
        {
            _logger.LogInformation("创建充值订单: UserId={UserId}, Money={Money}", userId, money);

            // 1. 验证用户
            var user = await _dbContext.Users.FirstOrDefaultAsync(u => u.Id == userId);
            if (user == null)
            {
                return new RechargeResult { Status = 0, Msg = "用户不存在" };
            }

            // 2. 验证手机号绑定
            if (string.IsNullOrEmpty(user.Mobile))
            {
                return new RechargeResult { Status = 0, Msg = "请先绑定手机号" };
            }

            // 3. 验证充值金额
            if (money <= 0)
            {
                return new RechargeResult { Status = 0, Msg = "请输入充值金额" };
            }

            // 4. 获取最低充值金额配置
            var minMoney = await GetMinRechargeMoneyAsync();
            if (money < minMoney)
            {
                return new RechargeResult { Status = 0, Msg = $"充值金额最低{minMoney}起" };
            }

            // 5. 生成订单号
            var orderNum = GenerateOrderNum("CZ_");

            // 6. 创建充值订单记录
            var rechargeOrder = new UserRecharge
            {
                UserId = userId,
                OrderNum = orderNum,
                Money = money,
                Status = 1, // 待支付
                CreatedAt = (int)DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
                PayTime = 0
            };

            _dbContext.UserRecharges.Add(rechargeOrder);
            await _dbContext.SaveChangesAsync();

            // 7. 调用微信支付创建订单
            var payRequest = new WechatPayRequest
            {
                OrderNo = orderNum,
                Amount = money,
                Body = $"充值金额{money}",
                Attach = OrderAttachType.UserRecharge,
                UserId = userId
            };

            var payResult = await _wechatPayService.CreatePaymentAsync(payRequest);

            if (payResult.Status != 1)
            {
                _logger.LogWarning("创建微信支付订单失败: OrderNum={OrderNum}, Msg={Msg}", orderNum, payResult.Msg);
                return new RechargeResult { Status = 0, Msg = payResult.Msg };
            }

            _logger.LogInformation("充值订单创建成功: OrderNum={OrderNum}", orderNum);

            return new RechargeResult
            {
                Status = 1,
                Msg = "请求成功",
                Data = payResult.Data,
                OrderNum = orderNum
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建充值订单异常: UserId={UserId}, Money={Money}", userId, money);
            return new RechargeResult { Status = 0, Msg = "网络故障，请稍后重试" };
        }
    }

    /// <inheritdoc />
    public async Task<RechargeConfigResponse> GetRechargeConfigAsync()
    {
        try
        {
            var minMoney = await GetMinRechargeMoneyAsync();

            // 默认充值选项
            var options = new List<RechargeOption>
            {
                new() { Money = 10, Gift = 0, Label = "" },
                new() { Money = 30, Gift = 0, Label = "" },
                new() { Money = 50, Gift = 0, Label = "" },
                new() { Money = 100, Gift = 0, Label = "" },
                new() { Money = 200, Gift = 0, Label = "" },
                new() { Money = 500, Gift = 0, Label = "" }
            };

            return new RechargeConfigResponse
            {
                MinMoney = minMoney,
                Description = $"充值金额最低{minMoney}元起",
                Options = options
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取充值配置异常");
            return new RechargeConfigResponse
            {
                MinMoney = DEFAULT_MIN_RECHARGE,
                Description = $"充值金额最低{DEFAULT_MIN_RECHARGE}元起",
                Options = new List<RechargeOption>()
            };
        }
    }

    /// <inheritdoc />
    public async Task<PayStatusResponse> QueryPayStatusAsync(string orderNum)
    {
        try
        {
            if (string.IsNullOrEmpty(orderNum))
            {
                return new PayStatusResponse
                {
                    Status = -1,
                    StatusText = "订单号不能为空",
                    OrderNum = orderNum
                };
            }

            var orderNotify = await _dbContext.OrderNotifies
                .FirstOrDefaultAsync(o => o.OrderNo == orderNum);

            if (orderNotify == null)
            {
                return new PayStatusResponse
                {
                    Status = -1,
                    StatusText = "订单不存在",
                    OrderNum = orderNum
                };
            }

            var statusText = orderNotify.Status switch
            {
                0 => "支付未完成，请10秒后重试！",
                1 => "支付成功",
                2 => "订单已失效",
                _ => "未知状态"
            };

            return new PayStatusResponse
            {
                Status = orderNotify.Status,
                StatusText = statusText,
                OrderNum = orderNum
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "查询支付状态异常: OrderNum={OrderNum}", orderNum);
            return new PayStatusResponse
            {
                Status = -1,
                StatusText = "查询失败",
                OrderNum = orderNum
            };
        }
    }

    /// <inheritdoc />
    public async Task<BalancePayResult> BalancePayAsync(int userId, string orderNum, decimal amount)
    {
        try
        {
            _logger.LogInformation("余额支付: UserId={UserId}, OrderNum={OrderNum}, Amount={Amount}",
                userId, orderNum, amount);

            // 1. 验证用户
            var user = await _dbContext.Users.FirstOrDefaultAsync(u => u.Id == userId);
            if (user == null)
            {
                return new BalancePayResult { Status = 0, Msg = "用户不存在" };
            }

            // 2. 验证余额
            if (user.Money < amount)
            {
                return new BalancePayResult
                {
                    Status = 0,
                    Msg = "余额不足",
                    Balance = user.Money
                };
            }

            // 3. 扣减余额
            var deductResult = await _paymentService.DeductBalanceAsync(
                userId, amount, "余额支付", orderNum, 3);

            if (!deductResult.Success)
            {
                return new BalancePayResult
                {
                    Status = 0,
                    Msg = deductResult.Message,
                    Balance = user.Money
                };
            }

            // 4. 记录支付流水
            await _paymentService.RecordPaymentAsync(
                userId, orderNum, amount, PaymentType.BalancePay, "余额支付");

            _logger.LogInformation("余额支付成功: UserId={UserId}, OrderNum={OrderNum}, Amount={Amount}",
                userId, orderNum, amount);

            return new BalancePayResult
            {
                Status = 1,
                Msg = "支付成功",
                Balance = deductResult.RemainingBalance
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "余额支付异常: UserId={UserId}, OrderNum={OrderNum}", userId, orderNum);
            return new BalancePayResult { Status = 0, Msg = "支付失败，请稍后重试" };
        }
    }

    /// <inheritdoc />
    public async Task<bool> HandleRechargeSuccessAsync(string orderNum)
    {
        try
        {
            _logger.LogInformation("处理充值成功回调: OrderNum={OrderNum}", orderNum);

            // 1. 查找充值订单
            var rechargeOrder = await _dbContext.UserRecharges
                .FirstOrDefaultAsync(r => r.OrderNum == orderNum && r.Status == 1);

            if (rechargeOrder == null)
            {
                _logger.LogWarning("充值订单不存在或已处理: OrderNum={OrderNum}", orderNum);
                return false;
            }

            // 2. 更新订单状态
            rechargeOrder.Status = 2; // 已完成
            rechargeOrder.PayTime = (int)DateTimeOffset.UtcNow.ToUnixTimeSeconds();

            // 3. 增加用户余额
            var addResult = await _paymentService.AddBalanceAsync(
                rechargeOrder.UserId,
                rechargeOrder.Money,
                $"在线充值{rechargeOrder.Money}元",
                orderNum,
                2); // type=2 在线充值

            if (!addResult)
            {
                _logger.LogError("增加用户余额失败: UserId={UserId}, Money={Money}",
                    rechargeOrder.UserId, rechargeOrder.Money);
                return false;
            }

            await _dbContext.SaveChangesAsync();

            _logger.LogInformation("充值成功处理完成: OrderNum={OrderNum}, UserId={UserId}, Money={Money}",
                orderNum, rechargeOrder.UserId, rechargeOrder.Money);

            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理充值成功回调异常: OrderNum={OrderNum}", orderNum);
            return false;
        }
    }

    #region Private Methods

    /// <summary>
    /// 获取最低充值金额配置
    /// </summary>
    private async Task<decimal> GetMinRechargeMoneyAsync()
    {
        try
        {
            var config = await _dbContext.Configs
                .FirstOrDefaultAsync(c => c.ConfigKey == "base");

            if (config != null && !string.IsNullOrEmpty(config.ConfigValue))
            {
                using var doc = JsonDocument.Parse(config.ConfigValue);
                if (doc.RootElement.TryGetProperty("recharge_money", out var rechargeMoney))
                {
                    if (rechargeMoney.ValueKind == JsonValueKind.Number)
                    {
                        return rechargeMoney.GetDecimal();
                    }
                    if (rechargeMoney.ValueKind == JsonValueKind.String &&
                        decimal.TryParse(rechargeMoney.GetString(), out var money))
                    {
                        return money;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "获取最低充值金额配置失败，使用默认值");
        }

        return DEFAULT_MIN_RECHARGE;
    }

    /// <summary>
    /// 生成订单号
    /// </summary>
    private static string GenerateOrderNum(string prefix)
    {
        var timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
        var random = new Random().Next(100000, 999999);
        return $"{prefix}{timestamp}{random}";
    }

    #endregion
}
