package com.yizhi.application.exam.controller;

import com.yizhi.core.application.context.TaskContext;
import com.yizhi.core.application.file.constant.FileConstant;
import com.yizhi.core.application.file.task.AbstractDefaultTask;
import com.yizhi.core.application.file.util.OssUpload;
import com.yizhi.exam.application.feign.QuestionLibraryClient;
import com.yizhi.exam.application.feign.QuestionLibraryOptionClient;
import com.yizhi.exam.application.feign.QuestionLibrarySubjectClient;
import com.yizhi.exam.application.vo.QuestionLibraryVO;
import com.yizhi.exam.application.vo.domain.TrQuestionLibrarySubject;
import com.yizhi.exam.application.vo.domain.TrQuestionSubjectOption;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <功能>导出题库试题(xml导出)</>
 */

@Component
public class LibrarySubjectXmlExport extends AbstractDefaultTask<String, Map<String, Object>> {

    //    private String sheetName = "题库试题导出";
    private Integer pageSize = 20;
    private Integer pageNo = 1;
    private static Logger LOGGER = LoggerFactory.getLogger(LibrarySubjectXmlExport.class);
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

    @Value("${ACTIVE}")
    public String active;
    @Autowired
    QuestionLibrarySubjectClient questionLibrarySubjectClient;
    @Autowired
    QuestionLibraryOptionClient questionLibraryOptionClient;
    @Autowired
    QuestionLibraryClient questionLibraryClient;

