package com.gree.mall.miniapp.controller.acitivy;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gree.mall.miniapp.bean.promotion.PromotionLuckDrawExchangeDetail;
import com.gree.mall.miniapp.constant.Constant;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import com.gree.mall.miniapp.helper.ResponseHelper;
import com.gree.mall.miniapp.logic.acitivy.PromotionLuckDrawLogic;
import com.gree.mall.miniapp.plus.entity.PromotionLuckDrawCouponCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ResponseHeader;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Slf4j
@RestController
@Api(value = "抽奖活动API", tags ={"抽奖活动API"} )
@RequestMapping(value = "/promotion/luck/draw", produces = "application/json; charset=utf-8")
public class PromotionLuckDrawController {


    @Autowired
    PromotionLuckDrawLogic promotionLuckDrawLogic;
    @Autowired
    RedisLockRegistry redisLockRegistry;

    @ApiOperation("兑换")
    @PostMapping("/exchange")
    public ResponseHelper<PromotionLuckDrawExchangeDetail> exchange(
            @ApiParam("兑换码") @RequestParam String code,
            HttpServletRequest request
    ) throws InterruptedException {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_EXCHANGE_CODE + code);
        if(!obtain.tryLock(10,TimeUnit.SECONDS)){
            throw new RemoteServiceException("系统繁忙请稍后再试");
        }
        try {
            PromotionLuckDrawExchangeDetail exchange = promotionLuckDrawLogic.exchange(code, request);
            return ResponseHelper.success(exchange);
        }finally {
            obtain.unlock();
        }
    }

    @ApiOperation("历史兑换记录")
    @PostMapping("/list")
    public ResponseHelper<IPage<PromotionLuckDrawCouponCode>> list(
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize,
            HttpServletRequest request
    ){
        IPage<PromotionLuckDrawCouponCode> list = promotionLuckDrawLogic.list(pageNum, pageSize, request);
        return ResponseHelper.success(list);
    }

    @ApiOperation("历史兑换详情")
    @PostMapping("/detail")
    public ResponseHelper<PromotionLuckDrawExchangeDetail> detail(
            @RequestParam String code
    ){
        PromotionLuckDrawExchangeDetail detail = promotionLuckDrawLogic.detail(code);
        return ResponseHelper.success(detail);
    }

}
