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

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

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.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.support.filestorage.FileStorageUtil;

/**
 * @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 SysProperty sysProperty;

    @Override
    public void saveQuestionAudio(QuestionAudio questionAudio, User user) {
        QuestionAudio existQuestionAudio = this.findByQuestionIdAndFileName(questionAudio.getQuestionId(), questionAudio.getFileName());
        if (existQuestionAudio != null) {
            questionAudio.setId(existQuestionAudio.getId());

//            UpYun upYun = new UpYun(sysProperty.getBucketName(), sysProperty.getUserName(), sysProperty.getPassword());
//            upYun.deleteFile(existQuestionAudio.getFileUrl());
        	//通用存储
            FileStorageUtil.deleteFile(existQuestionAudio.getFileUrl());

            questionAudioRepo.delete(existQuestionAudio);
        }

        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;
        }

        List<QuestionAudio> audioList = questionAudioRepo.findByQuestionIdAndFileName(questionId, fileName);
        if (CollectionUtils.isNotEmpty(audioList)) {

            Collections.sort(audioList, (target1, target2) -> {
                if (target1.getCreateTime() == null || target2.getCreateTime() == null) {
                    return 0;
                }

                if (target1.getCreateTime().before(target2.getCreateTime())) {
                    return 1;
                }

                return -1;
            });

            //取最新的一个
            return audioList.get(0);
        }

        return null;
    }

    @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(sysProperty.getBucketName(), sysProperty.getUserName(), sysProperty.getPassword());
//                    upYun.deleteFile(audio.getFileUrl());
                	//通用存储
                    FileStorageUtil.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<>();
        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 = this.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(sysProperty.getBucketName(), sysProperty.getUserName(), sysProperty.getPassword());
//            upYun.deleteFile(audio.getFileUrl());
        	//通用存储
            FileStorageUtil.deleteFile(audio.getFileUrl());
        }
        questionAudioRepo.deleteAll(questionAudios);
    }
    
    @Override
    public void deleteAudioByQuestionId(List<String> questionIds) {
    	if(CollectionUtils.isEmpty(questionIds)) {
    		return;
    	}
        List<QuestionAudio> questionAudios = questionAudioRepo.findByQuestionIdIn(questionIds);
        Iterator<QuestionAudio> audioIterator = questionAudios.iterator();
        while (audioIterator.hasNext()) {
            QuestionAudio audio = audioIterator.next();
//            UpYun upYun = new UpYun(sysProperty.getBucketName(), sysProperty.getUserName(), sysProperty.getPassword());
//            upYun.deleteFile(audio.getFileUrl());
        	//通用存储
            FileStorageUtil.deleteFile(audio.getFileUrl());
        }
        questionAudioRepo.deleteAll(questionAudios);
    }

}

