package com.qmth.qrzk.repository.user.service.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.qmth.qrzk.dao.IQuestionOptionDao;
import com.qmth.qrzk.repository.common.base.BaseDao;
import com.qmth.qrzk.repository.user.model.QuestionOption;
import com.qmth.qrzk.repository.user.service.IQuestionOptionService;
import com.qmth.qrzk.repository.utils.Consts;
import com.qmth.qrzk.repository.utils.General;
import com.qmth.qrzk.repository.utils.docx.HtmlCreator;

@Service("questionOptionServiceImpl")
public class QuestionOptionServiceImpl implements IQuestionOptionService {
	
	@Autowired private BaseDao dao;
	
	private static Logger log = Logger.getLogger(QuestionOptionServiceImpl.class);

	@Autowired
	@Qualifier("questionOptionDaoImpl")
	private IQuestionOptionDao questionOptionDao;
	
	@Override
	public int saveQuestionOption(QuestionOption qo) {
		return questionOptionDao.insertOption(qo);
	}

	@Override
	public List<QuestionOption> findByQuestionId(int question_id) {
		List<QuestionOption> options = questionOptionDao.selectByQuestionId(question_id);
		if(options != null && options.size() > 0){
			for(QuestionOption qo:options){
				if(qo.getContentWord() != null && qo.getContentWord().length > 0 && General.isEmpty(qo.getContent())){
					try{
						qo.setContent(HtmlCreator.covertToHtml(qo.getContentWord()).toString());
					}catch(Exception e){
						log.warn("试题[id=" + question_id + "]的选项[id=" + qo.getId() + "]word数据无法转换成html代码，原因：" + e.getMessage(), e);
						qo.setContent("<span style='color:red'>" + String.format(Consts.ERR_QUS_OPT_MSG, question_id + "") + "</span>");
					}
				}
				if(qo.getContent() == null || qo.getContent().length() == 0){
					qo.setContent(qo.getSummary());
				}
			}
		}
		return options;
	}

	@Override
	public int deleteOption(int id) {
		return questionOptionDao.deleteById(id);
	}

	@Override
	public int update(QuestionOption qo) {
		return dao.update("updateOption", qo);
//		return questionOptionDao.updateOption(qo);
	}

	@Override
	public int deleteOptionsByQuesId(int quesId) {
		return dao.delete("deleteOptionsByQuesId", quesId);
	}

}
