package yangtz.cs.liu.wechat.controller.exam;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import yangtz.cs.liu.campus.controller.exam.ExamTasksController;
import yangtz.cs.liu.campus.domain.exam.ExamDetail;
import yangtz.cs.liu.campus.domain.exam.ExamMain;
import yangtz.cs.liu.campus.domain.exam.ExamUserScore;
import yangtz.cs.liu.campus.domain.exam.ExamUserScoreDetail;
import yangtz.cs.liu.campus.service.exam.IExamDetailService;
import yangtz.cs.liu.campus.service.exam.IExamMainService;
import yangtz.cs.liu.campus.service.exam.IExamUserScoreDetailService;
import yangtz.cs.liu.campus.service.exam.IExamUserScoreDetailService;
import yangtz.cs.liu.campus.service.exam.IExamUserScoreService;
import yangtz.cs.liu.campus.vo.exam.ExamMainVo;
import yangtz.cs.liu.campus.vo.exam.ExamUserScoreDetailVo;
import yangtz.cs.liu.campus.vo.exam.ScoreVo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 公众号，问卷调查
 */
@RestController
@RequestMapping("/wx/exam")
public class WxExamController extends BaseController {

    @Autowired
    private IExamMainService examMainService;

    @Autowired
    private IExamDetailService examDetailService;

    @Autowired
    private IExamUserScoreService examUserScoreService;

    @Autowired
    private IExamUserScoreDetailService examUserScoreDetailService;

    private Logger log = LoggerFactory.getLogger(WxExamController.class);

    /**
     * 获取问卷调查活动
     * <p>
     * 区分已结束与进行中
     *
     * @param userId 用户id
     * @return
     */
    @GetMapping("/getExam/{userId}")
    public TableDataInfo list(@PathVariable("userId") Long userId, ExamMainVo examMainVo) {
        try {
            startPage();
            List<ExamMainVo> list = examMainService.getExam(userId, examMainVo);
            /** 判断是否已经答题过 */
            list.stream().forEach(o -> {
                LambdaQueryWrapper<ExamUserScore> lqw = new LambdaQueryWrapper<>();
                lqw
                        .eq(ExamUserScore::getUserId, userId)
                        .eq(ExamUserScore::getExamId, o.getId())
                ;
                int count = examUserScoreService.count();
                if (count > 0) {
                    o.setIsAnswer(true);
                }
            });
            return getDataTable(list);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new ServiceException("查询失败");
        }
    }

    /**
     * @author lyric
     * @date 2022/11/16 10:13
     * 问卷内容详情(当前问卷下有什么内容)
     */
    @GetMapping("/examDetail/{id}")
    public AjaxResult examDetail(@PathVariable Long id) {
        LambdaQueryWrapper<ExamDetail> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(ExamDetail::getExamId, id)
                .orderByAsc(ExamDetail::getSort)
        ;
        List<ExamDetail> list = examDetailService.list(lqw);
        return AjaxResult.success(list);
    }

    /**
     * 回答考试(题目回答集合)
     */
    @PostMapping("/join/{userId}")
    public AjaxResult join(@PathVariable("userId") Long userId, @RequestBody @Validated ScoreVo scorevo) {
        try {
            /** 新增入用户问卷主表 */
            ExamUserScore examUserScore = new ExamUserScore();
            BeanUtils.copyProperties(scorevo, examUserScore);
            examUserScore.setAnswerTime(new Date());
            examUserScore.setUserId(userId);
            examUserScoreService.save(examUserScore);

            /** 插入答题记录 */
            Long userScoreId = examUserScore.getId();
            List<ExamUserScoreDetail> list = scorevo.getExamUserScoreDetailList();
            list.forEach(o -> {
                o.setUserScoreId(userScoreId);
            });
            examUserScoreDetailService.saveBatch(list);
            return AjaxResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new ServiceException("参与失败");
        }
    }

    /**
     * 查看历史答题列表
     */
    @GetMapping("/historyList/{userId}/{examId}")
    public TableDataInfo historyList(@PathVariable("userId") Long userId, @PathVariable("examId") Long examId) {
        startPage();
        LambdaQueryWrapper<ExamUserScore> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ExamUserScore::getExamId, examId).eq(ExamUserScore::getUserId, userId);
        List<ExamUserScore> list = examUserScoreService.list(lqw);
        return getDataTable(list);
    }

    /**
     * 查看本次答题情况
     */
    @GetMapping("/answerDetail/{examId}/{userScoreId}")
    public AjaxResult answerDetail(@PathVariable("examId") Long examId, @PathVariable("userScoreId") Long userScoreId) {
        /** 考试试题 */
        LambdaQueryWrapper<ExamDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ExamDetail::getExamId, examId).orderByAsc(ExamDetail::getSort);
        List<ExamDetail> list = examDetailService.list(lqw);
        List<Long> detailIdList = list.stream().map(ExamDetail::getId).collect(Collectors.toList());

        /** 答题情况 */
        LambdaQueryWrapper<ExamUserScoreDetail> scoreDetailLqw = new LambdaQueryWrapper<>();
        scoreDetailLqw
                .eq(ExamUserScoreDetail::getUserScoreId, userScoreId)
                .in(ExamUserScoreDetail::getExamDetailId, detailIdList)
                .orderByAsc(ExamUserScoreDetail::getExamDetailSort)
        ;
        List<ExamUserScoreDetail> scoreDetailList = examUserScoreDetailService.list(scoreDetailLqw);

        /** 拼接返回 */
        List<ExamUserScoreDetailVo> resList = new ArrayList<>();
        list.stream().forEach(o1 -> {
            scoreDetailList.stream().filter(o2 -> o1.getId().equals(o2.getExamDetailId())).limit(1).forEach(o2 -> {
                ExamUserScoreDetailVo vo = new ExamUserScoreDetailVo();
                vo.setExamDetail(o1);
                vo.setExamUserScoreDetail(o2);
                resList.add(vo);
            });
        });

        return AjaxResult.success(resList);
    }
}
