package com.izouma.nineth.web.mobile.v1.rewardpoints;


import com.izouma.nineth.domain.User;
import com.izouma.nineth.domain.DrawLotteryHistory;
import com.izouma.nineth.domain.PointActivityAward;
import com.izouma.nineth.domain.PointRewardActivity;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.enums.rewardpoints.PointActivityAwardType;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.lock.RedisLockException;
import com.izouma.nineth.service.CollectionService;
import com.izouma.nineth.service.rewardpoints.DrawLotteryHistoryService;
import com.izouma.nineth.service.rewardpoints.PointActivityService;
import com.izouma.nineth.web.BaseController;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/pointActivity/v1")
@AllArgsConstructor
public class PointActivityControllerV1 extends BaseController {
    private final PointActivityService pointActivityService;
    private final DrawLotteryHistoryService drawLotteryHistoryService;
    private final CollectionService collectionService;

    /**
     * 积分活动抽卡
     * @return
     */
    @PostMapping("/draw")
    public PointActivityAward draw(@RequestBody PointRewardActivity pointRewardActivity) {
        User user = currentUser();
        try {
            PointActivityAward pointActivityAward = pointActivityService.drawLottery(pointRewardActivity.getId(), user);
            pointActivityAward.setNum(null);
            pointActivityAward.setStock(null);
            if (PointActivityAwardType.ASSET.equals(pointActivityAward.getType())){
                collectionService.increaseStockCache(pointActivityAward.getAwardCollectionId(), -1);
            }
            return pointActivityAward;
        }catch(RedisLockException e){
            throw new BusinessException("抽取过快，请再试一次");
        }

    }

    /**
     * 当前进行的积分抽奖活动
     * @return
     */
    @PostMapping("/now")
    public PointRewardActivity now() {
        return pointActivityService.now();
    }

    /**
     * 获取当前进行的抽奖活动滚动记录
     * @return
     */
    @PostMapping("/nowActivityAwards")
    public List<DrawLotteryHistory> nowActivityAwards() {
        return pointActivityService.nowActivityAwards();
    }


    /**
     * 我的奖品
     * @return 我本次活动的奖品
     */
    @PostMapping("/awards")
    public Page<DrawLotteryHistory> awards(@RequestBody PageQuery pageQuery) {
        return drawLotteryHistoryService.awards(pageQuery,currentUser().getId());
    }

}

