package com.qmth.distributed.print.business.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.qmth.distributed.print.business.bean.dto.*;
import com.qmth.distributed.print.business.cache.CreatePdfCacheUtil;
import com.qmth.distributed.print.business.entity.*;
import com.qmth.distributed.print.business.enums.ExamDetailStatusEnum;
import com.qmth.distributed.print.business.enums.PrintMethodEnum;
import com.qmth.distributed.print.business.service.ExamDetailService;
import com.qmth.distributed.print.business.service.ExamStudentService;
import com.qmth.distributed.print.business.service.PrintCommonService;
import com.qmth.teachcloud.common.config.DictionaryConfig;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.*;
import com.qmth.teachcloud.common.enums.*;
import com.qmth.teachcloud.common.service.*;
import com.qmth.teachcloud.common.util.ConvertUtil;
import com.qmth.teachcloud.common.util.FileStoreUtil;
import com.qmth.teachcloud.common.util.RedisUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 创建pdf util
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2021/4/14
 */
@Component
public class CreatePdfUtil {
    private final static Logger log = LoggerFactory.getLogger(CreatePdfUtil.class);

//    @Resource
//    OssUtil ossUtil;

    @Resource
    BasicAttachmentService basicAttachmentService;

    @Resource
    FreemarkerUtil freemarkerUtil;

    @Resource
    @Lazy
    PrintCommonService printCommonService;

    @Resource
    ExamDetailService detailService;

    @Resource
    RedisUtil redisUtil;

    @Resource
    TeachcloudCommonService teachcloudCommonService;

    @Resource
    FileStoreUtil fileStoreUtil;

    @Resource
    BasicCampusService basicCampusService;

    @Resource
    SysOrgService sysOrgService;

    @Resource
    BasicCourseService basicCourseService;

    @Resource
    BasicClazzService basicClazzService;

    @Resource
    BasicSchoolService basicSchoolService;

    @Resource
    ExamDetailService examDetailService;

    @Resource
    ExamStudentService examStudentService;

    @Resource
    DictionaryConfig dictionaryConfig;

    /**
     * 创建登记表
     *
     * @param examDetail
     * @param basicAttachment
     * @param ordinaryPdfList
     * @param printCount
     */
    public void createCheckIn(ExamDetail examDetail, BasicAttachment basicAttachment, List<PdfDto> ordinaryPdfList, Integer printCount) throws Exception {
        BasicSchool basicSchool = basicSchoolService.getById(examDetail.getSchoolId());
        Map<String, List<String>> flowSchoolCodeMap = SystemConstant.getFlowSchoolCodeMap();
        if (Objects.isNull(basicAttachment)) {
            throw ExceptionResultEnum.ATTACHMENT_IS_NULL.exception();
        }
        String type = basicAttachment.getType();
        JSONObject jsonObject = JSONObject.parseObject(basicAttachment.getPath());

        if (Objects.nonNull(type) && Objects.equals(type, SystemConstant.PDF_PREFIX)) {
            String filePath = (String) jsonObject.get(SystemConstant.PATH);
            String url = SystemConstant.TEMP_FILES_DIR + File.separator + filePath;
            UploadFileEnum uploadFileEnum = UploadFileEnum.valueOf((String) jsonObject.get(SystemConstant.UPLOAD_TYPE));

//            File localFile = ossUtil.ossDownload(filePath, url);
            File localFile = fileStoreUtil.ossDownload(filePath, url, uploadFileEnum.getFssType());
            PdfDto pdfDto = PdfUtil.addPdfPage(localFile);
            for (int i = 0; i < printCount; i++) {
                if (flowSchoolCodeMap.get(SystemConstant.GDYKDX_FLOW_KEY).contains(basicSchool.getCode())) {
                    ordinaryPdfList.add(new PdfDto(localFile.getPath(), PageSizeEnum.A3, pdfDto.getPageCount()));
                } else if (flowSchoolCodeMap.get(SystemConstant.JXZYY_FLOW_KEY).contains(basicSchool.getCode())) {
                    ordinaryPdfList.add(new PdfDto(localFile.getPath(), PageSizeEnum.A4, pdfDto.getPageCount()));
                } else {
                    ordinaryPdfList.add(new PdfDto(localFile.getPath(), PageSizeEnum.A4, pdfDto.getPageCount()));
                }
            }
        } else {
            printCommonService.saveAttachmentPdf(ClassifyEnum.CHECK_IN, examDetail, basicAttachment, ordinaryPdfList, printCount, 0);
        }
    }

