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

import cn.com.qmth.examcloud.api.commons.security.bean.User;
import cn.com.qmth.examcloud.core.questions.base.CommonUtils;
import cn.com.qmth.examcloud.core.questions.base.enums.ExamFileType;
import cn.com.qmth.examcloud.core.questions.base.enums.ExportType;
import cn.com.qmth.examcloud.core.questions.base.question.enums.QuesStructType;
import cn.com.qmth.examcloud.core.questions.base.word.DocxProcessUtil;
import cn.com.qmth.examcloud.core.questions.dao.entity.ExamPaper;
import cn.com.qmth.examcloud.core.questions.dao.entity.ExportStructure;
import cn.com.qmth.examcloud.core.questions.dao.entity.ExtractConfig;
import cn.com.qmth.examcloud.core.questions.dao.entity.QuestionTypeNum;
import cn.com.qmth.examcloud.core.questions.service.bean.dto.PaperDetailExp;
import cn.com.qmth.examcloud.core.questions.service.bean.dto.PaperExp;
import org.apache.commons.collections.CollectionUtils;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * @author weiwenhai
 * @date 2018年6月2日 上午11:29:49
 * @company QMTH
 * @description 重庆大学导出、上传文件service
 */
@Service("cqdxExportPaperService")
public class CqdxExportPaperService extends ExportPaperAbstractService {

    @Override
    public void downloadPaper(String paperId, String zipFileName, String examType) throws Exception {
        PaperExp paperExp = super.initPaperExp(paperId);
        if (paperExp != null) {
            String paperfileName = paperExp.getName() + "_" + paperExp.getCourseNo() + "_" + ExamFileType.PAPER.getName() + DOCX_SUFFIX;
            File file = new File(TEMP_FILE_EXP + File.separator + zipFileName + File.separator + paperfileName);
            if (examType.equals("offLine")) {
                WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
                paperExp.setExamRemarkWord(DocxProcessUtil.html2Docx(wordMLPackage, CommonUtils.formatHtml(paperExp.getExamRemark())));
                DocxProcessUtil.exportWordNew(paperExp, file, CQDX_TMPLATE_PAPER);
            } else {
                DocxProcessUtil.exportWordNew(paperExp, file, CQDX_TMPLATE_PAPER);
            }
            DocxProcessUtil.processImage(zipFileName + File.separator + paperfileName, getPkgList(paperId));
            //下载音频
            super.downloadAudio(paperExp, zipFileName);
        }
    }

    @Override
    public void downloadPaperAnswer(String paperId, String zipFileName) throws Exception {
        PaperExp paperExp = initPaperExp(paperId);
        if (paperExp != null) {
            String answerFileName = paperExp.getName() + "_" + paperExp.getCourseNo() + "_" + ExamFileType.ANSWER.getName() + DOCX_SUFFIX;
            File file = new File(TEMP_FILE_EXP + File.separator + zipFileName + File.separator + answerFileName);
            DocxProcessUtil.exportWordNew(paperExp, file, CQDX_TMPLATE_ANSWER);
            DocxProcessUtil.processImage(zipFileName + File.separator + answerFileName, getPkgList(paperId));
        }
    }

    /**
     * 设置大题标题
     */
    @Override
    public void setExportQuestionTitle(List<PaperDetailExp> details, boolean isWord) {
        if (CollectionUtils.isEmpty(details)) {
            return;
        }

        final String style = "<em class=\"e_num\">%s</em>";

        for (PaperDetailExp detail : details) {
            String perQuesScore = checkPaperDetailUnitScore(detail);
            if (perQuesScore != null) {
                perQuesScore = CommonUtils.clearZeroPoint(perQuesScore);
                if (!isWord) {
                    perQuesScore = String.format(style, perQuesScore);
                }
                perQuesScore = String.format("每小题%s分，", perQuesScore);
            } else {
                perQuesScore = "";//每题分数不一致则不注明
            }

            QuesStructType type = detail.getPaperDetailUnits().get(0).getQuestionType();
            String detailScore = CommonUtils.formatValue(detail.getScore());
            String unitCount = String.valueOf(detail.getUnitCount());

            if (!isWord) {
                detailScore = String.format(style, detailScore);
                unitCount = String.format(style, unitCount);
            }
            String title = String.format("（本大题共%s小题，%s共%s分）", unitCount, perQuesScore, detailScore);

            if (type == QuesStructType.SINGLE_ANSWER_QUESTION) {
                detail.setTitleDetail("在每小题列出的备选项中只有一个符合题目要求的，请将其选出并将“答题卡”的相应代码涂黑，错涂、多涂或未涂均无分");
            } else if (type == QuesStructType.MULTIPLE_ANSWER_QUESTION) {
                detail.setTitleDetail("在每小题列出的备选项中至少有两个符合题目要求，请将符合项选出并将“答题卡”的相应代码涂黑");
            } else if (type == QuesStructType.BOOL_ANSWER_QUESTION) {
                detail.setTitleDetail("正确的填涂√、错误填涂×。错涂、多涂或未涂均无分");
            }

            detail.setTitle(title);
        }
    }

    @Override
    public void uploadFile(ExtractConfig extractConfig, String paperId, ExportStructure exportStructure, User accessUser, ExamPaper examPaper) throws Exception {
        PaperExp paperExp = initPaperExp(paperId);
        if (paperExp != null) {
            String currNum = CommonUtils.getCurNum();
            //删除原有试卷文件
        	/*ExamFile examFile = new ExamFile();
        	examFile.setExamId(extractConfig.getExamId()+"");
        	examFile.setCourseId(extractConfig.getCourseCode());
        	examFile.setOrgId(extractConfig.getOrgId());
        	examFileService.deleteExamFile(examFile);*/
            //没有试卷结构导出设置
            if (exportStructure == null) {
                //上传试卷
                uploadPaperOrAnswerFile(paperExp, extractConfig, accessUser, currNum, CQDX_TMPLATE_PAPER, ExamFileType.PAPER, examPaper);
                //上传答案
                uploadPaperOrAnswerFile(paperExp, extractConfig, accessUser, currNum, CQDX_TMPLATE_ANSWER, ExamFileType.ANSWER, examPaper);
            } else if (exportStructure != null && exportStructure.getExportType() == ExportType.NORMAL) {
                List<QuestionTypeNum> questionTypeNums = exportStructure.getQuestionTypeNums();
                //检查试卷中客观题的数量是否大于试卷导出设置中的设置的数量
                checkObjectiveDetailsNum(paperExp, questionTypeNums);
                //上传试卷
                uploadPaperOrAnswerFile(paperExp, extractConfig, accessUser, currNum, CQDX_TMPLATE_PAPER, ExamFileType.PAPER, examPaper);
                //上传答案
                uploadPaperOrAnswerFile(paperExp, extractConfig, accessUser, currNum, CQDX_TMPLATE_ANSWER, ExamFileType.ANSWER, examPaper);
                //上传试卷结构   不能在上传试卷和答案之前
                uploadPaperStructure(paperExp, extractConfig, accessUser, currNum, questionTypeNums, examPaper);
            } else if (exportStructure != null && exportStructure.getExportType() == ExportType.ONLINE) {
                //上传机考JSON文件
                uploadComputerTestFile(extractConfig, accessUser, examPaper);
            }
        }
    }


}
