package jnpf.cultivate.v2.controller.app.exam;

import jnpf.base.ActionResult;
import jnpf.cultivate.service.FtbCultivateExamUserService;
import jnpf.cultivate.v2.service.V2CultivateExamService;
import jnpf.model.cultivate.po.exam.FtbCultivateExamUser;
import jnpf.model.cultivate.req.exam.SubExamQuestionReq;
import jnpf.model.cultivate.resp.SubExamVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 我的考试[app]
 *
 * @author yanwenfu
 * @create 2026-03-26
 */
@RestController
@RequestMapping(value = "/v2/app/exam")
public class ExamSubController {

    @Resource
    private FtbCultivateExamUserService examUserService;
    @Resource
    private V2CultivateExamService v2CultivateExamService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 提交试卷
     * @param userExamId 用户考试ID
     * @param req 请求参数
     * @return jnpf.base.ActionResult<jnpf.model.cultivate.resp.SubExamVo>
     */
    @PostMapping("/sub-user-exam/{userExamId}")
    public ActionResult<SubExamVo> subUserExam(@PathVariable("userExamId") String userExamId, @RequestBody @Valid SubExamQuestionReq req) {

        FtbCultivateExamUser examUser = examUserService.getById(userExamId);
        if (null == examUser || examUser.getEnabledMark() == 0) {
            return ActionResult.fail(1000, "考试记录已经删除");
        }
        String lockKey = "subExam" + userExamId;
        if (redisTemplate.opsForValue().setIfAbsent(lockKey, UUID.randomUUID().toString(), 10, TimeUnit.SECONDS)) {
            try {
                SubExamVo subExamVo = v2CultivateExamService.subUserExam(userExamId, req);
                return ActionResult.success(subExamVo);
            } catch (Exception e) {
                throw e;
            } finally {
                redisTemplate.delete(lockKey);
            }
        } else {
            throw new RuntimeException("考试提交中,请不要重复提交");
        }
    }
}
