package com.testor.module.report.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.common.util.ConverUtils;
import com.testor.common.util.FileUtil;
import com.testor.module.duty.model.domain.TSysDutyLog;
import com.testor.module.duty.model.domain.TSysTaskWork;
import com.testor.module.duty.model.dto.TSysDutyLogParam;
import com.testor.module.duty.service.TSysDutyLogService;
import com.testor.module.duty.service.TSysTaskWorkService;
import com.testor.module.partner.model.domain.TPartnerStaff;
import com.testor.module.partner.service.TPartnerStaffService;
import com.testor.module.train.exam.model.domain.TTrainExamChoice;
import com.testor.module.train.exam.model.domain.TTrainExamJudgment;
import com.testor.module.train.exam.model.domain.TTrainQuestionBank;
import com.testor.module.train.exam.model.domain.TTrainTestQuestions;
import com.testor.module.train.exam.service.TTrainExamChoiceService;
import com.testor.module.train.exam.service.TTrainExamJudgmentService;
import com.testor.module.train.exam.service.TTrainQuestionBankService;
import com.testor.module.train.exam.service.TTrainTestQuestionsService;
import com.testor.module.train.paper.model.domain.TTrainPaper;
import com.testor.module.train.paper.model.dto.*;
import com.testor.module.train.paper.service.TTrainPaperService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/freemarker")
@Api(value = "TTrainPaper", tags = "freemarker模板统一下载")
public class FreemarkerController {
    @Autowired
    private SysOrgService sysOrgService;
    @Autowired
    private Configuration configuration;
    @Autowired
    private TSysDutyLogService tSysDutyLogService;
    @Autowired
    private TSysTaskWorkService tSysTaskWorkService;
    @Resource
    private HttpServletResponse response;
    @Autowired
    private TTrainTestQuestionsService tTrainTestQuestionsService;
    @Autowired
    private TTrainPaperService tTrainPaperService;
    @Autowired
    private TTrainExamChoiceService tTrainExamChoiceService;
    @Autowired
    private TTrainExamJudgmentService tTrainExamJudgmentService;
    @Autowired
    private TTrainQuestionBankService tTrainQuestionBankService;

    @Autowired
    private TPartnerStaffService staffService;

    @Value("${ureport.path}")
    private String path;

    @Value("${minio.imgInport}")
    private String imgInport;

    @Value("${minio.path}")
    private String addr;

    @Resource
    private HttpServletRequest request;

