package thyyxxk.webserver.controller.singlepage;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import thyyxxk.webserver.config.auth.PassToken;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.dao.his.singlepage.LotteryDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.singlepage.lottery.LotteryResult;
import thyyxxk.webserver.entity.singlepage.lottery.LotteryUser;
import thyyxxk.webserver.utils.ResultVoUtil;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/lottery")
public class LotteryController {
    private final LotteryDao dao;

    @Autowired
    public LotteryController(LotteryDao dao) {
        this.dao = dao;
    }

    @PassToken
    @GetMapping("/selectLotteryUsers")
    public ResultVo<List<LotteryUser>> selectLotteryUsers() {
        return ResultVoUtil.success(dao.selectLotteryUsers());
    }

    @PassToken
    @PostMapping("/chooseWinner")
    public ResultVo<LotteryUser> chooseWinner() {
        LotteryUser user = dao.selectRandomLotteryUser();
        if (null == user) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "所以人都已中奖，无法进行下一轮抽奖。");
        }
        return ResultVoUtil.success(user);
    }

    @PassToken
    @PostMapping("/recordLotteryResult")
    public ResultVo<Integer> recordLotteryResult(@RequestBody LotteryResult result) {
        return ResultVoUtil.success(dao.updateLotteryResult(result));
    }

    @PassToken
    @PostMapping("/selectWonUsers")
    public ResultVo<List<LotteryUser>> selectWonUsers(@RequestBody List<Integer> request) {
        if (request.isEmpty()) {
            return ResultVoUtil.fail(ExceptionEnum.SLIGHTLY_ERROR);
        }
        StringBuilder builder = new StringBuilder();
        for (Integer code : request) {
            builder.append(",").append(code);
        }
        String statement = builder.substring(1);
        List<LotteryUser> wonUsers = dao.selectWonUsers(statement);
        return ResultVoUtil.success(wonUsers);
    }
}
