package cn.com.qmth.examcloud.core.questions.service.impl;

import cn.com.qmth.examcloud.api.commons.security.bean.User;
import cn.com.qmth.examcloud.core.questions.base.Model;
import cn.com.qmth.examcloud.core.questions.dao.AudioTimeConfigRepo;
import cn.com.qmth.examcloud.core.questions.dao.PaperDetailUnitRepo;
import cn.com.qmth.examcloud.core.questions.dao.PaperRepo;
import cn.com.qmth.examcloud.core.questions.dao.entity.*;
import cn.com.qmth.examcloud.core.questions.service.AudioTimeConfigService;
import cn.com.qmth.examcloud.core.questions.service.ExtractConfigService;
import cn.com.qmth.examcloud.core.questions.service.QuesService;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.Map.Entry;

/**
 * @author chenken
 * @date 2017年8月10日 下午3:16:12
 * @company QMTH
 * @description 音频次数设置service
 */
@Service("audioTimeConfigService")
public class AudioTimeConfigServiceImpl implements AudioTimeConfigService {

    @Autowired
    private AudioTimeConfigRepo audioTimeConfigRepo;

    @Autowired
    private PaperRepo paperRepo;

    @Autowired
    private PaperDetailUnitRepo paperDetailUnitRepo;

    @Autowired
    private QuesService quesService;

    @Autowired
    private ExtractConfigService extractConfigService;

    @Override
    public void saveAudioTimeConfig(List<AudioTimeConfig> audioTimeConfigs, User user) {
        if (audioTimeConfigs != null && audioTimeConfigs.size() > 0) {
            this.deleteByExamIdAndCourseCode(audioTimeConfigs.get(0).getExamId(), audioTimeConfigs.get(0).getCourseCode());
            for (AudioTimeConfig audioTimeConfig : audioTimeConfigs) {
                audioTimeConfig.setCreateDate(new Date());
                //audioTimeConfig.setCreateUser(user.getName());
                audioTimeConfig.setCreateUser(user.getDisplayName());
            }
            audioTimeConfigRepo.saveAll(audioTimeConfigs);
        }
    }

    @Override
    public List<AudioTimeConfig> findByAudioTimeConfig(AudioTimeConfig audioTimeConfig) {
        return audioTimeConfigRepo.findAll(Example.of(audioTimeConfig));
    }

    @Override
    public void deleteByExamIdAndCourseCode(String examId, String courseCode) {
        audioTimeConfigRepo.deleteByExamIdAndCourseCode(examId, courseCode);
    }

    @Override
    public List<AudioTimeConfig> findAudioTimeConfigList(List<AudioTimeConfig> audioTimeConfigModelList) {
        List<AudioTimeConfig> audioTimeConfigList = new ArrayList<>();
        for (AudioTimeConfig audioTimeConfig : audioTimeConfigModelList) {
            Paper paper = Model.of(paperRepo.findById(audioTimeConfig.getPaper().getId()));
            //根据试卷查询所有小题
            List<PaperDetailUnit> list = paperDetailUnitRepo.findByPaperOrderByNumber(paper);
            for (PaperDetailUnit paperDetailUnit : list) {
                if (paperDetailUnit.getQuestion().getHasAudio() != null
                        && paperDetailUnit.getQuestion().getHasAudio()) {
                    quesService.formatQues(paperDetailUnit.getQuestion());
                    audioTimeConfigList.add(new AudioTimeConfig(audioTimeConfig.getExamId(),
                            audioTimeConfig.getExamName(),
                            audioTimeConfig.getGroupCode(),
                            audioTimeConfig.getCourseCode(),
                            paperDetailUnit));
                }
            }
        }
        return audioTimeConfigList;
    }

    @Override
    public void addAudioTimeConfig(AudioTimeConfig audioTimeConfig) {
        audioTimeConfig.setCreateDate(new Date());
        audioTimeConfigRepo.save(audioTimeConfig);
    }

    @Override
    public List<AudioTimeConfig> findAudioTimeConfigByExamId(String examId, String courseCode) {
        List<AudioTimeConfig> audioTimeConfigList = audioTimeConfigRepo.findByExamIdAndCourseCodeOrderByGroupCode(examId, courseCode);
        //添加后面成为音频题的设置
        addAudioTimeConfig(examId, courseCode, audioTimeConfigList);
        //删除已经不是音频题的设置
        deleteAudioTimeConfig(audioTimeConfigList);
        return audioTimeConfigList;
    }