    /**
     * 生成卷袋贴
     *
     * @param tag
     * @param basicAttachment
     * @param schoolName
     * @param examStudentList
     * @param variablePdfList
     * @param printCount
     * @param examDetailCourseList
     * @throws IOException
     */
    public void createPaperPackage(boolean tag, BasicAttachment basicAttachment, String schoolName, ExamDetail examDetail, List<ExamStudentCourseDto> examStudentList, List<PdfDto> variablePdfList, Integer printCount, List<ExamDetailCourse> examDetailCourseList) throws IOException {
        if (Objects.isNull(basicAttachment)) {
            throw ExceptionResultEnum.ATTACHMENT_IS_NULL.exception();
        }
        Map<String, Object> htmlMap = new HashMap<>();
        if (Objects.nonNull(examDetailCourseList) && examDetailCourseList.size() > 0) {
            List<String> paperNumbers = examDetailCourseList.stream().map(s -> s.getPaperNumber()).collect(Collectors.toList());
            List<String> courseCodes = examDetailCourseList.stream().map(s -> s.getCourseCode()).collect(Collectors.toList());
            List<String> courseNames = examDetailCourseList.stream().map(s -> s.getCourseName()).collect(Collectors.toList());
            htmlMap.put("courseName", String.join(", ", courseNames));
            htmlMap.put("courseCode", String.join(", ", paperNumbers));
            // 学院
            Set<String> stringSet = new HashSet<>();
            List<BasicCourse> basicCourses = basicCourseService.findBySchoolIdAndCourseCode(examDetail.getSchoolId(), courseCodes);
            for (BasicCourse basicCours : basicCourses) {
                List<SysOrg> sysOrgs = sysOrgService.findParentsByOrgId(basicCours.getTeachingRoomId());
                Set<String> collegeName = sysOrgs.stream().filter(m -> OrgTypeEnum.COLLEGE.equals(m.getType())).map(m -> m.getName()).collect(Collectors.toSet());
                if (CollectionUtils.isEmpty(collegeName)) {
                    collegeName = sysOrgs.stream().filter(m -> OrgTypeEnum.FACULTY.equals(m.getType())).map(m -> m.getName()).collect(Collectors.toSet());
                }
                if (!CollectionUtils.isEmpty(collegeName)) {
                    stringSet.addAll(collegeName);
                }
            }
            htmlMap.put("collegeName", CollectionUtils.isEmpty(stringSet) ? "" : String.join(",", stringSet));
        } else {
            htmlMap.put("courseName", "");
            htmlMap.put("courseCode", "");
            htmlMap.put("collegeName", "");
        }
        Set<Long> clazzIdSet = new HashSet<>();
        for (ExamDetailCourse examDetailCourse : examDetailCourseList) {
            String clazzInfo = examDetailCourse.getClazzId();
            if (SystemConstant.strNotNull(clazzInfo)) {
                Set<Long> clazzIdSetCell = Arrays.stream(clazzInfo.split(",")).map(SystemConstant::convertIdToLong).collect(Collectors.toSet());
                clazzIdSet.addAll(clazzIdSetCell);
            }
        }
        List<Long> classIds = new ArrayList<>(clazzIdSet);

        String campusName = CollectionUtils.isEmpty(classIds) ? "" : basicCampusService.findCampusNamesByClazzIdList(classIds, ",");
        htmlMap.put("schoolName", schoolName);
        htmlMap.put("campusName", campusName);
        htmlMap.put("examSite", examDetail.getExamPlace());
        htmlMap.put("examRoom", examDetail.getExamRoom());
        htmlMap.put("startTime", DateUtil.format(new Date(examDetail.getExamStartTime()), SystemConstant.DEFAULT_DATE_PATTERN));
        htmlMap.put("endTime", DateUtil.format(new Date(examDetail.getExamEndTime()), SystemConstant.DEFAULT_DATE_PATTERN));
        htmlMap.put("paperCode", examDetail.getPackageCode());
        htmlMap.put("paperCodeImg", GoogleBarCodeUtil.createBarCode(examDetail.getPackageCode(), false));

        List<String> extendColumnList = examStudentList.stream().map(m -> m.getExtendFields()).distinct().collect(Collectors.toList());
        Set<String> startCollege = new HashSet();
        Set<String> className = new HashSet();
        Set<String> proctorCollege = new HashSet();
        Set<String> examManager = new HashSet();

        String className1 = examDetailService.findClazzNamesByClazzIds(classIds, ",");

        if (Objects.nonNull(extendColumnList) && extendColumnList.size() > 0) {
            for (String s : extendColumnList) {
                List<Map> mapList = JSONObject.parseArray(s, Map.class);
                for (Map map : mapList) {
                    if (Objects.equals("startCollege", map.get("code").toString())) {
                        startCollege.add(map.get("value").toString());
                    }
                    if (Objects.equals("className", map.get("code").toString())) {
                        className.add(map.get("value").toString());
                    }
                    if (Objects.equals("proctorCollege", map.get("code").toString())) {
                        proctorCollege.add(map.get("value").toString());
                    }
                    if (Objects.equals("examManager", map.get("code").toString())) {
                        examManager.add(map.get("value").toString());
                    }
                }
            }
        }

        htmlMap.put("startCollege", String.join(",", startCollege));
        htmlMap.put("className", StringUtils.isNotBlank(className1) ? className1 : String.join(",", className));
        htmlMap.put("proctorCollege", String.join(",", proctorCollege));
        htmlMap.put("examManager", String.join(",", examManager));

//        List<ExamStudent> tempList = examStudentList.stream().filter(s -> (Objects.nonNull(s.getSiteNumber()) && !Objects.equals("", s.getSiteNumber().trim()))).collect(Collectors.toList());
//        String minSite = "", maxSite = "";
//        if (Objects.nonNull(tempList) && tempList.size() > 0) {
//            minSite = tempList.stream().min((a, b) -> a.getSiteNumber().compareTo(b.getSiteNumber())).get().getSiteNumber();
//            maxSite = tempList.stream().max((a, b) -> a.getSiteNumber().compareTo(b.getSiteNumber())).get().getSiteNumber();
//        }

        Optional<ExamStudentCourseDto> minSite = null;
        Optional<ExamStudentCourseDto> maxSite = null;
        List<ExamStudentCourseDto> tempList = examStudentList.stream().filter(s -> (Objects.nonNull(s.getSiteNumber()) && !Objects.equals("", s.getSiteNumber().trim()))).collect(Collectors.toList());
        if (Objects.nonNull(tempList) && tempList.size() > 0) {
//            for (ExamStudentCourseDto e : tempList) {
//                char[] chars = e.getSiteNumber().toLowerCase().toCharArray();
//                String ascii = "";
//                for (int i = 0; i < chars.length; i++) {
//                    ascii = ascii + chars[i];
//                }
//                e.setAscii(ascii.hashCode());
//            }
            minSite = tempList.stream().min(Comparator.comparing(s -> s.getSiteNumber().hashCode()));
            maxSite = tempList.stream().max(Comparator.comparing(s -> s.getSiteNumber().hashCode()));
        }

        htmlMap.put("minSite", Optional.ofNullable(minSite).map(s -> s.get().getSiteNumber()).orElse(""));
        htmlMap.put("maxSite", Optional.ofNullable(maxSite).map(s -> s.get().getSiteNumber()).orElse(""));
        htmlMap.put("studentCount", examStudentList != null && examStudentList.size() > 0 ? examStudentList.size() : examDetail.getPrintCount());

        String tagValue = tag ? "订" : null;
        htmlMap.put("tag", tagValue);

        htmlMap.computeIfAbsent("basicAttachment", v -> basicAttachment);
        htmlMap.computeIfAbsent("variablePdfList", v -> variablePdfList);
        htmlMap.computeIfAbsent("printCount", v -> printCount);
        htmlMap.computeIfAbsent("sequence", v -> 1);
        htmlMap.computeIfAbsent("examDetail", v -> examDetail);
        htmlMap.computeIfAbsent("printType", v -> ClassifyEnum.PACKAGE);
        freemarkerUtil.createPaperPackage(htmlMap);
    }

