package com.ruoyi.system.utils.downloadpaper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.learn.domain.LearnQuestions;
import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class DownloadPaperUtils {

    public static byte[] download(String paperName, List<LearnQuestions> questions) throws Exception {
        boolean test = false;
        String url;
        // String url = "http://152.136.133.33:8808/paperdownload-0.0.1-SNAPSHOT/paperdownload/paperDownload/";
        if (test) {
            url = "http://47.98.207.100:8081/test/user/testPaperDownload"; // 测试用
        } else {
            url = "http://152.136.133.33:8808/paperdownload-0.0.1-SNAPSHOT/paperdownload/paperDownload/";
        }
        // String postData =
        // IOUtils.toString(getClass().getClassLoader().getResourceAsStream("postdata.json"),
        // "utf-8");
        Map<String, String> param = new HashMap<String, String>();
        param.put("docType", "docx");
        param.put("answerType", "1");
        param.put("fontSize", "1");
        param.put("paperName", paperName);
        param.put("paperSizeType", "A4");
        // param.put("paperData", buildPaperData(paperName, questions));
        if (test) {
            param.put("type", "2"); // 测试用
            param.put("postData", buildPaperData(paperName, questions));
        } else {
            param.put("paperData", buildPaperData(paperName, questions));
        }
        byte[] data = HttpUtils.post(url, param);
        return data;
    }

    public static String buildPaperData(String paperName, List<LearnQuestions> questionsList) throws Exception {
        String[] paperInfos = new String[] { "A4", "1", "docx" };//

        JSONObject paperData = new JSONObject();
        paperData.put("paperStruType", "1");
        JSONObject mainTitle = new JSONObject();
        mainTitle.put("mainTitleExist", true);
        mainTitle.put("mainTitleName", paperName);

        paperData.put("mainTitle", mainTitle);

        /**
        JSONObject subTitle = new JSONObject();
        subTitle.put("subTitleExist", true);
        subTitle.put("subTitleName", "");

        paperData.put("subTitle", subTitle);


        paperData.put("bindingLine", true);
        paperData.put("securityMark", true);
        paperData.put("gradeBar", true);
        paperData.put("questionAndNotes", true);
        paperData.put("qGradeBar", true);
         **/
        paperData.put("fontSize", 2);
        paperData.put("subjectId", 1);
        paperData.put("phaseId", 1);

        paperData.put("paperSizeType", paperInfos[0]);
        paperData.put("answerType", paperInfos[1]);
        paperData.put("docType", paperInfos[2]);

        /**
        JSONObject paperInfoBar = new JSONObject();
        paperInfoBar.put("paperInfoBarExist", true);
        paperInfoBar.put("paperInfoBarName", "考试时间：120分钟；命题人：");
        paperData.put("paperInfoBar", paperInfoBar);

        JSONObject studentInfoBar = new JSONObject();
        studentInfoBar.put("studentInfoBarExist", true);
        studentInfoBar.put("studentInfoBarName", "学校=>___________姓名：___________班级：___________考号：___________");
        paperData.put("studentInfoBar", studentInfoBar);

        JSONObject needingAttention = new JSONObject();
        needingAttention.put("needingAttentionExist", true);
        needingAttention.put("attention", new String[] { "填写答题卡的内容用2B铅笔填写", "提前 10 分钟收取答题卡" });
        paperData.put("needingAttention", needingAttention);
        **/
        JSONObject notesList1 = new JSONObject();
        notesList1.put("title", "第I卷（选择题）");
        notesList1.put("notes", "请点击修改第I卷的文字说明");

        JSONObject notesList2 = new JSONObject();
        notesList2.put("title", "第II卷（非选择题）");
        notesList2.put("notes", "请点击修改第I卷的文字说明");

        /**
        JSONObject subPaperAndNotes = new JSONObject();
        subPaperAndNotes.put("subPaperAndNotesExist", true);
        subPaperAndNotes.put("notesList", new Object[] { notesList1, notesList2 });

        paperData.put("subPaperAndNotes", subPaperAndNotes);
         **/
        JSONArray $paperQtypeList = new JSONArray();
        Map<String, JSONObject> qtypeMap = new HashMap<String, JSONObject>();
        for (LearnQuestions questions : questionsList) {
            String qtpye = questions.getQtpye();
            if (!qtypeMap.containsKey(qtpye)) {
                JSONObject qm = new JSONObject();
                qm.put("questionFristType", qtpye);
                qm.put("questionId", questions.getId());
                qm.put("questionSecondType", "");
                qm.put("questionDesc", "");
                qm.put("questionTypeNote", "");
                qm.put("thisTypeSize", "4");
                // qm.put("questionsList", new JSONObject());
                qtypeMap.put(qtpye, qm);
                $paperQtypeList.add(qm);
            }

            JSONObject $ques = new JSONObject();
            $ques.put("questionContent", trim_first_div(questions.getTitle()));
            $ques.put("questionAnswer", replace_latex(questions.getAnswer2()));// $this->replace_img($question['answer2']),
            // knowledges
            JSONObject questionLabelList = new JSONObject();
            questionLabelList.put("labelName", replace_latex(questions.getKnowledges()));// ,//(string)$this->replace_img($question['knowledges']),
            questionLabelList.put("importance", 1);
            $ques.put("questionLabelList", questionLabelList);

            $ques.put("questionSource", "");
            $ques.put("questionDifficulty", questions.getDiff());
            $ques.put("questionAnswerInfo", trim_first_div(questions.getParse()));

            // options
            String $options = "<table>";
            if (StringUtils.isNotBlank(questions.getOptionA()))
                $options = $options + "<tr><td>A." + replace_latex(questions.getOptionA()) + "</td></tr>";
            if (StringUtils.isNotBlank(questions.getOptionB()))
                $options = $options + "<tr><td>B." + replace_latex(questions.getOptionB()) + "</td></tr>";
            if (StringUtils.isNotBlank(questions.getOptionC()))
                $options = $options + "<tr><td>C." + replace_latex(questions.getOptionC()) + "</td></tr>";
            if (StringUtils.isNotBlank(questions.getOptionD()))
                $options = $options + "<tr><td>D." + replace_latex(questions.getOptionD()) + "</td></tr>";
            if (StringUtils.isNotBlank(questions.getOptionE()))
                $options = $options + "<tr><td>E." + replace_latex(questions.getOptionE()) + "</td></tr>";
            $options = $options + "</table>";
            if ($options == "<table></table>")
                $options = "";
            $ques.put("questionSelection", $options);

            JSONObject qm = (JSONObject) qtypeMap.get(qtpye);
            JSONArray quesLIst = (JSONArray) qm.get("questionsList");
            if (quesLIst == null) {
                quesLIst = new JSONArray();
                qm.put("questionsList", quesLIst);
            }
            quesLIst.add($ques);
        }
        paperData.put("questionsTypeList", $paperQtypeList);

        String result = replace_latex(JSONObject.toJSONString(paperData));
//        System.out.println(result);
        return result;
    }

    private static String trim_first_div(String title) {
        return title;
    }

    private static String replace_latex(String str) {
        if (str == null) {
            return str;
        }
        return str.replace("&lt;", "<").replace("&gt;", ">");
    }
}
