using HoneyBox.Admin.Business.Attributes;
using HoneyBox.Admin.Business.Models;
using HoneyBox.Admin.Business.Models.User;
using HoneyBox.Admin.Business.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;

namespace HoneyBox.Admin.Business.Controllers;

/// <summary>
/// 用户管理控制器
/// </summary>
[Route("api/admin/business/users")]
public class UserController : BusinessControllerBase
{
    private readonly IUserBusinessService _userService;

    public UserController(IUserBusinessService userService)
    {
        _userService = userService;
    }

    #region 用户列表和详情

    /// <summary>
    /// 获取用户列表
    /// </summary>
    /// <param name="request">查询请求</param>
    /// <returns>用户列表</returns>
    [HttpGet]
    [BusinessPermission("user:list")]
    public async Task<IActionResult> GetUserList([FromQuery] UserListRequest request)
    {
        try
        {
            var result = await _userService.GetUserListAsync(request);
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 获取用户详情
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <returns>用户详情</returns>
    [HttpGet("{id:int}")]
    [BusinessPermission("user:view")]
    public async Task<IActionResult> GetUserDetail(int id)
    {
        try
        {
            var result = await _userService.GetUserDetailAsync(id);
            if (result == null)
            {
                return NotFoundError("用户不存在");
            }
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    #endregion

    #region 资金变动

    /// <summary>
    /// 变更用户资金
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <param name="request">变动请求</param>
    /// <returns>操作结果</returns>
    [HttpPut("{id:int}/money")]
    [BusinessPermission("user:money")]
    public async Task<IActionResult> ChangeUserMoney(int id, [FromBody] UserMoneyChangeRequest request)
    {
        if (!ModelState.IsValid)
        {
            var errors = ModelState.Values
                .SelectMany(v => v.Errors)
                .Select(e => e.ErrorMessage)
                .FirstOrDefault();
            return ValidationError(errors ?? "参数验证失败");
        }

        try
        {
            var operatorId = (int)(GetCurrentUserId() ?? 0);
            var result = await _userService.ChangeUserMoneyAsync(id, request, operatorId);
            if (result)
            {
                return Ok("资金变动成功");
            }
            return Error(BusinessErrorCodes.InternalError, "资金变动失败");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    #endregion

    #region 状态管理

    /// <summary>
    /// 设置用户状态（封号/解封）
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <param name="request">状态请求</param>
    /// <returns>操作结果</returns>
    [HttpPut("{id:int}/status")]
    [BusinessPermission("user:status")]
    public async Task<IActionResult> SetUserStatus(int id, [FromBody] UserStatusRequest request)
    {
        if (!ModelState.IsValid)
        {
            return ValidationError("参数验证失败");
        }

        try
        {
            var result = await _userService.SetUserStatusAsync(id, request.Status);
            if (result)
            {
                var statusText = request.Status == 1 ? "解封" : "封号";
                return Ok($"用户{statusText}成功");
            }
            return Error(BusinessErrorCodes.InternalError, "状态变更失败");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 设置测试账号标识
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <param name="request">测试账号请求</param>
    /// <returns>操作结果</returns>
    [HttpPut("{id:int}/test")]
    [BusinessPermission("user:test")]
    public async Task<IActionResult> SetTestAccount(int id, [FromBody] UserTestAccountRequest request)
    {
        if (!ModelState.IsValid)
        {
            return ValidationError("参数验证失败");
        }

        try
        {
            var result = await _userService.SetTestAccountAsync(id, request.IsTest);
            if (result)
            {
                var statusText = request.IsTest == 1 ? "设置为测试账号" : "取消测试账号";
                return Ok($"已{statusText}");
            }
            return Error(BusinessErrorCodes.InternalError, "设置失败");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 清空用户手机号
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <returns>操作结果</returns>
    [HttpDelete("{id:int}/mobile")]
    [BusinessPermission("user:clear")]
    public async Task<IActionResult> ClearMobile(int id)
    {
        try
        {
            var result = await _userService.ClearMobileAsync(id);
            if (result)
            {
                return Ok("手机号已清空");
            }
            return Error(BusinessErrorCodes.InternalError, "清空失败");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 清空用户微信绑定
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <returns>操作结果</returns>
    [HttpDelete("{id:int}/wechat")]
    [BusinessPermission("user:clear")]
    public async Task<IActionResult> ClearWeChat(int id)
    {
        try
        {
            var result = await _userService.ClearWeChatAsync(id);
            if (result)
            {
                return Ok("微信绑定已清空");
            }
            return Error(BusinessErrorCodes.InternalError, "清空失败");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    #endregion


    #region 赠送功能

    /// <summary>
    /// 赠送优惠券给用户
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <param name="request">赠送请求</param>
    /// <returns>操作结果</returns>
    [HttpPost("{id:int}/coupon")]
    [BusinessPermission("user:gift")]
    public async Task<IActionResult> GiftCoupon(int id, [FromBody] GiftCouponRequest request)
    {
        if (!ModelState.IsValid)
        {
            var errors = ModelState.Values
                .SelectMany(v => v.Errors)
                .Select(e => e.ErrorMessage)
                .FirstOrDefault();
            return ValidationError(errors ?? "参数验证失败");
        }

        try
        {
            var result = await _userService.GiftCouponAsync(id, request);
            if (result)
            {
                return Ok("优惠券赠送成功");
            }
            return Error(BusinessErrorCodes.InternalError, "赠送失败");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 赠送卡牌给用户
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <param name="request">赠送请求</param>
    /// <returns>操作结果</returns>
    [HttpPost("{id:int}/card")]
    [BusinessPermission("user:gift")]
    public async Task<IActionResult> GiftCard(int id, [FromBody] GiftCardRequest request)
    {
        if (!ModelState.IsValid)
        {
            var errors = ModelState.Values
                .SelectMany(v => v.Errors)
                .Select(e => e.ErrorMessage)
                .FirstOrDefault();
            return ValidationError(errors ?? "参数验证失败");
        }

        try
        {
            var result = await _userService.GiftCardAsync(id, request);
            if (result)
            {
                return Ok("卡牌赠送成功");
            }
            return Error(BusinessErrorCodes.InternalError, "赠送失败");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    #endregion

    #region 统计功能

    /// <summary>
    /// 获取用户盈亏统计
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <param name="startDate">开始日期</param>
    /// <param name="endDate">结束日期</param>
    /// <returns>盈亏统计</returns>
    [HttpGet("{id:int}/profit")]
    [BusinessPermission("user:view")]
    public async Task<IActionResult> GetUserProfitLoss(int id, [FromQuery] DateTime? startDate, [FromQuery] DateTime? endDate)
    {
        try
        {
            var dateRange = (startDate.HasValue || endDate.HasValue)
                ? new DateRange { StartDate = startDate, EndDate = endDate }
                : null;

            var result = await _userService.GetUserProfitLossAsync(id, dateRange);
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 获取下级用户列表
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <param name="page">页码</param>
    /// <param name="pageSize">每页数量</param>
    /// <returns>下级用户列表</returns>
    [HttpGet("{id:int}/team")]
    [BusinessPermission("user:view")]
    public async Task<IActionResult> GetSubordinateUsers(int id, [FromQuery] int page = 1, [FromQuery] int pageSize = 20)
    {
        try
        {
            var result = await _userService.GetSubordinateUsersAsync(id, page, pageSize);
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    #endregion

    #region 用户详情相关

    /// <summary>
    /// 获取用户盒柜列表
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <param name="query">查询参数</param>
    /// <returns>盒柜列表</returns>
    [HttpGet("{id:int}/box")]
    [BusinessPermission("user:view")]
    public async Task<IActionResult> GetUserBox(int id, [FromQuery] UserBoxQuery query)
    {
        try
        {
            var result = await _userService.GetUserBoxAsync(id, query);
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 获取用户订单列表
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <param name="query">查询参数</param>
    /// <returns>订单列表</returns>
    [HttpGet("{id:int}/orders")]
    [BusinessPermission("user:view")]
    public async Task<IActionResult> GetUserOrders(int id, [FromQuery] UserOrderQuery query)
    {
        try
        {
            var result = await _userService.GetUserOrdersAsync(id, query);
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 获取用户余额流水明细
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <param name="query">查询参数</param>
    /// <returns>流水明细列表</returns>
    [HttpGet("{id:int}/money-detail")]
    [BusinessPermission("user:view")]
    public async Task<IActionResult> GetUserMoneyDetail(int id, [FromQuery] MoneyDetailQuery query)
    {
        try
        {
            var result = await _userService.GetUserMoneyDetailAsync(id, query);
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 获取用户积分流水明细
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <param name="query">查询参数</param>
    /// <returns>流水明细列表</returns>
    [HttpGet("{id:int}/integral-detail")]
    [BusinessPermission("user:view")]
    public async Task<IActionResult> GetUserIntegralDetail(int id, [FromQuery] MoneyDetailQuery query)
    {
        try
        {
            var result = await _userService.GetUserIntegralDetailAsync(id, query);
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 获取用户钻石流水明细
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <param name="query">查询参数</param>
    /// <returns>流水明细列表</returns>
    [HttpGet("{id:int}/score-detail")]
    [BusinessPermission("user:view")]
    public async Task<IActionResult> GetUserScoreDetail(int id, [FromQuery] MoneyDetailQuery query)
    {
        try
        {
            var result = await _userService.GetUserScoreDetailAsync(id, query);
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 获取用户哈尼券流水明细
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <param name="query">查询参数</param>
    /// <returns>流水明细列表</returns>
    [HttpGet("{id:int}/money2-detail")]
    [BusinessPermission("user:view")]
    public async Task<IActionResult> GetUserMoney2Detail(int id, [FromQuery] MoneyDetailQuery query)
    {
        try
        {
            var result = await _userService.GetUserMoney2DetailAsync(id, query);
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 获取用户IP登录历史
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <param name="page">页码</param>
    /// <param name="pageSize">每页数量</param>
    /// <returns>IP登录历史列表</returns>
    [HttpGet("{id:int}/ip-logs")]
    [BusinessPermission("user:view")]
    public async Task<IActionResult> GetUserIpLogs(int id, [FromQuery] int page = 1, [FromQuery] int pageSize = 20)
    {
        try
        {
            var result = await _userService.GetUserIpLogsAsync(id, page, pageSize);
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    #endregion

    #region 统计和操作相关

    /// <summary>
    /// 获取用户邀请统计列表
    /// </summary>
    /// <param name="query">查询参数</param>
    /// <returns>邀请统计列表</returns>
    [HttpGet("invite-stats")]
    [BusinessPermission("user:view")]
    public async Task<IActionResult> GetInviteStats([FromQuery] InviteStatsQuery query)
    {
        try
        {
            var result = await _userService.GetInviteStatsAsync(query);
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 获取用户登录统计
    /// </summary>
    /// <param name="query">查询参数</param>
    /// <returns>登录统计数据</returns>
    [HttpGet("login-stats")]
    [BusinessPermission("user:view")]
    public async Task<IActionResult> GetLoginStats([FromQuery] LoginStatsQuery query)
    {
        try
        {
            var result = await _userService.GetLoginStatsAsync(query);
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 获取用户盈亏列表
    /// </summary>
    /// <param name="query">查询参数</param>
    /// <returns>盈亏列表</returns>
    [HttpGet("profit-loss-list")]
    [BusinessPermission("user:view")]
    public async Task<IActionResult> GetProfitLossList([FromQuery] ProfitLossListQuery query)
    {
        try
        {
            var result = await _userService.GetProfitLossListAsync(query);
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 绑定用户手机号
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <param name="request">绑定请求</param>
    /// <returns>操作结果</returns>
    [HttpPut("{id:int}/mobile")]
    [BusinessPermission("user:edit")]
    public async Task<IActionResult> BindMobile(int id, [FromBody] BindMobileRequest request)
    {
        if (!ModelState.IsValid || string.IsNullOrWhiteSpace(request.Mobile))
        {
            return ValidationError("手机号不能为空");
        }

        try
        {
            var result = await _userService.BindMobileAsync(id, request.Mobile);
            if (result)
            {
                return Ok("手机号绑定成功");
            }
            return Error(BusinessErrorCodes.InternalError, "绑定失败");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 重置用户签到数据
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <returns>操作结果</returns>
    [HttpPut("{id:int}/sign-reset")]
    [BusinessPermission("user:edit")]
    public async Task<IActionResult> ResetUserSign(int id)
    {
        try
        {
            var result = await _userService.ResetUserSignAsync(id);
            if (result)
            {
                return Ok("签到数据已重置");
            }
            return Error(BusinessErrorCodes.InternalError, "重置失败");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 清空用户UID
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <returns>操作结果</returns>
    [HttpDelete("{id:int}/uid")]
    [BusinessPermission("user:clear")]
    public async Task<IActionResult> ClearUid(int id)
    {
        try
        {
            var result = await _userService.ClearUidAsync(id);
            if (result)
            {
                return Ok("UID已清空");
            }
            return Error(BusinessErrorCodes.InternalError, "清空失败");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    #endregion
}