    /**
     * 创建签到表
     *
     * @param basicAttachment
     * @param schoolName
     * @param examDetail
     * @param examStudentList
     * @param variablePdfList
     * @param printCount
     * @param examDetailCourseList
     */
    public void createSignBook(BasicAttachment basicAttachment, String schoolName, ExamDetail examDetail, List<ExamStudentCourseDto> examStudentList, List<PdfDto> variablePdfList, Integer printCount, List<ExamDetailCourse> examDetailCourseList) throws IOException {
        if (Objects.isNull(basicAttachment)) {
            throw ExceptionResultEnum.ATTACHMENT_IS_NULL.exception();
        }
        Map<String, Object> htmlMap = new HashMap<>();
        if (Objects.nonNull(examDetailCourseList) && examDetailCourseList.size() > 0) {
            List<String> paperNumbers = examDetailCourseList.stream().map(ExamDetailCourse::getPaperNumber).collect(Collectors.toList());
            List<String> courseNames = examDetailCourseList.stream().map(ExamDetailCourse::getCourseName).collect(Collectors.toList());
            htmlMap.put("courseName", String.join(", ", courseNames));
            htmlMap.put("courseCode", String.join(", ", paperNumbers));
        } else {
            htmlMap.put("courseName", "");
            htmlMap.put("courseCode", "");
        }
        htmlMap.put("schoolName", schoolName);
        htmlMap.put("examRoom", examDetail.getExamRoom());

        List<String> extendColumnList = examStudentList.stream().map(ExamStudent::getExtendFields).distinct().collect(Collectors.toList());
        Set<String> classTeacher = new HashSet();
        if (extendColumnList.size() > 0) {
            for (String s : extendColumnList) {
                List<Map> mapList = JSONObject.parseArray(s, Map.class);
                for (Map map : mapList) {
                    if (Objects.equals("classTeacher", map.get("code").toString())) {
                        classTeacher.add(map.get("value").toString());
                    }
                }
            }
        }
        htmlMap.put("classTeacher", String.join(",", classTeacher));
        htmlMap.put("startTime", DateUtil.format(new Date(examDetail.getExamStartTime()), SystemConstant.DEFAULT_DATE_PATTERN));
        htmlMap.put("endTime", DateUtil.format(new Date(examDetail.getExamEndTime()), SystemConstant.DEFAULT_DATE_PATTERN));
        htmlMap.put("paperCode", examDetail.getPackageCode());
        htmlMap.put("paperCodeImg", GoogleBarCodeUtil.createBarCode(examDetail.getPackageCode(), false));

        int pageSize = 60;
        int halfPageSize = pageSize / 2;

        if (examStudentList.size() > 0) {
            int totalCount = examStudentList.size();
            List<Map> subList = new ArrayList<>();
            int pageCount = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
            for (int i = 0; i < pageCount; i++) {
                Map subMap = new HashMap();
                subMap.put("index", i + 1);
                int studentCount;
                List<ExamStudentCourseDto> subStudents;
                if (pageCount == 1) {
                    studentCount = totalCount;
                    subStudents = examStudentList;
                } else if (i == pageCount - 1) {
                    studentCount = totalCount - (pageCount - 1) * pageSize;
                    subStudents = examStudentList.subList(pageSize * i, examStudentList.size());
                } else {
                    studentCount = pageSize;
                    subStudents = examStudentList.subList(pageSize * i, pageSize * (i + 1));
                }
                subMap.put("studentCount", totalCount);
                List<ExamStudentDto> examStudentList1 = new ArrayList<>();
                List<ExamStudentDto> examStudentList2 = new ArrayList<>();

                Gson gson = new Gson();
                int mod = subStudents.size() % 2;
                int htmlTableCount = mod == 0 ? subStudents.size() / 2 : subStudents.size() / 2 + 1;
                for (int j = 0; j < htmlTableCount; j++) {
                    ExamStudentDto examStudentDto = gson.fromJson(gson.toJson(subStudents.get(j)), ExamStudentDto.class);
                    examStudentDto.setIndex(j + 1);
                    String clazzName = getClassName(examStudentDto);
                    examStudentDto.setClazzName(clazzName);
                    examStudentList1.add(examStudentDto);
                }
                for (int j = htmlTableCount; j < subStudents.size(); j++) {
                    ExamStudentDto examStudentDto = gson.fromJson(gson.toJson(subStudents.get(j)), ExamStudentDto.class);
                    examStudentDto.setIndex(j + 1);
                    String clazzName = getClassName(examStudentDto);
                    examStudentDto.setClazzName(clazzName);
                    examStudentList2.add(examStudentDto);
                }
//                if (examStudentList1.size() > examStudentList2.size()) {
//                    for (int j = subStudents.size() - htmlTableCount; j < examStudentList1.size(); j++) {
//                        examStudentList2.add(new ExamStudentDto());
//                    }
//                }
                if (examStudentList1.size() < halfPageSize) {
                    int examStudentList1Size = examStudentList1.size();
                    for (int j = 0; j < halfPageSize - examStudentList1Size; j++) {
                        ExamStudentDto examStudentDto = new ExamStudentDto();
                        examStudentDto.setIndex(null);
                        examStudentDto.setSiteNumber("");
                        examStudentDto.setStudentName("");
                        examStudentDto.setClazzName("");
                        examStudentList1.add(examStudentDto);
                    }
                }
                if (examStudentList2.size() < halfPageSize) {
                    int examStudentList2Size = examStudentList2.size();
                    for (int j = 0; j < halfPageSize - examStudentList2Size; j++) {
                        ExamStudentDto examStudentDto = new ExamStudentDto();
                        examStudentDto.setIndex(null);
                        examStudentDto.setSiteNumber("");
                        examStudentDto.setStudentName("");
                        examStudentDto.setClazzName("");
                        examStudentList2.add(examStudentDto);
                    }
                }
                subMap.put("studentList1", examStudentList1);
                subMap.put("studentList2", examStudentList2);
                subList.add(subMap);
            }
            htmlMap.put("subList", subList);
        } else {
            int totalCount = examDetail.getPrintCount();
            List<Map> subList = new ArrayList<>();
            int pageCount = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
            for (int i = 0; i < pageCount; i++) {
                Map subMap = new HashMap();
                subMap.put("index", i + 1);
                int studentCount;
                if (pageCount == 1) {
                    studentCount = pageSize;
                } else if (i == pageCount - 1) {
                    studentCount = totalCount - (pageCount - 1) * pageSize;
                } else {
                    studentCount = pageSize;
                }
                subMap.put("studentCount", totalCount);
                List<ExamStudentDto> examStudentList1 = new ArrayList<>();
                List<ExamStudentDto> examStudentList2 = new ArrayList<>();

                int mod = studentCount % 2;
                int htmlTableCount = mod == 0 ? studentCount / 2 : studentCount / 2 + 1;
                for (int j = 0; j < htmlTableCount; j++) {
                    ExamStudentDto examStudentDto = new ExamStudentDto();
                    examStudentDto.setIndex(null);
                    examStudentDto.setStudentName("");
                    examStudentDto.setClazzName("");
                    examStudentList1.add(examStudentDto);
                }
                for (int j = htmlTableCount; j < studentCount; j++) {
                    ExamStudentDto examStudentDto = new ExamStudentDto();
                    examStudentDto.setIndex(null);
                    examStudentDto.setStudentName("");
                    examStudentDto.setClazzName("");
                    examStudentList2.add(examStudentDto);
                }
                if (examStudentList1.size() < halfPageSize) {
                    for (int j = 0; j < halfPageSize - examStudentList1.size(); j++) {
                        ExamStudentDto examStudentDto = new ExamStudentDto();
                        examStudentDto.setIndex(null);
                        examStudentDto.setSiteNumber("");
                        examStudentDto.setStudentName("");
                        examStudentDto.setClazzName("");
                        examStudentList1.add(examStudentDto);
                    }
                }
                if (examStudentList2.size() < halfPageSize) {
                    for (int j = 0; j < halfPageSize - examStudentList2.size(); j++) {
                        ExamStudentDto examStudentDto = new ExamStudentDto();
                        examStudentDto.setIndex(null);
                        examStudentDto.setSiteNumber("");
                        examStudentDto.setStudentName("");
                        examStudentDto.setClazzName("");
                        examStudentList2.add(examStudentDto);
                    }
                }
                subMap.put("studentList1", examStudentList1);
                subMap.put("studentList2", examStudentList2);
                subList.add(subMap);
            }
            htmlMap.put("subList", subList);
        }
        htmlMap.computeIfAbsent("basicAttachment", v -> basicAttachment);
        htmlMap.computeIfAbsent("variablePdfList", v -> variablePdfList);
        htmlMap.computeIfAbsent("printCount", v -> printCount);
        htmlMap.computeIfAbsent("sequence", v -> 2);
        htmlMap.computeIfAbsent("examDetail", v -> examDetail);
        htmlMap.computeIfAbsent("printType", v -> ClassifyEnum.SIGN);
        freemarkerUtil.createSignBook(htmlMap);
    }