    @PostMapping("/getDowDutyLog")
    @ApiOperation(value = "本单位批量下载值班日志", notes = "单个下载传 id   批量导出传 companyIds")
    public void getDownloadDutyLogsss(@RequestBody TSysDutyLogParam param) throws Exception {
        UserInfo loginUser = ContextUtils.getLoginUser();
        List<String> companyIds = param.getCompanyIds();
        QueryWrapper<TSysDutyLog> queryWrapper = new QueryWrapper<>();
        String dutyOrgId = param.getId();
        Template template = configuration.getTemplate("dowdutylog.ftl");
        //模板位置
        if (StringHelper.isNotEmpty(dutyOrgId)) {
            queryWrapper.eq(TSysDutyLog.ID, dutyOrgId);
            TSysDutyLog one = tSysDutyLogService.getOne(queryWrapper);
            one.setIssueApply("\n办理情况："+one.getIssueApply()+";遗留问题："+one.getPreHandoverIssue());
            Map<String, Object> oneMap = objectToMap(one);
            //作业活动
            String jobId = one.getJobId();
            String[] split = jobId.split(",");
            QueryWrapper<TSysTaskWork> wrapper = new QueryWrapper<>();
            wrapper.in(TSysTaskWork.ID, split);
            //获取作业活动
            List<TSysTaskWork> tSysTaskWorks = tSysTaskWorkService.export(wrapper);
            oneMap.put("taskWorkList", tSysTaskWorks);
            //ToDo 获取文件流转为base64格式

            toDo64(one, oneMap);
            //作业活动
            String onefileName = one.getCompanyName() + one.getDutyDate() + one.getSubmitter() + "值班工作日志.doc";
            ServletOutputStream servletOutputStream = exportWordFreemarker(onefileName);
            Writer bufferedWriter = new BufferedWriter(new OutputStreamWriter(servletOutputStream, "utf-8"));
            template.process(oneMap, bufferedWriter);
        } else {
            if (companyIds != null && companyIds.size()>0) {
                queryWrapper.in(TSysDutyLog.COMPANY_ID, companyIds);
            } else {
                String orgId = loginUser.getOrgId();
                queryWrapper.eq(TSysDutyLog.COMPANY_ID, orgId);
            }
            List<TSysDutyLog> list = tSysDutyLogService.list(queryWrapper);
            try {
                ZipArchiveOutputStream zos = ZipExport();
                for (TSysDutyLog tSysDutyLog : list) {
                    ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
                    Template template1 = configuration.getTemplate("dowdutylog.ftl");
                    Map<String, Object> tSysDutyLogMap = objectToMap(tSysDutyLog);
                    //导出文件名称
                    String fileName = tSysDutyLog.getCompanyName() + tSysDutyLog.getDutyDate() + tSysDutyLog.getSubmitter() + "值班工作日志.doc";
                    tSysDutyLog.setIssueApply("\n办理情况："+tSysDutyLog.getIssueApply()+";遗留问题："+tSysDutyLog.getPreHandoverIssue());
                    // 导出模板
                    //作业活动
                    String jobId = tSysDutyLog.getJobId();
                    String[] split = jobId.split(",");
                    QueryWrapper<TSysTaskWork> wrapper = new QueryWrapper<>();
                    wrapper.in(TSysTaskWork.ID, split);
                    //作业活动
                    List<TSysTaskWork> tSysTaskWorks = tSysTaskWorkService.export(wrapper);
                    tSysDutyLogMap.put("taskWorkList", tSysTaskWorks);
                    //ToDo 获取文件流转为base64格式
                    toDo64(tSysDutyLog, tSysDutyLogMap);
                    Writer bufferedWriter = new BufferedWriter(new OutputStreamWriter(arrayOutputStream, "utf-8"));
                    template.process(tSysDutyLogMap, bufferedWriter);
                    ArchiveEntry entry = new ZipArchiveEntry(fileName);
                    zos.putArchiveEntry(entry);
                    zos.write(arrayOutputStream.toByteArray());
                    zos.closeArchiveEntry();
                    arrayOutputStream.close();
                }
                zos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void toDo64(TSysDutyLog one, Map<String, Object> oneMap) {
        if (StringUtils.isNotBlank(one.getSuccessionSign())) {
            String successionSign = one.getSuccessionSign().substring(addr.length(), one.getSuccessionSign().length());

            oneMap.put("imginfoOne", FileUtil.convertImageFromUrlToBase64(imgInport+successionSign));
        }else {
            oneMap.put("imginfoOne","/9j/4AAQSkZJRgABAQAAkACQAAD/4QCARXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAA" +
                    "PgEbAAUAAAABAAAARgEoAAMAAAABAAIAAIdpAAQAAAABAAAATgAAAAAAAACQAAAAAQAAAJAAAAABAAOgAQADAAA" +
                    "AAf//AACgAgAEAAAAAQAAAU6gAwAEAAAAAQAAAJgAAAAA/+0AOFBob3Rvc2hvcCAzLjAAOEJJTQQEAAAAAAAAOEJJ" +
                    "TQQlAAAAAAAQ1B2M2Y8AsgTpgAmY7PhCfv/iEAhJQ0NfUFJPRklMRQABAQAAD/hhcHBsAhAAAG1udHJSR0IgWFlaIA" +
                    "fnAAQAAQAJAAwAJmFjc3BBUFBMAAAAAEFQUEwAAAAAAAAAAAAAAAAAAAAAAAD21gABAAAAANMtYXBwbAAAAAAAAAAAAAAA" +
                    "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEmRlc2MAAAFcAAAAYmRzY20AAAHAAAAEnGNwcnQAAAZcAAA" +
                    "AI3d0cHQAAAaAAAAAFHJYWVoAAAaUAAAAFGdYWVoAAAaoAAAAFGJYWVoAAAa8AAAAFHJUUkMAAAbQAAAIDGFhcmcAAA7cAA" +
                    "AAIHZjZ3QAAA78AAAAMG5kaW4AAA8sAAAAPmNoYWQAAA9sAAAALG1tb2QAAA+YAAAAKHZjZ3AAAA/AAAAAOGJUUkMAAAbQAA" +
                    "AIDGdUUkMAAAbQAAAIDGFhYmcAAA7cAAAAIGFhZ2cAAA7cAAAAIGRlc2MAAAAAAAAACERpc3BsYXkAAAAAAAAAAAAAAAAAAA" +
                    "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABtbHVjAAA" +
                    "AAAAAACYAAAAMaHJIUgAAABQAAAHYa29LUgAAAAwAAAHsbmJOTwAAABIAAAH4aWQAAAAAABIAAAIKaHVIVQAAABQAAAIcY3NDW" +
                    "gAAABYAAAIwZGFESwAAABwAAAJGbmxOTAAAABYAAAJiZmlGSQAAABAAAAJ4aXRJVAAAABgAAAKIZXNFUwAAABYAAAKgcm9STwA" +
                    "AABIAAAK2ZnJDQQAAABYAAALIYXIAAAAAABQAAALedWtVQQAAABwAAALyaGVJTAAAABYAAAMOemhUVwAAAAoAAAMkdmlWTgAAAA" +
                    "4AAAMuc2tTSwAAABYAAAM8emhDTgAAAAoAAAMkcnVSVQAAACQAAANSZW5HQgAAABQAAAN2ZnJGUgAAABYAAAOKbXMAAAAAABIAA" +
                    "AOgaGlJTgAAABIAAAOydGhUSAAAAAwAAAPEY2FFUwAAABgAAAPQZW5BVQAAABQAAAN2ZXNYTAAAABIAAAK2ZGVERQAAABAAAAPoZW5VUwAAABIAAAP4cHRCUgAAABgAAAQKcGxQTAAAABIAAAQiZWxHUgAAACIAAAQ0c3ZTRQAAABAAAARWdHJUUgAAABQAAARmcHRQVAAAABYAAAR6amFKUAAAAAwAAASQAEwAQwBEACAAdQAgAGIAbwBqAGnO7LfsACAATABDAEQARgBhAHIAZwBlAC0ATABDAEQATABDAEQAIABXAGEAcgBuAGEAUwB6AO0AbgBlAHMAIABMAEMARABCAGEAcgBlAHYAbgD9ACAATABDAEQATABDAEQALQBmAGEAcgB2AGUAcwBrAOYAcgBtAEsAbABlAHUAcgBlAG4ALQBMAEMARABWAOQAcgBpAC0ATABDAEQATABDAEQAIABhACAAYwBvAGwAbwByAGkATABDAEQAIABhACAAYwBvAGwAbwByAEwAQwBEACAAYwBvAGwAbwByAEEAQwBMACAAYwBvAHUAbABlAHUAciAPAEwAQwBEACAGR" +
                    " ");
        }
        if (StringUtils.isNotBlank(one.getHandoverSign())) {
            String handoverSign = one.getHandoverSign().substring(addr.length(), one.getHandoverSign().length());
            oneMap.put("imginfoTwo", FileUtil.convertImageFromUrlToBase64(imgInport+handoverSign));

        }else {
            oneMap.put("imginfoTwo","/9j/4AAQSkZJRgABAQAAkACQAAD/4QCARXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAA" +
                    "PgEbAAUAAAABAAAARgEoAAMAAAABAAIAAIdpAAQAAAABAAAATgAAAAAAAACQAAAAAQAAAJAAAAABAAOgAQADAAA" +
                    "AAf//AACgAgAEAAAAAQAAAU6gAwAEAAAAAQAAAJgAAAAA/+0AOFBob3Rvc2hvcCAzLjAAOEJJTQQEAAAAAAAAOEJJ" +
                    "TQQlAAAAAAAQ1B2M2Y8AsgTpgAmY7PhCfv/iEAhJQ0NfUFJPRklMRQABAQAAD/hhcHBsAhAAAG1udHJSR0IgWFlaIA" +
                    "fnAAQAAQAJAAwAJmFjc3BBUFBMAAAAAEFQUEwAAAAAAAAAAAAAAAAAAAAAAAD21gABAAAAANMtYXBwbAAAAAAAAAAAAAAA" +
                    "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEmRlc2MAAAFcAAAAYmRzY20AAAHAAAAEnGNwcnQAAAZcAAA" +
                    "AI3d0cHQAAAaAAAAAFHJYWVoAAAaUAAAAFGdYWVoAAAaoAAAAFGJYWVoAAAa8AAAAFHJUUkMAAAbQAAAIDGFhcmcAAA7cAA" +
                    "AAIHZjZ3QAAA78AAAAMG5kaW4AAA8sAAAAPmNoYWQAAA9sAAAALG1tb2QAAA+YAAAAKHZjZ3AAAA/AAAAAOGJUUkMAAAbQAA" +
                    "AIDGdUUkMAAAbQAAAIDGFhYmcAAA7cAAAAIGFhZ2cAAA7cAAAAIGRlc2MAAAAAAAAACERpc3BsYXkAAAAAAAAAAAAAAAAAAA" +
                    "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABtbHVjAAA" +
                    "AAAAAACYAAAAMaHJIUgAAABQAAAHYa29LUgAAAAwAAAHsbmJOTwAAABIAAAH4aWQAAAAAABIAAAIKaHVIVQAAABQAAAIcY3NDW" +
                    "gAAABYAAAIwZGFESwAAABwAAAJGbmxOTAAAABYAAAJiZmlGSQAAABAAAAJ4aXRJVAAAABgAAAKIZXNFUwAAABYAAAKgcm9STwA" +
                    "AABIAAAK2ZnJDQQAAABYAAALIYXIAAAAAABQAAALedWtVQQAAABwAAALyaGVJTAAAABYAAAMOemhUVwAAAAoAAAMkdmlWTgAAAA" +
                    "4AAAMuc2tTSwAAABYAAAM8emhDTgAAAAoAAAMkcnVSVQAAACQAAANSZW5HQgAAABQAAAN2ZnJGUgAAABYAAAOKbXMAAAAAABIAA" +
                    "AOgaGlJTgAAABIAAAOydGhUSAAAAAwAAAPEY2FFUwAAABgAAAPQZW5BVQAAABQAAAN2ZXNYTAAAABIAAAK2ZGVERQAAABAAAAPoZW5VUwAAABIAAAP4cHRCUgAAABgAAAQKcGxQTAAAABIAAAQiZWxHUgAAACIAAAQ0c3ZTRQAAABAAAARWdHJUUgAAABQAAARmcHRQVAAAABYAAAR6amFKUAAAAAwAAASQAEwAQwBEACAAdQAgAGIAbwBqAGnO7LfsACAATABDAEQARgBhAHIAZwBlAC0ATABDAEQATABDAEQAIABXAGEAcgBuAGEAUwB6AO0AbgBlAHMAIABMAEMARABCAGEAcgBlAHYAbgD9ACAATABDAEQATABDAEQALQBmAGEAcgB2AGUAcwBrAOYAcgBtAEsAbABlAHUAcgBlAG4ALQBMAEMARABWAOQAcgBpAC0ATABDAEQATABDAEQAIABhACAAYwBvAGwAbwByAGkATABDAEQAIABhACAAYwBvAGwAbwByAEwAQwBEACAAYwBvAGwAbwByAEEAQwBMACAAYwBvAHUAbABlAHUAciAPAEwAQwBEACAGR" +
                    " ");
        }
    }

    @SneakyThrows
    @ApiOperation(value = "试卷导出 试卷管理——安全教育培训 ", notes = "Get TTrainPaper By Id")
    @PostMapping("/export")
    public void export(@RequestBody TTrainPaperParam param){
        Long page = 1L;
        Long limit = 9999L;
        Page<TTrainPaper> resultPage = new Page<>(page, limit);
        QueryWrapper<TTrainPaper> queryWrapper = this.createQuery(param);
        String orgId = ContextUtils.getLoginUser().getOrgId();

        List<SysOrg> list = sysOrgService.list(new QueryWrapper<SysOrg>().select("org_id")
                .eq("parent_id", orgId).like("parent_ids", orgId).eq("status", "0").eq("is_dept", "0"));
        List<String> collect = list.stream().map(SysOrg::getOrgId).collect(Collectors.toList());
        collect.add(orgId);
        collect.add("32cdbb3a278944f1a83ca40dbcc93c0a");
        queryWrapper.in(collect.size()>0,"org_id",collect);
        Page<TTrainPaper> resultList = tTrainPaperService.page(resultPage, queryWrapper);
        List <String>ids=new ArrayList<>();
        if (!CollectionUtils.isEmpty(resultList.getRecords())) {
            ids= resultList.getRecords().stream().map(TTrainPaper::getId).collect(Collectors.toList());
        }else {
            return;
        }
        ZipArchiveOutputStream zos = ZipExport();
        for (String id : ids) {
            ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
            //freemarker的模板对象，获取模板
            Template template = configuration.getTemplate("TrainPaperExport.ftl");
            BaseResponse<ReturnTrainPaper> detail = tTrainPaperService.detail(id);
            ReturnTrainPaper data = detail.getData();
            if (CollectionUtils.isEmpty(data.getTestQuestionsContent())) {
                data.setTestQuestionsContent(new ArrayList<>());
            }
//            if (CollectionUtils.isEmpty(data.get())) {
//                data.setTestQuestionsContent(new ArrayList<>());
//            }
            Map<String, Object> map = new HashMap<>();
            map.put("paper", data);
            String fileName = data.getTestPaperName()+".doc";
            Writer bufferedWriter = new BufferedWriter(new OutputStreamWriter(arrayOutputStream, "utf-8"));
            template.process(map, bufferedWriter);
            ArchiveEntry entry = new ZipArchiveEntry(fileName);
            zos.putArchiveEntry(entry);
            zos.write(arrayOutputStream.toByteArray());
            zos.closeArchiveEntry();
            arrayOutputStream.close();
        }
        zos.close();
    }

    @ApiOperation(value = "导入试题模板下载 试卷管理——安全教育培训 ", notes = "Get TTrainPaper By Id")
    @GetMapping("/paperTemplateDownload")
    public void paperTemplateDownload(String id) throws Exception {

        TTrainQuestionBank service = tTrainQuestionBankService.getById(id);
        //  题库名称
        String questionBankName = service.getQuestionBankName();

        String url = path + "/ureport/excel?_u=file:TestQuestionTemplate.ureport.xml&id=" + id;
        Map<String, String> map = new HashMap<>();
        List<Map<String, String>> mapList = new ArrayList<>();
        map.put("path", url);
        map.put("name", "试题模板");
        String name = questionBankName+".xlsx";
        mapList.add(map);
        FileUtil.ExcelUrlToFile(mapList, request, response, name);
        //freemarker的模板对象，获取模板
//        Template template = configuration.getTemplate("paperTemplateDownload.ftl");
//        BaseResponse<ReturnTrainPaperTemplate> detail = detailDownload(id);
//        ReturnTrainPaperTemplate data = detail.getData();
//        Map<String, Object> map = new HashMap<>();
//        map.put("paper", data);
////        template.process(map, new FileWriter("d:/list.xlsx"));
//        TTrainQuestionBank service = tTrainQuestionBankService.getById(id);
//        String questionBankName = service.getQuestionBankName();
//        String fileName = questionBankName+".xlsx";
//        ServletOutputStream servletOutputStream = exportWordFreemarker(fileName);
//        Writer bufferedWriter = new BufferedWriter(new OutputStreamWriter(servletOutputStream, "utf-8"));
//        template.process(map, bufferedWriter);
    }

    public List<TestQuestionsContentTemplate> getExcelContent(String dsName, String datasetName, Map<String, Object> parameters) {
        List<TestQuestionsContentTemplate> templates = new ArrayList<>();
        String id = parameters.get("id").toString();
        BaseResponse<ReturnTrainPaperTemplate> detail = null;
        try {
            detail = detailDownload(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ReturnTrainPaperTemplate data = detail.getData();
        List<TestQuestionsContentTemplate> testQuestionsContentTemplate = data.getTestQuestionsContentTemplate();
        if (ObjectHelper.isEmpty(testQuestionsContentTemplate)) {
            return templates;
        }
        for (TestQuestionsContentTemplate contentTemplate : testQuestionsContentTemplate) {
            TestQuestionsContentTemplate template = BeanHelper.beanToBean(contentTemplate, TestQuestionsContentTemplate.class);
            for (OptionsTemplate optionsTemplate : contentTemplate.getOptionsTemplate()) {
                switch (optionsTemplate.getOptions()){
                    case "A":
                        template.setA(optionsTemplate.getOptionText());
                        break;
                    case "B":
                        template.setB(optionsTemplate.getOptionText());
                        break;
                    case "C":
                        template.setC(optionsTemplate.getOptionText());
                        break;
                    case "D":
                        template.setD(optionsTemplate.getOptionText());
                        break;
                }
            }
            templates.add(template);
        }
        return templates;
    }

    public BaseResponse<ReturnTrainPaperTemplate> detailDownload(String id) throws Exception {
        BaseResponse<ReturnTrainPaperTemplate> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            QueryWrapper<TTrainTestQuestions> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(TTrainTestQuestions.QUESTION_BANK_ID, id);
            //试卷包含的所有试题
            List<TTrainTestQuestions> trainTestQuestionsList = tTrainTestQuestionsService.list(queryWrapper);
            // 返回试卷详情
            ReturnTrainPaperTemplate returnTrainPaper = new ReturnTrainPaperTemplate();
            // 存储所有的题目
            List<TestQuestionsContentTemplate> testQuestionsContents = new ArrayList<>();
            int num = 0;
            for (TTrainTestQuestions tTrainTestQuestions : trainTestQuestionsList) {
                String testQuestionsType = tTrainTestQuestions.getTestQuestionsType();
                //试题id
                String questionsId = tTrainTestQuestions.getId();
                num++;
                String isCorrect = "";
                if ("SELECT".equals(testQuestionsType) || "MORE_SELECT".equals(testQuestionsType)) {
                    // 每一个题目
                    TestQuestionsContentTemplate testQuestionsContent = BeanHelper.beanToBean(tTrainTestQuestions, TestQuestionsContentTemplate.class);
                    QueryWrapper<TTrainExamChoice> wrapper = new QueryWrapper<>();
                    wrapper.eq(TTrainExamChoice.TEST_QUESTIONS_ID, questionsId);
                    // 当前题目包含的所有选项
                    List<TTrainExamChoice> list1 = tTrainExamChoiceService.list(wrapper);
                    // 按照选项排序
                    list1 = list1.stream().sorted(Comparator.comparing(TTrainExamChoice::getOptions))
                            .collect(Collectors.toList());
                    List<OptionsTemplate> optionsList = new ArrayList<>();
                    for (TTrainExamChoice tTrainExamChoice : list1) {
                        OptionsTemplate options = BeanHelper.beanToBean(tTrainExamChoice, OptionsTemplate.class);
                        if ("1".equals(options.getIsCorrect())) {
                            isCorrect += options.getOptions() + "、";
                        }
                        String optionsTest = options.getOptionText();
                        options.setOptionText(optionsTest);
                        optionsList.add(options);
                    }
                    String testQuestionsContent1 =  testQuestionsContent.getTestQuestionsContent();
                    testQuestionsContent.setTestQuestionsContent(testQuestionsContent1);
                    testQuestionsContent.setOptionsTemplate(optionsList);
                    String score = "";
                    if ("SELECT".equals(testQuestionsType)) {
                        score = "单选题";
                    }
                    if ("MORE_SELECT".equals(testQuestionsType)) {
                        score = "多选题";
                    }
                    testQuestionsContent.setScore(score);
                    testQuestionsContent.setIsCorrect(isCorrect);
                    testQuestionsContents.add(testQuestionsContent);
                }
                if ("JUDGE".equals(testQuestionsType)) {
                    // 每一个题目
                    TestQuestionsContentTemplate testQuestionsContent = BeanHelper.beanToBean(tTrainTestQuestions, TestQuestionsContentTemplate.class);
                    QueryWrapper<TTrainExamJudgment> wrapper = new QueryWrapper<>();
                    wrapper.eq(TTrainExamJudgment.TEST_QUESTIONS_ID, questionsId);
                    // 当前题目包含的所有选项
                    List<TTrainExamJudgment> list1 = tTrainExamJudgmentService.list(wrapper);
                    // 按照选项排序
                    list1 = list1.stream().sorted(Comparator.comparing(TTrainExamJudgment::getOptions))
                            .collect(Collectors.toList());
                    List<OptionsTemplate> optionsList = new ArrayList<>();
                    for (TTrainExamJudgment tTrainExamChoice : list1) {
                        OptionsTemplate options = BeanHelper.beanToBean(tTrainExamChoice, OptionsTemplate.class);
                        if ("1".equals(options.getIsCorrect())) {
                            isCorrect = options.getOptions();
                        }
                        String optionsTest = options.getOptionText();
                        options.setOptionText(optionsTest);
                        optionsList.add(options);
                    }
                    String testQuestionsContent1 =  testQuestionsContent.getTestQuestionsContent();
                    testQuestionsContent.setTestQuestionsContent(testQuestionsContent1);
                    testQuestionsContent.setOptionsTemplate(optionsList);
                    String score = "";
                    if ("JUDGE".equals(testQuestionsType)) {
                        score = "判断题";
                    }
                    testQuestionsContent.setScore(score);
                    testQuestionsContent.setIsCorrect(isCorrect);
                    testQuestionsContents.add(testQuestionsContent);
                }
                returnTrainPaper.setTestQuestionsContentTemplate(testQuestionsContents);
            }
            baseResponse.setData(returnTrainPaper);
        } else {
            throw new BusinessException("请求参数不正确");
        }
        return baseResponse;
    }

    /**
     * 导出freemarker
     *
     * @param fileName
     * @return
     * @throws Exception
     */
    private ServletOutputStream exportWordFreemarker(String fileName) throws Exception {
        response.reset();
        response.setHeader("Content-Type", "application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        ServletOutputStream outputStream = response.getOutputStream();
        return outputStream;
    }

    /**
     * 对象转为map
     *
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            map.put(fieldName, value);
        }
        return map;
    }

    /**
     * zip 打包导出
     *
     * @return
     */
    public ZipArchiveOutputStream ZipExport() throws Exception {
        String outputFileName = "文件" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".zip";
        response.reset();
        response.setHeader("Content-Type", "application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(outputFileName, "UTF-8"));
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        ZipArchiveOutputStream zos = new ZipArchiveOutputStream(response.getOutputStream());//压缩文件输出流
        zos.setUseZip64(Zip64Mode.AsNeeded);
        return zos;
    }
    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TTrainPaper> createQuery(TTrainPaperParam queryParam) {
        QueryWrapper<TTrainPaper> queryWrapper = new QueryWrapper<>();
        String orgId = ContextUtils.getLoginUser().getOrgId();
//        queryWrapper.eq(TTrainPaper.TEST_PAPER_STATUS, "1").or();
//        queryWrapper.eq(TTrainPaper.ORG_ID, orgId);
        queryWrapper.and(new Consumer<QueryWrapper<TTrainPaper>>() {
            @Override
            public void accept(QueryWrapper<TTrainPaper> tTrainPaperQueryWrapper) {
                tTrainPaperQueryWrapper.eq(TTrainPaper.TEST_PAPER_STATUS, "1").or().eq(TTrainPaper.ORG_ID, orgId);
            }
        });
        if (StringHelper.isNotEmpty(queryParam.getTestPaperStatus())) {
            queryWrapper.eq(TTrainPaper.TEST_PAPER_STATUS, queryParam.getTestPaperStatus());
        }
        if (StringHelper.isNotEmpty(queryParam.getTestPaperName())) {
            queryWrapper.like(TTrainPaper.TEST_PAPER_NAME, queryParam.getTestPaperName());
        }
        if (StringHelper.isNotEmpty(queryParam.getGroupPaperWay())) {
            queryWrapper.like(TTrainPaper.GROUP_PAPER_WAY, queryParam.getGroupPaperWay());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TTrainPaper.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TTrainPaper.STATUS, BizConstants.STATUS_DELETE);
        }
        if (StringHelper.isNotEmpty(queryParam.getOrderBy())) {
            if (StringHelper.isNotEmpty(queryParam.getOrderType())
                    && BizConstants.ASC.equals(queryParam.getOrderType())) {
                queryWrapper.orderByAsc(queryParam.getOrderBy());
            } else {
                queryWrapper.orderByDesc(queryParam.getOrderBy());
            }
        } else {
            queryWrapper.orderByDesc(TTrainPaper.UPDATE_DATE);
        }
        return queryWrapper;
    }
}
