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.QuesRepo;
import cn.com.qmth.examcloud.core.questions.dao.QuestionAudioRepo;
import cn.com.qmth.examcloud.core.questions.dao.entity.QuesOption;
import cn.com.qmth.examcloud.core.questions.dao.entity.Question;
import cn.com.qmth.examcloud.core.questions.dao.entity.QuestionAudio;
import cn.com.qmth.examcloud.core.questions.service.QuestionAudioService;
import cn.com.qmth.examcloud.core.questions.service.config.UpYunProperty;
import main.java.com.UpYun;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author chenken
 * @date 2017年8月1日 上午11:27:33
 * @company QMTH
 * @description QuestionRadioServiceImpl.java
 */
@Service("questionAudioService")
public class QuestionAudioServiceImpl implements QuestionAudioService {

    @Autowired
    private QuestionAudioRepo questionAudioRepo;

    @Autowired
    private QuesRepo quesRepo;

    @Autowired
    private UpYunProperty upYunProperty;

    @Override
    public void saveQuestionAudio(QuestionAudio questionAudio, User user) {
        QuestionAudio questionAudio2 = findByQuestionIdAndFileName(questionAudio.getQuestionId(), questionAudio.getFileName());
        if (questionAudio2 != null) {
            questionAudio.setId(questionAudio2.getId());
            UpYun upYun = new UpYun(upYunProperty.getBucketName(), upYunProperty.getUserName(), upYunProperty.getPassword());
            upYun.deleteFile(questionAudio2.getFileUrl());
            questionAudioRepo.delete(questionAudio2);
        }
        questionAudio.setCreateTime(new Date());
        questionAudio.setCreateUser(user.getDisplayName());
        questionAudioRepo.save(questionAudio);
    }

    @Override
    public List<QuestionAudio> findQuestionAudiosByQuestionId(String questionId) {
        Assert.hasLength(questionId, "questionId不能为空");
        return questionAudioRepo.findByQuestionId(questionId);
    }

    @Override
    public QuestionAudio findByQuestionIdAndFileName(String questionId, String fileName) {
        if (StringUtils.isBlank(questionId) || StringUtils.isBlank(fileName)) {
            return null;
        }
        return questionAudioRepo.findByQuestionIdAndFileName(questionId, fileName);
    }

    @Override
    public void deleteAudioNotInQuestion(Question question) {
        if (question.getHasAudio() != null && question.getHasAudio()) {
            List<QuestionAudio> questionAudios = questionAudioRepo.findByQuestionId(question.getId());
            StringBuffer buffer = new StringBuffer();
            buffer.append(question.getQuesBody());
            if (question.getQuesOptions() != null && question.getQuesOptions().size() > 0) {
                for (QuesOption option : question.getQuesOptions()) {
                    buffer.append(option.getOptionBody());
                }
            }
            String questionBodyAndOptionStr = buffer.toString();
            Iterator<QuestionAudio> audioIterator = questionAudios.iterator();
            while (audioIterator.hasNext()) {
                QuestionAudio audio = audioIterator.next();
                if (!questionBodyAndOptionStr.contains(audio.getFileName())) {
                    UpYun upYun = new UpYun(upYunProperty.getBucketName(), upYunProperty.getUserName(), upYunProperty.getPassword());
                    upYun.deleteFile(audio.getFileUrl());
                    questionAudioRepo.delete(audio);
                }
            }
        }
    }

    @Override
    public QuestionAudio findAudioById(String id) {
        if (StringUtils.isNotBlank(id)) {
            return Model.of(questionAudioRepo.findById(id));
        }
        return null;
    }

    @Override
    public void sortAudio(Question question) {
        if (question.getHasAudio() != null && question.getHasAudio()) {
            //音频顺序改变后，更新bodyHtml
            String newQusBody = getFileNames(question.getQuesBody(), question);
            question.setQuesBody(newQusBody);
            //跟新选项中的optionsHtml
            if (question.getQuesOptions() != null && question.getQuesOptions().size() > 0) {
                for (QuesOption option : question.getQuesOptions()) {
                    String newOptionBody = getFileNames(option.getOptionBody(), question);
                    option.setOptionBody(newOptionBody);
                }
            }
        }
    }

    private String getFileNames(String str, Question question) {
        Map<String, String> map = new LinkedHashMap<String, String>();
        Pattern p = Pattern.compile("<a\\s+[^<>]*\\s+name=\"([^<>\"]*)\"[^<>]*>");
        Matcher m = p.matcher(str);
        int i = 1;
        int y = 1;
        while (m.find()) {
            String name = m.group(1);
            StringBuffer buffer = new StringBuffer();
            if (name.substring(0, name.indexOf("_") + 1).contains("2")) {
                buffer.append(name.substring(0, name.lastIndexOf("_") + 1));
                buffer.append(i);
                buffer.append("@temp");
                buffer.append(name.substring(name.lastIndexOf(".")));
                map.put(name, buffer.toString());
                i++;
            } else {
                buffer.append(name.substring(0, name.lastIndexOf("_") + 1));
                buffer.append(y);
                buffer.append("@temp");
                buffer.append(name.substring(name.lastIndexOf(".")));
                map.put(name, buffer.toString());
                y++;
            }
        }
        //循环替换
        for (String key : map.keySet()) {
            str = str.replace(key, map.get(key));
        }
        //替换并更新数据
        for (String key : map.keySet()) {
            String fileName = key;
            String value = map.get(key).replace("@temp", "");
            str = str.replace(map.get(key), value);
            QuestionAudio questionAudio = questionAudioRepo.findByQuestionIdAndFileName(question.getId(), fileName);
            questionAudio.setFileName(value);
            questionAudioRepo.save(questionAudio);
        }
        return str;
    }

    @Override
    public void deleteAudio(List<Question> questions) {
        //筛选有音频的试题
        List<String> ids = new ArrayList<String>();
        for (Question question : questions) {
            if (question.getHasAudio() != null && question.getHasAudio()) {
                ids.add(question.getId());
            }
        }
        List<QuestionAudio> questionAudios = questionAudioRepo.findByQuestionIdIn(ids);
        Iterator<QuestionAudio> audioIterator = questionAudios.iterator();
        while (audioIterator.hasNext()) {
            QuestionAudio audio = audioIterator.next();
            UpYun upYun = new UpYun(upYunProperty.getBucketName(), upYunProperty.getUserName(), upYunProperty.getPassword());
            upYun.deleteFile(audio.getFileUrl());
        }
        questionAudioRepo.deleteAll(questionAudios);
    }

}