    /**
     * 替换html通用模版中的条码信息
     *
     * @param content 题卡详细内容
     */
    public String resetHtmlTemplateBar(String content) {
        content = content.replaceAll("<img src=\"data:image/png;base64,\\$\\{examNumber\\}\">", "");
        content = content.replaceAll("\\$\\{examNumberStr\\}", "");
        return content;
    }

    /**
     * 替换自定义题卡参数
     *
     * @param examCardDetail
     * @return
     * @throws IOException
     */
    public String replaceHtmlCard(ExamCardDetail examCardDetail, BasicCardRule basicCardRule) throws IOException {
        //通用题卡
        String cardTemp = examCardDetail.getHtmlContent();
        cardTemp = cardTemp.replaceAll("\\$\\{paperTypeName\\}", "");
        //随机生成试卷条码并将图片转成base64
        cardTemp = cardTemp.replaceAll("\\$\\{paperType\\}", "");
        cardTemp = cardTemp.replaceAll("<img src=\"data:image/png;base64,\\$\\{examNumber\\}\">", "");
        cardTemp = cardTemp.replaceAll("\\$\\{examNumberStr\\}", "");
        if (Objects.nonNull(basicCardRule) && Objects.nonNull(basicCardRule.getExtendFields())) {
            JSONArray jsonObjectExtend = (JSONArray) JSONArray.parse(basicCardRule.getExtendFields());//扩展字段
            if (Objects.nonNull(jsonObjectExtend)) {
                for (int i = 0; i < jsonObjectExtend.size(); i++) {
                    JSONObject object = (JSONObject) jsonObjectExtend.get(i);
                    cardTemp = cardTemp.replaceAll("\\$\\{" + object.get("code") + "\\}", "");
                }
            }
        }
        cardTemp = cardTemp.replaceAll("\\$\\{examDate\\}", "");
        cardTemp = cardTemp.replaceAll("\\$\\{examTime\\}", "");
        cardTemp = cardTemp.replaceAll("\\$\\{ticketNumber\\}", "");
        cardTemp = cardTemp.replaceAll("\\$\\{siteNumber\\}", "");
        cardTemp = cardTemp.replaceAll("\\$\\{paperTypeName\\}", "");
        cardTemp = cardTemp.replaceAll("\\$\\{studentCode\\}", "");
        cardTemp = cardTemp.replaceAll("\\$\\{studentName\\}", "");
        cardTemp = cardTemp.replaceAll("\\$\\{courseName\\}", "");
        cardTemp = cardTemp.replaceAll("\\$\\{courseCode\\}", "");
        cardTemp = cardTemp.replaceAll("\\$\\{examPlace\\}", "");
        cardTemp = cardTemp.replaceAll("\\$\\{examRoom\\}", "");
        cardTemp = cardTemp.replaceAll("\\$\\{paperNumber\\}", "");

        // 根据题卡规则必选字段，替换相应值，没有则“”
        List<StudentExtendDto> studentExtendDtos = createExtendObjectNull(basicCardRule);
        if (studentExtendDtos != null) {
            for (StudentExtendDto extendDto : studentExtendDtos) {
                cardTemp = cardTemp.replaceAll("\\$\\{" + extendDto.getFieldName() + "\\}", String.valueOf(extendDto.getValue()));
            }
        }

        return cardTemp;
    }

    /**
     * 获取题卡attachmentId
     *
     * @param examCardDetail
     * @param attachmentIds
     */
    public void getCardAttachmentId(ExamCardDetail examCardDetail, Set<Long> attachmentIds) {
        if (Objects.nonNull(examCardDetail.getAttachmentId()) && !Objects.equals("", examCardDetail.getAttachmentId())) {
            JSONObject jsonObjectCard = JSONObject.parseObject(examCardDetail.getAttachmentId());
            JSONArray jsonArrayCard = (JSONArray) jsonObjectCard.get("card");
            for (int i = 0; i < jsonArrayCard.size(); i++) {
                JSONObject object = (JSONObject) jsonArrayCard.get(i);
                if (Objects.nonNull(object.get("attachmentId")) && !Objects.equals("", object.get("attachmentId"))) {
                    attachmentIds.add((Long) (object.get("attachmentId")));
                }
            }
        }
    }

    /**
     * 获取试卷pdf
     *
     * @param stuPaperType 考生卷型
     * @param paperPdfDto  抽取的试卷文件信息
     * @param pdfList      考生试卷集合
     */
    public PdfDto getExamStudentPaperPdf(String stuPaperType, List<PaperPdfDto> paperPdfDto, List<PdfDto> pdfList) throws IOException {
        Set<Integer> pagesList = new HashSet<>();
        if (!CollectionUtils.isEmpty(paperPdfDto)) {
            for (PaperPdfDto dto : paperPdfDto) {
                if (stuPaperType.equals(dto.getType())) {
                    int pages = dto.getPages();
                    pagesList.add(pages);
                    PdfDto pdfDto = PdfUtil.addPdfPage(dto.getFile());
                    pdfList.add(new PdfDto(dto.getFile().getPath(), PageSizeEnum.A3, pdfDto.getPageCount()));
                }
            }
            int pageCount = pagesList.stream().mapToInt(Integer::intValue).sum();
            return new PdfDto(PageSizeEnum.A3, pageCount);
        } else {
            return null;
        }
    }

    /**
     * 获取试卷pdf
     *
     * @param paperPdfDto 抽取的试卷文件信息
     * @param backupCount 备份数量
     * @param pdfList     备份试卷集合
     */
    public PdfDto getPaperPdf(List<PaperPdfDto> paperPdfDto, Integer backupCount, List<PdfDto> pdfList) throws IOException {
        Set<Integer> pagesList = new HashSet<>();
        boolean tag = false;
        if (!CollectionUtils.isEmpty(paperPdfDto)) {
            for (PaperPdfDto dto : paperPdfDto) {
                int pages = dto.getPages();
                pagesList.add(pages);
                tag = pages > 2;
                PdfDto pdfDto = PdfUtil.addPdfPage(dto.getFile());
                for (int j = 1; j <= backupCount; j++) {
                    pdfList.add(new PdfDto(dto.getFile().getPath(), PageSizeEnum.A3, pdfDto.getPageCount()));
                }
            }
            int pageCount = pagesList.stream().mapToInt(Integer::intValue).sum();
            return new PdfDto(PageSizeEnum.A3, pageCount, tag);
        } else {
            return null;
        }
    }

