package cn.com.qmth.examcloud.core.questions.starter;

import cn.com.qmth.examcloud.core.questions.base.core.enums.CourseLevel;

import com.google.gson.Gson;

import cn.com.qmth.examcloud.core.questions.base.question.enums.QuesStructType;
import cn.com.qmth.examcloud.core.questions.dao.*;
import cn.com.qmth.examcloud.core.questions.dao.entity.*;
import cn.com.qmth.examcloud.core.questions.service.ImportPaperService;
import cn.com.qmth.examcloud.core.questions.service.PaperDetailUnitService;
import cn.com.qmth.examcloud.core.questions.service.impl.CourseService;
//import cn.com.qmth.examcloud.core.questions.base.GridFSUtil;
import cn.com.qmth.examcloud.core.questions.base.enums.ExtractPolicy;
import cn.com.qmth.examcloud.core.questions.base.enums.PaperType;
import cn.com.qmth.examcloud.core.questions.base.word.DocxProcessUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;

import org.apache.log4j.Logger;
import org.docx4j.Docx4J;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.Map;

/**
 * Unit test for simple App.
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTest {
    protected final Logger log = Logger.getLogger(ApplicationTest.class);

    @Autowired
    QuesRepo quesRepo;

    @Autowired
    PaperRepo paperRepo;

    @Autowired
    PaperDetailRepo paperDetailRepo;

    @Autowired
    PaperDetailUnitRepo paperDetailUnitRepo;

//    @Autowired
//    GridFSUtil gridFSUtil;

    @Autowired
    ExamPaperRepo examPaperRepo;

    @Autowired
    ExtractConfigRepo extractConfigRepo;

    @Autowired
    ImportPaperService importPaperService;

//    @Autowired
//    ExportPaperService exportPaperService;

    @Autowired
    Gson gson;

    @Autowired
    PaperDetailUnitService paperDetailUnitService;

    @Autowired
    CourseService courseService;

    @Test
    public void testGridFs() throws FileNotFoundException {
        String fileName = "testXml";
        String filePath = "/Users/songyue/Desktop/" + fileName + ".xml";
        FileInputStream fileInputStream = new FileInputStream(new File(filePath));
//        gridFSUtil.save(fileInputStream,fileName);
//        gridFSUtil.getByFileName(fileName);
    }

    @Test
    public void testQuestion() {
        Question question = new Question();
        question.setQuesBody("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /><style>.wordTd_disabled{border:solid windowtext 1pt;padding:0cm 5.4pt 0cm 5.4pt;} p{white-space:sWrap;word-wrap:break-word;} span{white-space:sWrap;word-wrap:break-word;}</style></head><body><p style=\"text-align:both;\"><span style=\"color:#000000;font-size:10pt;font-family:Times New Roman;\"><span style=\"font-style:normal;\"><span style=\"font-weight:normal;\">\n" +
                "材料在外力作用下发生形变(套题题干)。\n" +
                "</span></span></span></p></body></html>");
        QuestionType questionType = new QuestionType();
        questionType.setName("阅读理解");
        questionType.setQuesType(QuesStructType.NESTED_ANSWER_QUESTION);
        question.setQuestionType(QuesStructType.NESTED_ANSWER_QUESTION);
        List<Question> subquestionList = new ArrayList<Question>();

        for (int i = 0; i < 10; i++) {
            Question subquestion = new Question();
            subquestion.setQuesBody("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /><style>.wordTd_disabled{border:solid windowtext 1pt;padding:0cm 5.4pt 0cm 5.4pt;} p{white-space:sWrap;word-wrap:break-word;} span{white-space:sWrap;word-wrap:break-word;}</style></head><body><p style=\"text-align:both;\"><span style=\"color:#000000;font-size:10pt;font-family:Times New Roman;\"><span style=\"font-style:normal;\"><span style=\"font-weight:normal;\">\n" +
                    "材料在外力作用下发生形变，当外力撤消后能恢复原来大小和形状的性质称为(小题题干" + i + ")。\n" +
                    "</span></span></span></p></body></html>");
            subquestion.setQuesAnswer("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /><style>.wordTd_disabled{border:solid windowtext 1pt;padding:0cm 5.4pt 0cm 5.4pt;} p{white-space:sWrap;word-wrap:break-word;} span{white-space:sWrap;word-wrap:break-word;}</style></head><body><p style=\"text-align:both;\"><span style=\"color:#000000;font-size:10pt;font-family:Times New Roman;\"><span style=\"font-style:normal;\"><span style=\"font-weight:normal;\">\n" +
                    "B\n" +
                    "</span></span></span></p><p style=\"text-align:both;\"><br/></p></body></html>");
            QuesOption quesOption1 = new QuesOption();
            quesOption1.setOptionBody("A.12312312313");
            QuesOption quesOption2 = new QuesOption();
            quesOption2.setOptionBody("B.34534534545");
            List<QuesOption> quesOptionList = new ArrayList<QuesOption>();
            quesOptionList.add(quesOption1);
            quesOptionList.add(quesOption2);
            subquestion.setQuesOptions(quesOptionList);
            QuestionType questionType1 = new QuestionType();
            questionType1.setQuesType(QuesStructType.SINGLE_ANSWER_QUESTION);
            subquestion.setQuestionType(QuesStructType.SINGLE_ANSWER_QUESTION);
            subquestionList.add(subquestion);
        }
        question.setSubQuestions(subquestionList);
        quesRepo.save(question);
    }

    @Test
    public void testPaper() {
        paperRepo.deleteAll();
        paperDetailRepo.deleteAll();
        paperDetailUnitRepo.deleteAll();

        Paper paper = new Paper();
        paper.setName("测试试卷");
        paper.setPaperDetailCount(1);
        paper.setTitle("测试试卷");
        PaperDetail paperDetail = new PaperDetail();
        paperDetail.setName("选择题");
        paperDetail.setScore((double) 20);
        paperDetail.setNumber(1);
        paperDetail.setPaper(paper);
        QuestionType questionType1 = new QuestionType();
        questionType1.setName("单项选择题");
        questionType1.setQuesType(QuesStructType.SINGLE_ANSWER_QUESTION);
        paperDetail.setUnitCount(3);

        paperRepo.save(paper);
        paperDetailRepo.save(paperDetail);


        List<Question> questionList = quesRepo.findAll();
        int i = 0;
        for (Question ques : questionList) {
            PaperDetailUnit paperDetailUnit = new PaperDetailUnit();
            paperDetailUnit.setQuestionType(ques.getQuestionType());
            paperDetailUnit.setNumber(i);
            paperDetailUnit.setPaper(paper);
            paperDetailUnit.setPaperDetail(paperDetail);
            paperDetailUnit.setScore((double) 10);
            paperDetailUnit.setQuestion(ques);
            i++;
            paperDetailUnitRepo.save(paperDetailUnit);
        }
    }

    @Test
    public void testExtract() {
        extractConfigRepo.deleteAll();
        examPaperRepo.deleteAll();
        ExamPaper examPaper = new ExamPaper();
        examPaper.setExamId((long) 1);
        examPaper.setCourseCode("1");
        examPaper.setExtractCount(1);
        examPaper.setGroupCode("1");
//        examPaper.setPaperId("58b3e0b06def240e05b0c0e1");
        examPaperRepo.save(examPaper);

        ExtractConfig extractConfig = new ExtractConfig();
        extractConfig.setExamId((long) 1);
        extractConfig.setCourseCode("1");
        extractConfig.setPolicy(ExtractPolicy.RANDOM_POLICY);
        extractConfigRepo.save(extractConfig);
    }

    @Test
    public void testImport() {
        paperRepo.deleteAll();
        paperDetailRepo.deleteAll();
        quesRepo.deleteAll();
        paperDetailUnitRepo.deleteAll();
//        String inputFilePath = "/Users/songyue/docxImport/ceshi2.docx";
//        try {
//            File inputFile = new File(inputFilePath);
//            FileInputStream inputStream = new FileInputStream(inputFile);
//            System.out.println(inputFilePath);
//            long startTime = System.currentTimeMillis();    //获取开始时间
//
//            String errorInfo = importPaperService.ImportPaper("",inputFile);
//            System.out.println("errorInfo:"+errorInfo);
//
//            long endTime = System.currentTimeMillis();    //获取结束时间
//
//            System.out.println("程序运行时间：" + (endTime - startTime)/1000 + "s");    //输出程序运行时间
//
//
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }


    }

//    @Test
//    public void testExport()throws Exception{
//        long startTime = System.currentTimeMillis();    //获取开始时间
//        exportPaperService.exportPaper("590ae38edd8e85f0bab928c2");
//        long endTime = System.currentTimeMillis();    //获取结束时间
//        System.out.println("程序运行时间：" + (endTime - startTime)/1000 + "s");    //输出程序运行时间
//    }

    @SuppressWarnings({"unused", "resource"})
    @Test
    public void testImport1() {
        String inputFilePath = "/Users/songyue/docxImport/ceshi2.docx";
        String outFilePath = "/Users/songyue/docxImport/ceshi11111.docx";
        try {
            File inputFile = new File(inputFilePath);
            FileInputStream inputStream = new FileInputStream(inputFile);
            System.out.println(inputFilePath);
            WordprocessingMLPackage wordMLPackage = Docx4J.load(inputFile);
            DocxProcessUtil.initPkgImage(wordMLPackage);
            Docx4J.save(wordMLPackage, new FileOutputStream(outFilePath));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testCourse() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("courseNo", "03013750");
        params.put("courseName", "专升本《合同法》");
//        List<Paper> papers = paperRepo.findByParams(params);
        Page<Paper> papers = paperRepo.findByPaperType(PaperType.IMPORT, new PageRequest(0, 10));
        System.out.println(papers.getTotalElements());
//        System.out.println(gson.toJson(papers));
    }

    @Test
    public void testCourse1() {
        List<Question> questions = quesRepo.findAll();
        List<Question> saveQues = new ArrayList<>();
        for (Question question : questions) {
            //Course course = courseRepo.findFirstByCodeAndOrgId(question.getCourseNo(),question.getOrgId());
            Course course = courseService.getCourse(Long.valueOf(question.getOrgId()), question.getCourseNo());
            if (course != null) {
                question.setCourseLevel(course.getLevel());
            } else {
                question.setCourseLevel(CourseLevel.ALL.name());
            }
            saveQues.add(question);
        }
        quesRepo.saveAll(saveQues);
    }

    @Test
    public void testCourse2() {
        List<Question> questions = quesRepo.findAll();
        List<Question> saveQues = new ArrayList<>();
        for (Question question : questions) {
            //Course course = courseRepo.findFirstByCodeAndOrgId(question.getCourseNo(),question.getOrgId());
            Course course = courseService.getCourse(Long.valueOf(question.getOrgId()), question.getCourseNo());
            question.setCourse(course);
            saveQues.add(question);
        }
        quesRepo.saveAll(saveQues);
    }

    @Test
    public void testCourse3() {
        List<Paper> papers = paperRepo.findAll();
        List<Paper> savePaper = new ArrayList<>();
        for (Paper paper : papers) {
            //Course course = courseRepo.findFirstByCodeAndOrgId(paper.getCourseNo(),paper.getOrgId());
            Course course = courseService.getCourse(Long.valueOf(paper.getOrgId()), paper.getCourseNo());
            paper.setCourse(course);
            savePaper.add(paper);
        }
        paperRepo.saveAll(savePaper);
    }

    @Test
    public void testCourse7() {
        List<Course> courses = new ArrayList<Course>();
        for (Course course : courses) {
            if (course != null) {
                if (course.getEnable().equals("1")) {
                    course.setEnable("true");
                }
                if (course.getEnable().equals("0")) {
                    course.setEnable("false");
                }
            }
        }
        //courseRepo.save(courses);
    }

    @Test
    public void testCourse6() {
        List<ExtractConfig> configs = extractConfigRepo.findAll();
        for (ExtractConfig config : configs) {
            //Course course = courseRepo.findFirstByCodeAndOrgId(config.getCourseCode(),config.getOrgId());
            Course course = courseService.getCourse(Long.valueOf(config.getOrgId()), config.getCourseCode());
            config.setCourse(course);
        }
        extractConfigRepo.saveAll(configs);
    }

    @Test
    public void testCourse5() {
        List<Question> questions = quesRepo.findAll();
        List<Paper> papers = paperRepo.findAll();
        for (Question question : questions) {
            Course course = question.getCourse();
            if (course != null) {
                if (course.getEnable().equals("1")) {
                    course.setEnable("true");
                }
                if (course.getEnable().equals("0")) {
                    course.setEnable("false");
                }
            }
        }
        for (Paper paper : papers) {
            Course course = paper.getCourse();
            if (course != null) {
                if (course.getEnable().equals("1")) {
                    course.setEnable("true");
                }
                if (course.getEnable().equals("0")) {
                    course.setEnable("false");
                }
            }
        }
        quesRepo.saveAll(questions);
        paperRepo.saveAll(papers);
    }

    @SuppressWarnings("unused")
    @Test
    public void testCourse4() {
        //Course course = courseRepo.findFirstByCodeAndOrgId("010048","1");
        Course course = courseService.getCourse(Long.valueOf("010048"), "1");
    }

}
