package com.tzy.controller.appuser;

import com.tzy.annotation.ApiLimitRule;
import com.tzy.common.config.handle.ApiVersion;
import com.tzy.common.core.domain.AjaxResult;
import com.tzy.common.dto.OutDTO;
import com.tzy.common.dto.UserInfo;
import com.tzy.common.utils.UserUtils;
import com.tzy.dto.QuizActivityDto;
import com.tzy.dto.QuizActivityParam;
import com.tzy.dto.QuizLibDto;
import com.tzy.framework.web.domain.LimitRule;
import com.tzy.pojo.quiz.QuizAnswer;
import com.tzy.service.QuizActivityService;
import com.tzy.service.QuizAnswerService;
import com.tzy.service.QuizLibService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 答题活动
 */

@Api(tags = "答题活动")
@RestController
@RequestMapping("/api/{version}/quiz")
public class QuizActivityController {

    @Autowired
    QuizLibService quizLibService;
    @Autowired
    QuizActivityService quizActivityService;
    @Autowired
    QuizAnswerService quizAnswerService;
    /**
     * 根据活动id查询题目，且当前时间在活动时间范围内,
     * 判断用户是否已在该轮次答题，已答题，直接返回，未答题，随机生成题目
     */
    @PostMapping("/quizLib/{id}")
    @ApiVersion(1.0)
    @ApiOperation("查询答题活动详情及题目列表")
    public AjaxResult getQuizLibList(@PathVariable("id") Long activityId){
        QuizActivityDto quizActivityDto = quizActivityService.getById(activityId);
        //判断当前活动状态及时间范围
        if (quizActivityDto.getStatus()==0){
            return AjaxResult.error("当前活动未开启");
        }
        Date now = new Date();
        Date startTime = quizActivityDto.getStartTime();
        if (now.before(startTime)||now.after(quizActivityDto.getEndTime())){
            return AjaxResult.error("当前时间不在活动时间范围内");
        }
        //计算当前答题轮次
        long round = quizActivityService.calculateRound(quizActivityDto);
        //查询用户答题轮次是否大于等于当前轮次
        UserInfo simpleUserInfo = UserUtils.getSimpleUserInfo();
        if (simpleUserInfo==null){
            return AjaxResult.error("请先登录");
        }
        Integer id = simpleUserInfo.getId();
        int count = quizAnswerService.countRoundByUser(id, round,activityId);
        if (count>0){
            return AjaxResult.error("您已参与本轮答题活动");
        }
        //查询活动题库
        List<QuizLibDto> quizLibDtoList = quizLibService.queryQuizLibByActivityId(activityId);
        //非必答题集合
        List<QuizLibDto> optionQuizLib = quizLibDtoList.stream().filter(quizLibDto -> quizLibDto.getRequired() == 0).collect(Collectors.toList());
        //必答题集合
        List<QuizLibDto> mustAnswerQuizLib = quizLibDtoList.stream().filter(quizLibDto -> quizLibDto.getRequired() == 1).collect(Collectors.toList());
        //假如有必答题

        int randomNum = quizActivityDto.getQuestionNum() - mustAnswerQuizLib.size();
        if (randomNum > 0) {
            //需要随机生成剩余题目,题目不能重复
            Random random = new Random();
            random.ints(0, optionQuizLib.size()).distinct().limit(randomNum).forEach((i) -> {
                QuizLibDto quizLibDto = optionQuizLib.get(i);
                //加入题目集合
                mustAnswerQuizLib.add(quizLibDto);
            });
        }


        quizActivityDto.setQuizLibDtoList(mustAnswerQuizLib);
        return AjaxResult.success(quizActivityDto);
    }

    /**
     * 用户答题接口
     * @return
     */
    @PostMapping("/answer")
    @ApiVersion(1.0)
    @ApiLimitRule(seconds = 2,limitCount=1,type= LimitRule.USER,msg="操作频繁,请稍后再试!")
    @ApiOperation("用户提交答题接口")
    public OutDTO answer(@RequestBody QuizActivityParam quizActivityParam){
        //计算当前答题轮次，并判断用户当前答题轮次是否大于等于当前轮次
        QuizActivityDto quizActivityDto = quizActivityService.getById(quizActivityParam.getActivityId());
        //判断当前活动状态及时间范围
        if (quizActivityDto.getStatus()==0){
            return OutDTO.error500("当前活动未开启");
        }
        Date now = new Date();
        Date startTime = quizActivityDto.getStartTime();
        if (now.before(startTime)||now.after(quizActivityDto.getEndTime())){
            return OutDTO.error500("当前时间不在活动时间范围内");
        }
        //计算当前答题轮次
        long round = quizActivityService.calculateRound(quizActivityDto);
        UserInfo simpleUserInfo = UserUtils.getSimpleUserInfo();
        if (simpleUserInfo==null){
            return OutDTO.error500("请先登录");
        }
        Integer userInfoId = simpleUserInfo.getId();
        int count = quizAnswerService.countRoundByUser(userInfoId, round,quizActivityParam.getActivityId());
        if (count>0){
            return OutDTO.error500("您已参与本轮答题活动");
        }
        //插入用户答题表
        List<QuizAnswer> quizAnswers = quizActivityParam.getQuizAnswers();
        quizAnswers.forEach(quizAnswer -> {
            quizAnswer.setRound(round);
            quizAnswer.setActivityId(quizActivityParam.getActivityId());
            quizAnswer.setUserId(userInfoId);
        });
        boolean batchSaveAnswer = quizAnswerService.batchSaveAnswer(quizAnswers);
        if (!batchSaveAnswer){
            return OutDTO.error500("答题失败，请联系系统管理员");
        }
        long errorAnswerCount = quizAnswers.stream().filter(quizAnswer -> quizAnswer.getType()==0).count();
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("allRight",errorAnswerCount==0);
        return OutDTO.ok(resultMap);
    }



}