    /**
     * 获取考试试卷
     *
     * @param paperType      抽取的试卷型（多个用,分隔）
     * @param examTaskDetail 命题任务上传试卷信息
     */
    public List<PaperPdfDto> getPaperPdfFile(String paperType, ExamTaskDetail examTaskDetail) throws Exception {
        String[] paperTypes = paperType.split(",");
        List<PaperPdfDto> paperPdfDtoList = new ArrayList<>();
        PaperPdfDto paperPdfDto = null;
        JSONArray jsonArrayPaper = JSONArray.parseArray(examTaskDetail.getPaperAttachmentIds());
        for (int i = 0; i < jsonArrayPaper.size(); i++) {
            JSONObject object = (JSONObject) jsonArrayPaper.get(i);
            if (Objects.nonNull(object.get("attachmentId")) && !Objects.equals("", object.get("attachmentId"))) {
                Long attachmentId = Long.parseLong((String) (object.get("attachmentId")));
                BasicAttachment basicAttachment = basicAttachmentService.getById(attachmentId);
                if (Objects.isNull(basicAttachment)) {
                    throw ExceptionResultEnum.ATTACHMENT_IS_NULL.exception();
                }
                String name = (String) object.get("name");
                // 返回抽中的试卷
                for (String type : paperTypes) {
                    if (Objects.equals(name.toUpperCase(), type.toUpperCase())) {
                        File file = teachcloudCommonService.getFile(basicAttachment.getPath(), false);
                        int pages = (int) object.get("pages");
                        paperPdfDto = new PaperPdfDto(type, file, pages);
                        paperPdfDtoList.add(paperPdfDto);
                        break;
                    }
                }

            }
        }
        return paperPdfDtoList;
    }

