package com.xhkjedu.sstudy.service.question;

import com.xhkjedu.sstudy.mapper.question.QuestionMapper;
import com.xhkjedu.sstudy.mapper.question.UserBasketMapper;
import com.xhkjedu.sstudy.model.question.TUserBasket;
import com.xhkjedu.utils.N_Utils;
import com.xhkjedu.sstudy.vo.question.QuestionVo;
import com.xhkjedu.sstudy.vo.question.UserBasketVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ywx
 * @classname UserBasketService
 * @description 
 * @date 2020/6/9 10:49
 **/
@Service
public class UserBasketService {
    @Resource
    private UserBasketMapper userBasketMapper;
    @Resource
    private QuestionMapper questionMapper;

    //添加
    public Integer save(TUserBasket model) {
        Integer ubid = userBasketMapper.getUbidByUserIdQuestionId(model.getUserid(),model.getQuestionid());
        if (N_Utils.isEmptyInteger(ubid)) {
            model.setCreatetime(N_Utils.getSecondTimestamp());
            userBasketMapper.insertUseGeneratedKeys(model);
            questionMapper.updateCount(model.getQuestionid());//更新组题次数
            ubid = model.getId();
        }
        return ubid;
    }

    //删除
    public Integer deleteById(Integer userid,String questionid) {
       // return userBasketMapper.deleteByPrimaryKey(ubid);
        return userBasketMapper.deleteByQuestioniduid(userid,questionid);
    }

    /**
     * 清空试题篮
     * @Param [userid, subjectid]
     * @Author ywx
     * @Date 2020/6/9 10:54
     * @return java.lang.Integer
     **/
    public Integer deleteBySubjectId(Integer userid, String subjectid) {
        return userBasketMapper.deleteBySubjectId(userid, subjectid);
    }

    //获取列表
    public List <UserBasketVo> findAll(Integer userid, String subjectid) {
        List<UserBasketVo> baskets = userBasketMapper.findAll(userid, subjectid);
        for (UserBasketVo b : baskets) {
            List<QuestionVo> questions = b.getQuestions();
            b.setPtnum(questions.size());
            Double scoretotal = questions.stream().collect(Collectors.summingDouble(QuestionVo::getScore));
            b.setPtscore(scoretotal);
        }
        return baskets;
    }

    /**
     * 删除题型下指定试题
     * @Param [userid, qtypeid]
     * @Author ywx
     * @Date 2020/6/9 11:06
     * @return java.lang.Integer
     **/
    public Integer deleteByTypeId(Integer userid, String qtypeid) {
        return userBasketMapper.deleteByTypeId(userid, qtypeid);
    }
}