    @Override
    protected String execute(Map<String, Object> map) {
        String upLoadUrl = null;
        Long companyId = Long.valueOf(map.get("companyId").toString());
        Long accountId = Long.valueOf(map.get("accountId").toString());
        Long siteId = Long.valueOf(map.get("siteId").toString());
        Long orgId = Long.valueOf(map.get("orgId").toString());
        Long libraryId = Long.valueOf(map.get("libraryId").toString());
        Date submitTime = (Date) map.get("submitTime");
        String serialNo = (String) map.get("serialNo");
        Long taskId = (Long) map.get("taskId");
        String taskName = (String) map.get("taskName");

        QuestionLibraryVO questionLibraryVO = questionLibraryClient.selectQuestionLibraryById(libraryId);
        String sheetName = questionLibraryVO.getName();

        //创建任务
        TaskContext taskContext = new TaskContext(taskId, serialNo, taskName, accountId, submitTime, siteId, companyId);//任务id、任务名称、操作人ID、操作时间
        working(taskContext);

        List<TrQuestionLibrarySubject> subjectList = null;
        List<TrQuestionLibrarySubject> resultList = new ArrayList<>();
        List<TrQuestionSubjectOption> optionList = null;

        try {
            // 1、创建document对象
            Document document = DocumentHelper.createDocument();
            // 2、创建根节点root
            Element root = document.addElement("root");
            OutputFormat formatXml = null;

            try {
                //获取所需要的题库中分页中所有subject试题
                pageNo = (Integer) map.get("pageNo");
                pageSize = (Integer) map.get("pageSize");
                Integer subjectNum = (Integer) map.get("subjectNum");
                if (subjectNum == null) {
                    subjectNum = 0;
                }
                if (pageNo > 0 && pageSize > 0) {
                    Integer pageTotal = subjectNum / pageSize;
                    if (pageTotal == 0) {
                        subjectList = questionLibrarySubjectClient.queryQuestionLibraryList(libraryId, pageNo, pageSize);
                        if (!CollectionUtils.isEmpty(subjectList)) {
                            resultList.addAll(subjectList);
                        }
                    } else {
                        for (int i = 1; i <= pageTotal; i++) {
                            subjectList = questionLibrarySubjectClient.queryQuestionLibraryList(libraryId, i, pageSize);
                            if (!CollectionUtils.isEmpty(subjectList)) {
                                resultList.addAll(subjectList);
                            }
                        }
                        if (subjectNum % pageSize > 0) {
                            subjectList = questionLibrarySubjectClient.queryQuestionLibraryList(libraryId, pageTotal + 1, pageSize);
                            if (!CollectionUtils.isEmpty(subjectList)) {
                                resultList.addAll(subjectList);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.error("查询对应的subject表数据出错", e);
                fail(taskContext, "查询对应的subject表数据出错");
            }

            if (resultList.size() > 0 && null != resultList) {
                for (TrQuestionLibrarySubject librarySubject : resultList) {

                    // 3、生成子节点及子节点内容
                    Element channel = root.addElement("multiply");
                    Element typeNode = channel.addElement("type");
                    typeNode.setText(librarySubject.getType().toString());
                    if (librarySubject.getType().equals(1)) {
                        typeNode.setText("单选题");
                    }
                    if (librarySubject.getType().equals(2)) {
                        typeNode.setText("多选题");
                    }
                    if (librarySubject.getType().equals(3)) {
                        typeNode.setText("判断题");
                    }
                    if (librarySubject.getType().equals(4)) {
                        typeNode.setText("问答题");
                    }

                    Element stemNode = channel.addElement("stem");
                    stemNode.setText(librarySubject.getStem() == null ? "" : librarySubject.getStem());
                    Element questionLabelNode = channel.addElement("question_label");
                    questionLabelNode.setText(librarySubject.getQuestionLabel() == null ? "" : librarySubject.getQuestionLabel());
                    Element analysisNode = channel.addElement("analysis");
                    analysisNode.setText(librarySubject.getAnalysis() == null ? "" : librarySubject.getAnalysis());

                    if (librarySubject.getType().equals(4)) {
                        Element scoreRuleNode = channel.addElement("score_rule");
                        // xml的text(元素节点)不能为null
                        scoreRuleNode.setText(replaceNullString(librarySubject.getScoreRule()));

                    }

                    //因为type为4代表的是问答题，  是没有选项的 ，需要过滤问答题
                    if (librarySubject.getType() == 1 || librarySubject.getType() == 2 || librarySubject.getType() == 3) {
                        Long subjectId = librarySubject.getId();
                        if (null != subjectId && subjectId != 0) {
                            try {
                                optionList = questionLibraryOptionClient.QueryTrQuestionSubjectOptionList(subjectId);
                            } catch (Exception e) {
                                e.printStackTrace();
                                LOGGER.error("查询对应的option表数据出错", e);
                                fail(taskContext, "查询对应的option表数据出错");

                            }
                            if (null != optionList && optionList.size() > 0) {

                                StringBuilder sb = new StringBuilder();

                                Element isAnswerNode = channel.addElement("is_answer");
                                for (int j = 0; j < optionList.size(); j++) {
                                    TrQuestionSubjectOption option = optionList.get(j);
                                    Integer isAnswer = option.getIsAnswer();
                                    String content = option.getContent();
                                    Integer sort = j + 1;

                                    if (isAnswer == 1) {
                                        //该步不会第一位有逗号，也防止最后一位拼接逗号！
                                        if (sb.length() > 0) {
                                            sb.append(",");
                                        }
                                        sb.append(sort);
                                    }
                                    isAnswerNode.setText(sb.toString());
                                    Element contentNode = channel.addElement("content" + (j + 1));
                                    contentNode.setText(content);
                                }

                            }
                        }

                    }
                }

                // 4、设置生成xml的格式
                formatXml = OutputFormat.createPrettyPrint();
                // 设置编码格式
                formatXml.setEncoding("UTF-8");
            }

            // 5、生成xml文件
            File fileName = new File(sheetName + "_" + simpleDateFormat.format(submitTime) + ".xml");
            String requestPath = FileConstant.SAVE_PATH;
            File fileDir = new File(requestPath);
            if (!fileDir.exists()) {
                fileDir.mkdir();
            }

            String path = requestPath + File.separator + fileName.getName();
            FileOutputStream os = null;
            File file = null;
            XMLWriter writer = null;
            try {
                os = new FileOutputStream(path);
                writer = new XMLWriter(os, formatXml);
                // 设置是否转义，默认使用转义字符
                writer.setEscapeText(false);
                writer.write(document);

                // 阿里云返回url
                upLoadUrl = OssUpload.upload(path, fileName.getName());
                file = new File(path);
                success(taskContext, "成功", upLoadUrl);
            } catch (Exception e1) {
                e1.printStackTrace();
                fail(taskContext, "写入过程中发生错误");
                LOGGER.error("上传过程中发生错误，请查看日志");
            } finally {
                if (os != null) {
                    os.close();
                }
                if (writer != null) {
                    writer.close();
                }
                if (file != null) {
                    file.delete();
                }
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            fail(taskContext, sheetName + "导出过程中发生错误，请查看日志" + e.getMessage());
            LOGGER.error(sheetName + "导出过程中发生错误，请查看日志");
        }
        return upLoadUrl;
    }

    public static String replaceNullString(String str) {
        if (str == null) {
            return "";
        } else {
            return str;
        }
    }
}


