package com.ruoyi.app.user;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.PromotionUserCoupon;
import com.ruoyi.system.domain.dto.ReceiveCouponDto;
import com.ruoyi.system.domain.vo.StoreCouponVO;
import com.ruoyi.system.domain.vo.MyCouponVO;
import com.ruoyi.system.service.IPromotionUserCouponService;
import com.ruoyi.system.utils.Auth;
import com.ruoyi.system.utils.JwtUtil;

/**
 * 用户端优惠券接口
 *
 * 【优惠券规则】
 * 1. 每个用户每批次限领1张优惠券
 * 2. 每个订单最多使用1张优惠券(满减券/商品券/免配送费券三选一)
 * 3. 同享券(isMutex=0)可与促销叠加，互斥券(isMutex=1)与促销二选一
 * 4. 已领取的券在有效期内可用，过期自动标记不可用
 * 5. 领取后商家修改/下架券批次，已领取的券仍可使用(快照机制)
 * 6. 并发领取使用乐观锁扣库存(UPDATE remain_count=remain_count-1 WHERE remain_count>0)
 */
@RestController
@RequestMapping("/app/userPromotionCoupon")
public class UserPromotionCouponController extends BaseController {

    @Autowired
    private IPromotionUserCouponService userCouponService;

    /**
     * 查询门店可领优惠券列表
     *
     * @param token   用户登录token
     * @param storeId 门店ID
     * @return 券批次列表，每条含 id,name,couponType,threshold,amount,validDays,received(是否已领)
     */
    @Anonymous
    @Auth
    @GetMapping("/storeCoupons")
    public AjaxResult storeCoupons(@RequestHeader String token,@RequestParam Long storeId) {
        JwtUtil jwtUtil=new JwtUtil();
        String userId = jwtUtil.getusid(token);
        if (userId == null) {
            return AjaxResult.error("请先登录");
        }
        List<StoreCouponVO> list = userCouponService.selectStoreCouponsForUser(Long.valueOf(userId), storeId);
        return AjaxResult.success(list);
    }

    /**
     * 领取优惠券
     *
     * 规则：每用户每批次限领1张，乐观锁扣库存，领取后计算过期时间(领取日期+validDays天23:59:59)
     *
     * @param token  用户登录token
     * @param dto batchId(必填), storeId(必填)
     * @return 领取成功的券实例
     */
    @Anonymous
    @Auth
    @PostMapping("/receive")
    public AjaxResult receive(@RequestHeader String token,@RequestBody ReceiveCouponDto dto) {
        JwtUtil jwtUtil=new JwtUtil();
        String userId = jwtUtil.getusid(token);
        if (userId == null) {
            return AjaxResult.error("请先登录");
        }
        if (dto.getBatchId() == null) {
            return AjaxResult.error("参数错误：缺少batchId");
        }
        PromotionUserCoupon coupon = userCouponService.receiveCoupon(Long.valueOf(userId), dto.getBatchId(), dto.getStoreId());
        return AjaxResult.success("领取成功", coupon);
    }

    /**
     * 查询我的优惠券列表
     *
     * 实时判断过期：expire_time < NOW() 的券自动标记为已过期(status=2)
     *
     * @param token   用户登录token
     * @param status  券状态(选填): 0=未使用 1=已使用 2=已过期，不传则返回全部
     * @param storeId 门店ID(选填)，不传则返回所有门店的券
     * @return 用户券列表，含 storeName, batchName, couponType, status, expireTime 等
     */
    @Anonymous
    @Auth
    @GetMapping("/myCoupons")
    public AjaxResult myCoupons(@RequestHeader String token,@RequestParam(required = false) Integer status,
                                @RequestParam(required = false) Long storeId) {
        JwtUtil jwtUtil=new JwtUtil();
        String userId = jwtUtil.getusid(token);
        if (userId == null) {
            return AjaxResult.error("请先登录");
        }
        List<MyCouponVO> list = userCouponService.selectMyCoupons(Long.valueOf(userId), status, storeId);
        return AjaxResult.success(list);
    }
}
