package com.ruoyi.web.controller.manager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.system.domain.qu.ElQu;
import com.ruoyi.system.domain.userbook.ElUserBook;
import com.ruoyi.system.service.ElQuService;
import com.ruoyi.system.service.ElUserBookService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * packageName com.ruoyi.web.controller.manager
 *
 * @author wangxy
 * @version JDK 8
 * @className UserBookManager
 * @date 2024/7/1
 * @description 错题本
 */
@Component
public class UserBookManager {


    @Resource
    private ElUserBookService userBookService;

    @Resource
    private ElQuService quService;


    public void addBook(String examId, String quId) {

         ElUserBook book = userBookService.lambdaQuery()
                 .eq(ElUserBook::getUserId, ShiroUtils.getUserId())
                 .eq(ElUserBook::getExamId, examId)
                 .eq(ElUserBook::getQuId, quId).one();
        // 问题
        ElQu qu = quService.getById(quId);
        if (Objects.isNull(book)) {
            book = new ElUserBook();
            book.setExamId(examId);
            book.setUserId(ShiroUtils.getUserId());
            book.setTitle(qu.getContent());
            book.setQuId(quId);
            book.setWrongCount(1);
            Integer maxSort = this.findMaxSort(examId,  ShiroUtils.getUserId());
            book.setSort(maxSort+1);
            userBookService.save(book);
        } else {
            book.setWrongCount(book.getWrongCount()+1);
            userBookService.updateById(book);
        }
    }

    /**
     * 查找最大的排序
     * @param userId
     * @return
     */
    private Integer findMaxSort(String examId, Long userId){
        QueryWrapper<ElUserBook> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(ElUserBook::getExamId, examId)
                .eq(ElUserBook::getUserId, userId);
        wrapper.last(" ORDER BY `sort` DESC");
        ElUserBook book = userBookService.getOne(wrapper, false);
        if(Objects.isNull(book)){
            return 0;
        }
        return book.getSort();
    }



}