    private void addAudioTimeConfig(String examId, String courseCode, List<AudioTimeConfig> audioTimeConfigList) {
        List<String> questionIds = new ArrayList<>();
        for (AudioTimeConfig audioTimeConfig : audioTimeConfigList) {
            questionIds.add(audioTimeConfig.getQuestionId());
        }
        //添加后面成为音频题的设置
        ExtractConfig extractConfig = extractConfigService.findConfig(new ExtractConfig(Long.valueOf(examId), courseCode));
        Map<String, String> paperIdMap = extractConfig.getFinishedPaperIdMap();
        if (paperIdMap != null && paperIdMap.size() > 0) {
            Set<Entry<String, String>> entrySet = paperIdMap.entrySet();
            Iterator<Entry<String, String>> iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Entry<String, String> entry = iterator.next();
                Paper paper = Model.of(paperRepo.findById(entry.getValue()));
                //根据试卷查询所有小题
                List<PaperDetailUnit> list = paperDetailUnitRepo.findByPaperOrderByNumber(paper);
                for (PaperDetailUnit paperDetailUnit : list) {
                    if (paperDetailUnit.getQuestion().getHasAudio() != null
                            && paperDetailUnit.getQuestion().getHasAudio()) {
                        if (questionIds.contains(paperDetailUnit.getQuestion().getId())) {
                            continue;
                        }
                        audioTimeConfigList.add(new AudioTimeConfig(examId, extractConfig.getExamName(), entry.getKey(), courseCode, paperDetailUnit));
                    }
                }
            }
        }
    }

    /**
     * 将题目已经不是音频题的对象从集合中删除，并将对象从数据库删除
     *
     * @param audioTimeConfigList
     */
    private void deleteAudioTimeConfig(List<AudioTimeConfig> audioTimeConfigList) {
        List<AudioTimeConfig> configs = new ArrayList<>();
        for (AudioTimeConfig audioTimeConfig : audioTimeConfigList) {
            Question question = audioTimeConfig.getPaperDetailUnit().getQuestion();
            if (question.getHasAudio() == null || !question.getHasAudio()) {
                configs.add(audioTimeConfig);
            }
            quesService.formatQues(audioTimeConfig.getPaperDetailUnit().getQuestion());
        }
        audioTimeConfigList.removeAll(configs);
        audioTimeConfigRepo.deleteAll(configs);
    }

    @Override
    public Map<String, String> findAudioTimeConfig(String examId, String courseCode, String groupCode, String paperDetailUnitId) {
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isNotBlank(examId)) {
            map.put("errMessage", "examId为空");
            return map;
        }
        if (StringUtils.isNotBlank(courseCode)) {
            map.put("errMessage", "courseCode为空");
            return map;
        }
        if (StringUtils.isNotBlank(groupCode)) {
            map.put("errMessage", "groupCode为空");
            return map;
        }
        if (StringUtils.isNotBlank(paperDetailUnitId)) {
            map.put("errMessage", "paperDetailUnitId为空");
            return map;
        }
        PaperDetailUnit paperDetailUnit = Model.of(paperDetailUnitRepo.findById(paperDetailUnitId));
        AudioTimeConfig audioTime = new AudioTimeConfig();
        audioTime.setCourseCode(courseCode);
        audioTime.setExamId(examId);
        audioTime.setGroupCode(groupCode);
        audioTime.setPaperDetailUnit(paperDetailUnit);
        AudioTimeConfig audioTimeConfig = Model.of(audioTimeConfigRepo.findOne(Example.of(audioTime)));
        if (audioTimeConfig == null) {
            map.put("errMessage", "音频次数未设置");
            return map;
        }
        Integer playTime = audioTimeConfig.getPlayTime();
        map.put("playTime", playTime.toString());
        return map;
    }

    @Override
    public List<AudioTimeConfig> findUpdateAudioTimeConfigList(List<AudioTimeConfig> audioTimeConfigModelList) {
        List<AudioTimeConfig> list = findAudioTimeConfigList(audioTimeConfigModelList);
        List<AudioTimeConfig> newList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (AudioTimeConfig audioTimeConfig : list) {
                List<AudioTimeConfig> oldAudioTimeConfig = audioTimeConfigRepo
                		.findByExamIdAndCourseCodeAndGroupCodeAndPaperDetailUnit(audioTimeConfig.getExamId()
                				, audioTimeConfig.getCourseCode(), audioTimeConfig.getGroupCode()
                				, audioTimeConfig.getPaperDetailUnit());
                if (!CollectionUtils.isEmpty(oldAudioTimeConfig)) {
                    newList.add(oldAudioTimeConfig.get(0));
                } else {
                    newList.add(audioTimeConfig);
                }
            }
            return newList;
        }
        return newList;
    }

}