    /**
     * 抽取试卷
     *
     * @param drawRule
     * @param examTaskDetail
     * @param key
     * @return
     */
    public String getPaperType(DrawRuleEnum drawRule, ExamTaskDetail examTaskDetail, String key) {
        //抽取卷型
        drawRule = Objects.nonNull(drawRule) ? drawRule : DrawRuleEnum.ONE;
        //未曝光卷型
        String unexposedPaperType = examTaskDetail.getUnexposedPaperType();
        //已曝光卷型
        String exposedPaperType = examTaskDetail.getExposedPaperType();

        if (drawRule == DrawRuleEnum.ONE) {
            if (Objects.isNull(unexposedPaperType) || Objects.equals(unexposedPaperType.trim(), "")) {
//                CreatePdfCacheUtil.deletePaperType(key);
                throw ExceptionResultEnum.PAPER_ERROR.exception();
            }
        } else {
            if ((Objects.isNull(exposedPaperType) || Objects.equals(exposedPaperType.trim(), "")) && (Objects.isNull(unexposedPaperType) || Objects.equals(unexposedPaperType.trim(), ""))) {
//                CreatePdfCacheUtil.deletePaperType(key);
                throw ExceptionResultEnum.PAPER_ERROR.exception();
            }
        }
        // 单次抽取套数
        int drawCount = examTaskDetail.getDrawCount().intValue();
        String paperType = null;
        String[] paperTypes;
        boolean lock = true;
        for (int i = 0; i < SystemConstant.MAX_RETRY_COUNT; i++) {
            lock = redisUtil.lock(key, SystemConstant.REDIS_CACHE_TIME_OUT);
            if (lock) {
                try {
                    paperType = CreatePdfCacheUtil.getPaperType(key);
                    if (StringUtils.isBlank(paperType)) {
                        if (drawRule == DrawRuleEnum.ONE) {
                            paperTypes = unexposedPaperType.split(",");
                            if (paperTypes.length - drawCount < 0) {
                                throw ExceptionResultEnum.ERROR.exception("没有可用卷型");
                            }
                        } else {
                            if (Objects.nonNull(unexposedPaperType)) {
                                paperTypes = unexposedPaperType.split(",");
                            } else {
                                paperTypes = exposedPaperType.split(",");
                            }
                        }
                        paperType = randomPaperType(paperTypes, exposedPaperType, drawCount);
                        CreatePdfCacheUtil.setPaperType(key, paperType);
                    }
                    break;
                } catch (Exception e) {
                    log.error(SystemConstant.LOG_ERROR, e);
                } finally {
                    redisUtil.releaseLock(key);
                }
            } else {//未获取到锁，等待500毫秒继续获取
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    log.error(SystemConstant.LOG_ERROR, e);
                }
            }
        }
        log.info("getPaperType key:{},paperType:{},lock:{}", key, paperType, lock);
        if (!lock) {
            log.info("getPaperType 未获取到锁,key:{}", key);
            throw ExceptionResultEnum.PAPER_TYPE_ERROR.exception();
        }
        return paperType;
    }

    private String randomPaperType(String[] unexposedPaperTypes, String exposedPaperTypes, int drawCount) {
        List<String> finalTypes = new ArrayList<>();
        List<String> unexposedPaperTypesList = new ArrayList<>(Arrays.asList(unexposedPaperTypes));
        List<String> exposedPaperTypesList = StringUtils.isBlank(exposedPaperTypes) ? new ArrayList<>() : new ArrayList<>(Arrays.asList(exposedPaperTypes.split(",")));
        if (unexposedPaperTypesList.size() - drawCount >= 0) {
            for (int i = 0; i < drawCount; i++) {
                int paperRandom = new Random().nextInt(unexposedPaperTypesList.size());
                finalTypes.add(unexposedPaperTypesList.get(paperRandom));
                unexposedPaperTypesList.remove(paperRandom);
            }

        } else {
            for (int i = 0; i < unexposedPaperTypesList.size(); i++) {
                int paperRandom = new Random().nextInt(unexposedPaperTypesList.size());
                finalTypes.add(unexposedPaperTypesList.get(paperRandom));
                unexposedPaperTypesList.remove(paperRandom);
            }
            for (int i = 0; i < drawCount - unexposedPaperTypesList.size(); i++) {
                int paperRandom = new Random().nextInt(exposedPaperTypesList.size());
                finalTypes.add(exposedPaperTypesList.get(paperRandom));
                exposedPaperTypesList.remove(paperRandom);
            }
        }
        finalTypes = finalTypes.stream().sorted(Comparator.comparing(String::valueOf)).collect(Collectors.toList());
        return String.join(",", finalTypes);
    }

    /**
     * 合并A3 pdf
     *
     * @param list
     * @return
     * @throws IOException
     */
    public String mergeA3Pdf(List<PdfDto>... list) throws IOException {
        List<PdfDto> mergePdfA3List = new ArrayList<>();
        for (int i = 0; i < list.length; i++) {
            mergePdfA3List.addAll(list[i]);
        }
        List<String> pathA3List = mergePdfA3List.stream().map(PdfDto::getPath).collect(Collectors.toList());
        return PdfUtil.mergePdf(pathA3List.toArray(new String[mergePdfA3List.size()]), null);
    }

    /**
     * 合并A4 pdf
     *
     * @param list
     * @return
     * @throws IOException
     */
    public String mergeA4Pdf(List<PdfDto>... list) throws IOException {
        List<PdfDto> mergePdfA4List = new ArrayList<>();
        for (int i = 0; i < list.length; i++) {
            mergePdfA4List.addAll(list[i]);
        }
        List<String> pathA4List = mergePdfA4List.stream().map(PdfDto::getPath).collect(Collectors.toList());
        return PdfUtil.mergePdf(pathA4List.toArray(new String[mergePdfA4List.size()]), null);
    }

    /**
     * 合并pdf后保存数据库
     *
     * @param dirNameA4
     * @param dirNameA3
     * @param dirNameCardA3
     * @param tbTask
     * @param userId
     * @param examDetail
     * @param basicExamRule
     * @param mergePdfDeleteList
     * @return
     * @throws IOException
     */
    @Transactional
    public BasicAttachment mergePdfSaveDb(String dirNameA4,
                                          String dirNameA3,
                                          String dirNameCardA3,
                                          TBTask tbTask,
                                          Long userId,
                                          ExamDetail examDetail,
                                          BasicExamRule basicExamRule,
                                          List<PdfDto> mergePdfDeleteList) throws Exception {
        boolean oss = dictionaryConfig.sysDomain().isOss();
        StringJoiner stringJoiner = new StringJoiner("").add(SystemConstant.PDF_TEMP_FILES_DIR).add(File.separator);
        // oss上只认"/"，windows生成的路径分隔符全部替换为"/"
        File localA4PdfFile = null, localA3PdfFile = null, localA3PdfCardFile = null;
        BasicAttachment basicAttachment = null;
        if (Objects.nonNull(dirNameA4)) {
            dirNameA4 = dirNameA4.replaceAll("\\\\", "/");
            localA4PdfFile = new File(stringJoiner.toString() + File.separator + dirNameA4);
        }
        // 试卷+题卡
        if (Objects.nonNull(dirNameA3)) {
            dirNameA3 = dirNameA3.replaceAll("\\\\", "/");
            localA3PdfFile = new File(stringJoiner.toString() + File.separator + dirNameA3);
            basicAttachment = basicAttachmentService.saveAttachmentPdf(dirNameA3, userId);
            tbTask.setImportFileName(basicAttachment.getName());
            tbTask.setImportFilePath(basicAttachment.getPath());
            examDetail.setAttachmentId(basicAttachment.getId());
        }
        // 题卡
        if (Objects.nonNull(dirNameCardA3)) {
            dirNameCardA3 = dirNameCardA3.replaceAll("\\\\", "/");
            localA3PdfCardFile = new File(stringJoiner.toString() + File.separator + dirNameCardA3);
            basicAttachment = basicAttachmentService.saveAttachmentPdf(dirNameCardA3, userId);
            if (StringUtils.isBlank(tbTask.getImportFileName())) {
                tbTask.setImportFileName(basicAttachment.getName());
            }
            if (StringUtils.isBlank(tbTask.getImportFilePath())) {
                tbTask.setImportFilePath(basicAttachment.getPath());
            }
            examDetail.setCardAttachmentId(basicAttachment.getId());
        }
        examDetail.setPagesA3(PdfUtil.getPdfPages(localA3PdfFile));
        examDetail.setPagesA4(PdfUtil.getPdfPages(localA4PdfFile));
        if (PrintMethodEnum.AUTO == basicExamRule.getPrintMethod()) {
            examDetail.setStatus(ExamDetailStatusEnum.WAITING);
        } else {
            examDetail.setStatus(ExamDetailStatusEnum.READY);
        }
        detailService.saveOrUpdate(examDetail);
        if (Objects.nonNull(localA3PdfFile) && oss) {
//            ossUtil.ossUpload(dirNameA3, localA3PdfFile, DigestUtils.md5Hex(new FileInputStream(localA3PdfFile)));
            fileStoreUtil.ossUpload(dirNameA3, localA3PdfFile, DigestUtils.md5Hex(new FileInputStream(localA3PdfFile)), fileStoreUtil.getUploadEnumByPath(dirNameA3).getFssType());
            localA3PdfFile.delete();
        }
        if (Objects.nonNull(localA3PdfCardFile) && oss) {
            fileStoreUtil.ossUpload(dirNameCardA3, localA3PdfCardFile, DigestUtils.md5Hex(new FileInputStream(localA3PdfCardFile)), fileStoreUtil.getUploadEnumByPath(dirNameCardA3).getFssType());
            localA3PdfCardFile.delete();
        }
        if (Objects.nonNull(localA4PdfFile) && oss) {
            localA4PdfFile.delete();
        }
        //删除题卡临时文件
//        if (oss) {
        for (PdfDto pdfDto : mergePdfDeleteList) {
            if (Objects.nonNull(pdfDto)) {
                new File(pdfDto.getPath()).delete();
            }
        }
//        }
//        for (PdfDto pdfDto : mergePdfA3List) {
//            if (Objects.nonNull(pdfDto)) {
//                new File(pdfDto.getPath()).delete();
//            }
//        }
//        for (PdfDto pdfDto : mergePdfA4List) {
//            if (Objects.nonNull(pdfDto)) {
//                new File(pdfDto.getPath()).delete();
//            }
//        }
        return basicAttachment;
    }

    /**
     * 删除附件
     *
     * @param attachmentIds
     * @param ftlList
     */
    public void deleteAttachment(Set<Long> attachmentIds, Set<File> ftlList) {
        if (Objects.nonNull(attachmentIds) && attachmentIds.size() > 0) {
            QueryWrapper<BasicAttachment> basicAttachmentQueryWrapper = new QueryWrapper<>();
            basicAttachmentQueryWrapper.lambda().in(BasicAttachment::getId, attachmentIds);
            basicAttachmentService.batchDeleteAttachment(basicAttachmentService.list(basicAttachmentQueryWrapper));
            basicAttachmentService.removeByIds(attachmentIds);
        }
        if (Objects.nonNull(dictionaryConfig.sysDomain()) && dictionaryConfig.sysDomain().isOss()) {
            if (Objects.nonNull(ftlList) && ftlList.size() > 0) {
                for (File file : ftlList) {
                    file.delete();
                }
            }
        }
    }

    /**
     * 考生题卡html
     *
     * @param studentContent     题卡html内容
     * @param examStudent        考生对象
     * @param examDetail         考场对象
     * @param examDetailCourse   考场课程对象
     * @param userId             当前用户ID
     * @param examStudentPdfList 考生题卡集合
     * @param basicCardRule      题卡规则
     */
    public BasicAttachment examStudentHtml(String studentContent, ExamStudent examStudent, String paperType, ExamDetail examDetail, ExamDetailCourse examDetailCourse, Long userId, List<PdfDto> examStudentPdfList, BasicCardRule basicCardRule) throws IOException {
        String studentHtml = studentContent;
            /*if (Objects.nonNull(examStudent.getExtendFields())) {
                JSONArray jsonObjectExtend = (JSONArray) JSONArray.parse(examStudent.getExtendFields());//扩展字段
                if (Objects.nonNull(jsonObjectExtend)) {
                    int i = 0;
                    while (i < jsonObjectExtend.size()) {
                        JSONObject object = (JSONObject) jsonObjectExtend.get(i);
                        studentHtml = studentHtml.replaceAll("\\$\\{" + object.get("code") + "\\}", String.valueOf(object.get("value")));
                        i++;
                    }
                }
            }*/
        // 生成学生考号条码并将图片转成base64
        studentHtml = studentHtml.replaceAll("\\$\\{examNumber\\}", examStudent != null && examStudent.getTicketNumber() != null ? GoogleBarCodeUtil.createBarCode(examStudent.getTicketNumber(), false) : "");
        studentHtml = studentHtml.replaceAll("\\$\\{examNumberStr\\}", examStudent != null && examStudent.getTicketNumber() != null ? examStudent.getTicketNumber() : "");
        // 随机生成学生试卷条码并将图片转成base64
        studentHtml = studentHtml.replaceAll("\\$\\{paperType\\}", examStudent != null && examStudent.getPaperType() != null ? GoogleBarCodeUtil.createBarCode(SystemConstant.convertPaperType(examStudent.getPaperType()), false) : StringUtils.isNotBlank(paperType) ? GoogleBarCodeUtil.createBarCode(SystemConstant.convertPaperType(paperType), false) : "");
        // 替换考生卷型
        studentHtml = studentHtml.replaceAll("\\$\\{paperTypeName\\}", examStudent != null && examStudent.getPaperType() != null ? examStudent.getPaperType() : StringUtils.isNotBlank(paperType) ? paperType : "");

        // 根据题卡规则必选字段，替换相应值，没有则“”
        List<StudentExtendDto> studentExtendDtos = createExtendObject(examDetail, examStudent, basicCardRule);
        if (studentExtendDtos != null) {
            for (StudentExtendDto extendDto : studentExtendDtos) {
                studentHtml = studentHtml.replaceAll("\\$\\{" + extendDto.getFieldName() + "\\}", String.valueOf(extendDto.getValue()));
            }
        }
        // 以下值通过createExtendObject动态设置了，暂时屏蔽（2022-03-11 by xf）
            /*
            studentHtml = studentHtml.replaceAll("\\$\\{ticketNumber\\}", examStudent.getTicketNumber());
            studentHtml = studentHtml.replaceAll("\\$\\{siteNumber\\}", examStudent.getSiteNumber());
            studentHtml = studentHtml.replaceAll("\\$\\{studentCode\\}", examStudent.getStudentCode());
            studentHtml = studentHtml.replaceAll("\\$\\{studentName\\}", examStudent.getStudentName());
            studentHtml = studentHtml.replaceAll("\\$\\{courseName\\}", examDetailCourse.getCourseName());
            studentHtml = studentHtml.replaceAll("\\$\\{courseCode\\}", examDetailCourse.getCourseCode());
            studentHtml = studentHtml.replaceAll("\\$\\{examPlace\\}", examDetail.getExamPlace());
            studentHtml = studentHtml.replaceAll("\\$\\{examRoom\\}", examDetail.getExamRoom());
            studentHtml = studentHtml.replaceAll("\\$\\{paperNumber\\}", examDetailCourse.getPaperNumber());*/

        //学生题卡
        BasicAttachment examStudentAttachment = printCommonService.saveAttachmentHtml(examDetail.getSchoolId() + "|" + examDetailCourse.getCourseCode() + (examStudent != null && examStudent.getTicketNumber() != null ? "|" + examStudent.getTicketNumber() : ""), studentHtml, userId, examStudentPdfList);
        if (examStudent != null) {
            examStudent.setAttachmentId(examStudentAttachment.getId());
        }
        return examStudentAttachment;
    }

    /**
     * 题卡规则字段
     *
     * @param examDetail
     * @param examStudent   考生对象
     * @param basicCardRule 题卡规则对象
     */
    private List<StudentExtendDto> createExtendObject(ExamDetail examDetail, ExamStudent examStudent, BasicCardRule basicCardRule) {
        ExamStudentPdfInfoDto examStudentPdfInfoDto = examStudent == null ? null : examStudentService.getByStudentId(examStudent.getId());
        if (basicCardRule == null) {
            return null;
        }
        List<JSONObject> requiredFieldsJson = JSONArray.parseArray(basicCardRule.getRequiredFields(), JSONObject.class);
        List<StudentExtendDto> studentExtendDtos = new ArrayList<>();
        if (requiredFieldsJson.size() > 0) {
            for (JSONObject jsonObject : requiredFieldsJson) {
                StudentExtendDto studentExtendDto = new StudentExtendDto();
                String code = String.valueOf(jsonObject.get("code"));
                studentExtendDto.setFieldName(code);
                Object value = examStudentPdfInfoDto == null ? null : ReflectUtil.getFieldValue(examStudentPdfInfoDto, code);
                studentExtendDto.setValue(value == null ? "" : value);
                studentExtendDtos.add(studentExtendDto);
            }
        }
        List<JSONObject> extendFieldsJson = JSONArray.parseArray(basicCardRule.getExtendFields(), JSONObject.class);
        if (extendFieldsJson.size() > 0) {
            Map<String, Object> studentExtendMap = null;
            if (examStudentPdfInfoDto != null && StringUtils.isNotBlank(examStudentPdfInfoDto.getExtendFields())) {
                studentExtendMap = JSONArray.parseArray(examStudentPdfInfoDto.getExtendFields(), JSONObject.class).stream().collect(Collectors.toMap(k -> String.valueOf(k.get("code")), v -> v.get("value")));
            }


            Map<String, Object> map = ConvertUtil.analyzeDateAndTime(examDetail.getExamStartTime(), examDetail.getExamEndTime());

            for (JSONObject jsonObject : extendFieldsJson) {
                boolean enable = Boolean.parseBoolean(jsonObject.get("enable").toString());
                StudentExtendDto studentExtendDto = new StudentExtendDto();
                String code = String.valueOf(jsonObject.get("code"));


                studentExtendDto.setFieldName(code);
                Object value = examStudentPdfInfoDto == null ? null : ReflectUtil.getFieldValue(examStudentPdfInfoDto, code);
                // 时间需要特殊处理
                if ("examDate".equals(code)) {
                    value = Objects.nonNull(map.get("date")) ? (String) map.get("date") : "";
                }
                if ("examTime".equals(code)) {
                    value = Objects.nonNull(map.get("time")) ? (String) map.get("time") : "";
                }
                if (value == null) {
                    value = studentExtendMap == null ? null : studentExtendMap.get(code);
                }
                studentExtendDto.setValue(value == null ? "" : value);
                studentExtendDtos.add(studentExtendDto);
            }
        }
        return studentExtendDtos;
    }

    /**
     * 题卡规则字段
     *
     * @param basicCardRule 题卡规则对象
     */
    private List<StudentExtendDto> createExtendObjectNull(BasicCardRule basicCardRule) {
        if (basicCardRule == null) {
            return null;
        }
        List<JSONObject> requiredFieldsJson = JSONArray.parseArray(basicCardRule.getRequiredFields(), JSONObject.class);
        List<StudentExtendDto> studentExtendDtos = new ArrayList<>();
        if (requiredFieldsJson.size() > 0) {
            for (JSONObject jsonObject : requiredFieldsJson) {
                StudentExtendDto studentExtendDto = new StudentExtendDto();
                String code = String.valueOf(jsonObject.get("code"));
                studentExtendDto.setFieldName(code);
                studentExtendDto.setValue("");
                studentExtendDtos.add(studentExtendDto);
            }
        }
        List<JSONObject> extendFieldsJson = JSONArray.parseArray(basicCardRule.getExtendFields(), JSONObject.class);
        if (extendFieldsJson.size() > 0) {
            for (JSONObject jsonObject : extendFieldsJson) {
                StudentExtendDto studentExtendDto = new StudentExtendDto();
                String code = String.valueOf(jsonObject.get("code"));
                studentExtendDto.setFieldName(code);
                studentExtendDto.setValue("");
                studentExtendDtos.add(studentExtendDto);
            }
        }
        return studentExtendDtos;
    }

    /**
     * 通用题卡html
     *
     * @param sequence         序号
     * @param cardContent      题卡内容
     * @param examDetail       考场对象
     * @param examDetailCourse 考场课程对象
     * @param jsonArray        组装json返回
     * @param userId           当前用户ID
     * @param cardPdfList      备用题卡集合
     * @param basicCardRule    题卡规则对象
     */
    public BasicAttachment cardHtml(String sequence, String cardContent, ExamDetail examDetail, ExamDetailCourse examDetailCourse, JSONArray jsonArray, Long userId, List<PdfDto> cardPdfList, BasicCardRule basicCardRule) throws IOException {
        //通用题卡
        String cardTemp = cardContent;
        cardTemp = cardTemp.replaceAll("\\$\\{paperTypeName\\}", examDetailCourse.getPaperType());
        //随机生成试卷条码并将图片转成base64
        if (Objects.nonNull(examDetailCourse.getPaperType())) {
            cardTemp = cardTemp.replaceAll("\\$\\{paperType\\}", GoogleBarCodeUtil.createBarCode(SystemConstant.convertPaperType(examDetailCourse.getPaperType()), false));
        }
        if (Objects.nonNull(basicCardRule) && Objects.nonNull(basicCardRule.getExtendFields())) {
            JSONArray jsonObjectExtend = (JSONArray) JSONArray.parse(basicCardRule.getExtendFields());//扩展字段
            if (Objects.nonNull(jsonObjectExtend)) {
                int i = 0;
                while (i < jsonObjectExtend.size()) {
                    JSONObject object = (JSONObject) jsonObjectExtend.get(i);
                    cardTemp = cardTemp.replaceAll("\\$\\{" + object.get("code") + "\\}", "");
                    i++;
                }
            }
        }
        cardTemp = cardTemp.replaceAll("\\$\\{examDate\\}", "");
        cardTemp = cardTemp.replaceAll("\\$\\{examTime\\}", "");
        cardTemp = cardTemp.replaceAll("\\$\\{ticketNumber\\}", "");
        cardTemp = cardTemp.replaceAll("\\$\\{siteNumber\\}", "");
        cardTemp = cardTemp.replaceAll("\\$\\{paperTypeName\\}", "");
        cardTemp = cardTemp.replaceAll("\\$\\{studentCode\\}", "");
        cardTemp = cardTemp.replaceAll("\\$\\{studentName\\}", "");
        cardTemp = cardTemp.replaceAll("\\$\\{courseName\\}", "");
        cardTemp = cardTemp.replaceAll("\\$\\{courseCode\\}", "");
        cardTemp = cardTemp.replaceAll("\\$\\{examPlace\\}", "");
        cardTemp = cardTemp.replaceAll("\\$\\{examRoom\\}", "");
        cardTemp = cardTemp.replaceAll("\\$\\{paperNumber\\}", "");

        //通用题卡生成卷袋贴条码
        String packageCode = examDetail.getPackageCode() + sequence;
        String packageCodeImg = GoogleBarCodeUtil.createBarCode(packageCode, false);

        if (cardTemp.contains("<div class=\"page-box page-box-A3 page-box-0\">")) {
            String packageCodeDiv = "<div class=\"page-box page-box-A3 page-box-0\"><div class=\"package-number\" style=\"position: absolute;width: 200px;height: 40px;top: 10px;right: 25%;margin-left: -100px;text-align: center;z-index: 99;\"><img src=\"data:image/png;base64," + packageCodeImg + "\" style=\"display: block; height: 28px; width: 100%\" /><p style=\"line-height: 1; font-size: 12px; margin: 0;\">" + packageCode + "</p></div>";
            cardTemp = cardTemp.replaceAll("<div class=\"page-box page-box-A3 page-box-0\">", packageCodeDiv);
        } else if (cardTemp.contains("<div class=\"page-box page-box-A4 page-box-0\">")) {
            String packageCodeDiv = "<div class=\"page-box page-box-A4 page-box-0\"><div class=\"package-number\" style=\"position: absolute;width: 200px;height: 40px;top: 10px;right: 25%;margin-left: -100px;text-align: center;z-index: 99;\"><img src=\"data:image/png;base64," + packageCodeImg + "\" style=\"display: block; height: 28px; width: 100%\" /><p style=\"line-height: 1; font-size: 12px; margin: 0;\">" + packageCode + "</p></div>";
            cardTemp = cardTemp.replaceAll("<div class=\"page-box page-box-A4 page-box-0\">", packageCodeDiv);
        }


        BasicAttachment cardAttachment = printCommonService.saveAttachmentHtml(examDetail.getSchoolId() + "|" + examDetailCourse.getCourseCode(), cardTemp, userId, cardPdfList);
        JSONObject object = new JSONObject();
        object.put("name", examDetailCourse.getPaperType());
        object.put("examDetailCourseId", examDetailCourse.getId());
        object.put("attachmentId", cardAttachment.getId());
        object.put("packageCode", packageCode);
        jsonArray.add(object);
        return cardAttachment;
    }

    /**
     * 获取班级名称
     *
     * @param examStudentDto
     * @return
     */
    private String getClassName(ExamStudentDto examStudentDto) {
        String clazzName = examStudentDto.getClazzName();
        if (StringUtils.isNotBlank(clazzName)) {
            return clazzName;
        }
        if (StringUtils.isNotBlank(examStudentDto.getClazzId())) {
            BasicClazz basicClazz = basicClazzService.getById(examStudentDto.getClazzId());
            clazzName = Objects.nonNull(basicClazz) ? basicClazz.getClazzName() : null;
        }
        if (StringUtils.isNotBlank(clazzName)) {
            return clazzName;
        }
        List<Map> mapList = JSONObject.parseArray(examStudentDto.getExtendFields(), Map.class);
        for (Map map : mapList) {
            if (Objects.equals("className", map.get("code").toString())) {
                return map.get("value").toString();
            }
        }
        return null;
    }
}
