using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using VendingMachine.Application.Common;
using VendingMachine.Application.Services;
namespace VendingMachine.Api.Controllers;
[ApiController]
[Route("api/[controller]")]
public class CouponController : ControllerBase
{
private readonly ICouponService _couponService;
public CouponController(ICouponService couponService)
{
_couponService = couponService;
}
///
/// 获取可兑换优惠券列表
///
[HttpGet("redeemable")]
public async Task GetRedeemableCoupons()
{
var lang = GetLanguage();
var result = await _couponService.GetRedeemableCouponsAsync(lang);
return Ok(result);
}
///
/// 兑换优惠券
///
[Authorize]
[HttpPost("redeem/{couponId}")]
public async Task RedeemCoupon(string couponId)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (string.IsNullOrEmpty(uid))
return Unauthorized(ApiResponse.Fail("未授权"));
var result = await _couponService.RedeemCouponAsync(uid, couponId);
return result.Success ? Ok(result) : BadRequest(result);
}
///
/// 获取用户优惠券列表
///
[Authorize]
[HttpGet("my")]
public async Task GetMyCoupons([FromQuery] string? status)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (string.IsNullOrEmpty(uid))
return Unauthorized(ApiResponse.Fail("未授权"));
var lang = GetLanguage();
var result = await _couponService.GetMyCouponsAsync(uid, status, lang);
return Ok(result);
}
///
/// 获取印花优惠券列表
///
[Authorize]
[HttpGet("stamps")]
public async Task GetStampCoupons()
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (string.IsNullOrEmpty(uid))
return Unauthorized(ApiResponse.Fail("未授权"));
var lang = GetLanguage();
var result = await _couponService.GetStampCouponsAsync(uid, lang);
return Ok(result);
}
///
/// 兑换印花优惠券
///
[Authorize]
[HttpPost("stamps/redeem/{stampCouponId}")]
public async Task RedeemStampCoupon(string stampCouponId)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (string.IsNullOrEmpty(uid))
return Unauthorized(ApiResponse.Fail("未授权"));
var result = await _couponService.RedeemStampCouponAsync(uid, stampCouponId);
return result.Success ? Ok(result) : BadRequest(result);
}
///
/// 从请求头获取语言设置
///
private string GetLanguage()
{
return HttpContext.Items["Language"]?.ToString() ?? "zh-CN";
}
}