package com.ruoyi.web.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.ie.domain.Subject;
import com.ruoyi.ie.mapper.SubjectMapper;
import com.ruoyi.mxjb.domain.MxjbWrongBook;
import com.ruoyi.mxjb.mapper.MxjbWrongBookMapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class WrongBookService {
    private final SubjectMapper subjectMapper;
    private final MxjbWrongBookMapper wrongBookMapper;
    private final CacheService cacheService;

    public WrongBookService(SubjectMapper subjectMapper, MxjbWrongBookMapper wrongBookMapper, CacheService cacheService) {
        this.subjectMapper = subjectMapper;
        this.wrongBookMapper = wrongBookMapper;
        this.cacheService = cacheService;
    }

    public List<Subject> findSubject() {
        return subjectMapper.selectSubjectList(new Subject());
    }

    public List<MxjbWrongBook> findWrongQuestions(Long subjectId) {
        Map cond = Maps.newHashMap();
        cond.put("subjectId", subjectId);
        cond.put("creatorId", SecurityUtils.getUserId());
        List<MxjbWrongBook> wrongBookList = wrongBookMapper.findWrongQuestions(cond);
        wrongBookList.stream().forEach(t -> {
            setAnswerAttachemnts(t, t.getAnswers());
            t.setTypeId(cacheService.getQuestionType(t.getQtpye()));
        });
        return wrongBookList;
    }

    public List<MxjbWrongBook> findWrongExaminees(Long wrongId) {
        return wrongBookMapper.findWrongExaminees(wrongId);
    }

    public int deleteByQuestion(String customerCode, Long questionId) {
        MxjbWrongBook b = new MxjbWrongBook();
        b.setCustomerCode(customerCode);
        b.setQuestionId(questionId);
        return wrongBookMapper.deleteByQuestion(b);
    }

    public void setAnswerAttachemnts(MxjbWrongBook dto, String answer) {
        if (StringUtils.isNotBlank(answer)) {
            String[] answerArray = StringUtils.splitByWholeSeparatorPreserveAllTokens(answer, "$@");
            if (answerArray.length > 0) {
                dto.setAnswer(answerArray[0]);
                if (answerArray.length > 1) {
                    List<String> attacheList = Lists.newArrayList();
                    for (int i = 1; i < answerArray.length; i++) {
                        if (StringUtils.isNotBlank(answerArray[i]) && !"null".equals(answerArray[i])) {
                            attacheList.add(answerArray[i]);
                        }
                    }
                    dto.setAttachments(attacheList);
                }
            }
        }
    }
}
