package com.rongwei.trainingcommon.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rongwei.rwcommon.base.BaseDo;
import com.rongwei.rwcommon.base.R;
import com.rongwei.training.domain.ExamPaperDo;
import com.rongwei.training.domain.PaperSubjectAssignDo;
import com.rongwei.training.domain.SubjectDo;
import com.rongwei.trainingcommon.sys.dao.*;
import com.rongwei.trainingcommon.sys.service.SubjectService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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


@Service("subjectService")
public class SubjectServiceImpl extends ServiceImpl<SubjectDao, SubjectDo> implements SubjectService {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private PlanPaperDao planPaperDao;
    @Autowired
    private ExamPaperDao examPaperDao;
    @Autowired
    private PaperSubjectAssignDao paperSubjectAssignDao;
    @Autowired
    private PaperSubjectAutoDao paperSubjectAutoDao;
    @Autowired
    private SubjectService subjectService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R checkInfo(List<String> subjectIds) {
        /*******************************根据考题ID获取 分别获取作为固定考题和随机考题的试卷信息**************************/
        log.info("开始获取固定考题对应的试卷信息");
        List<PaperSubjectAssignDo> subjectAssignList = paperSubjectAssignDao.selectList(new QueryWrapper<PaperSubjectAssignDo>()
                .lambda().in(PaperSubjectAssignDo::getSubjectid, subjectIds).eq(BaseDo::getDeleted, "0"));
        log.info("获取固定考题对应的试卷信息结束,试卷信息 :{}", subjectAssignList);
        // 筛选出不在固定考题表中的 题目ID 删除
        List<String> toDeleteSubjectId = subjectIds.stream()
                .filter(subjectId -> !subjectAssignList.stream()
                        .map(PaperSubjectAssignDo::getSubjectid)
                        .collect(Collectors.toList())
                        .contains(subjectId)).collect(Collectors.toList());
        // 获取不到信息直接删除
        if (!toDeleteSubjectId.isEmpty()) {
            subjectService.update(new LambdaUpdateWrapper<SubjectDo>().in(SubjectDo::getId, toDeleteSubjectId).set(BaseDo::getDeleted, "1"));
            log.info("已删除考题: {}", toDeleteSubjectId);
        }
        // xiahan TODO: 2020/11/23 随机考题的信息无法获取
        // 根据考题ID+考题名称 进行分组
        Map<String, Set<String>> mapInfo = subjectAssignList.stream()
                .collect(Collectors.groupingBy(subjectAssignDo -> subjectAssignDo.getSubjectid() + ";" + subjectAssignDo.getSubjectname(),
                        Collectors.mapping(PaperSubjectAssignDo::getPaperid, Collectors.toSet())));
        // 返回的信息
        Map<String, List<String>> msgInfoMap = new HashMap<>();
        mapInfo.forEach((subjectId, paperIds) -> {
            // 获取试卷信息
            List<ExamPaperDo> examPaperDos = examPaperDao.selectList(new QueryWrapper<ExamPaperDo>().lambda()
                    .in(ExamPaperDo::getId, paperIds).eq(BaseDo::getDeleted, "0"));
            if (examPaperDos.isEmpty()) {
                subjectService.update(new LambdaUpdateWrapper<SubjectDo>().eq(SubjectDo::getId, subjectId.split(";")[0]).set(BaseDo::getDeleted, "1"));
            } else {
                msgInfoMap.put(subjectId.split(";")[1], examPaperDos.stream()
                        .map(ExamPaperDo::getExaminationname)
                        .distinct()
                        .collect(Collectors.toList()));
            }
        });
        if (msgInfoMap.isEmpty()) {
            return R.ok();
        }
        StringBuffer msg = new StringBuffer("所选考题: (");
        msg.append(String.join(",", msgInfoMap.keySet())).append(")");
        msg.append("已被试卷: (").append(msgInfoMap.values().stream().flatMap(Collection::stream).distinct().collect(Collectors.joining(",")));
        msg.append(")").append("使用,不可删除.");
        return R.errorWithMsg(msg.toString());
    }
}
