package shop.alien.store.controller;


import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.vo.StorePlatformBenefitsVo;
import shop.alien.store.service.StorePlatformBenefitsService;

import java.util.List;

@Slf4j
@Api(tags = {"福利管理"})
@ApiSort(10)
@CrossOrigin
@RestController
@RequestMapping("/userBenefits")
@RequiredArgsConstructor
public class LifeUserBenefitsController {

    private final StorePlatformBenefitsService benefitsService;


    @ApiOperation("领取福利（优惠券或U币）")
    @ApiOperationSupport(order = 7)
    @PostMapping("/receive")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "福利ID", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "int", paramType = "query", required = true)
    })
    @Transactional
    public R<String> receiveBenefits(@RequestParam Integer id, @RequestParam(required = false) Integer userId) {
        log.info("StorePlatformBenefitsController.receiveBenefits - id={},userId={}", id,userId);
        try {
            String result = benefitsService.receiveBenefits(id,userId);
            return R.success(result);
        } catch (RuntimeException e) {
            log.error("StorePlatformBenefitsController.receiveBenefits - error: {}", e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("StorePlatformBenefitsController.receiveBenefits - error: ", e);
            return R.fail("领取失败，请稍后重试");
        }
    }

    // 查看所以福利，区分可领取和已领取
    @ApiOperation("查看所有福利")
    @ApiOperationSupport(order = 8)
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "int", paramType = "query", required = true)
    })
    public R<List<StorePlatformBenefitsVo>> listBenefits(@RequestParam Integer userId) {
        log.info("StorePlatformBenefitsController.listBenefits - userId={}", userId);
        try {
            List<StorePlatformBenefitsVo> benefits = benefitsService.listBenefits(userId);
            return R.data(benefits);
        } catch (Exception e) {
            log.error("StorePlatformBenefitsController.listBenefits - error: ", e);
            return R.fail("查询失败，请稍后重试");
        }
    }
}
