package com.qmth.distributed.print.business.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.qmth.boot.api.exception.ApiException;
import com.qmth.distributed.print.business.bean.dto.SyncExamCardDto;
import com.qmth.distributed.print.business.bean.dto.SyncExamStudentDto;
import com.qmth.distributed.print.business.entity.*;
import com.qmth.distributed.print.business.enums.ExamPaperStructureStatusEnum;
import com.qmth.distributed.print.business.enums.ExamPrintPlanSyncStatusEnum;
import com.qmth.distributed.print.business.enums.PrintPlanStatusEnum;
import com.qmth.distributed.print.business.service.*;
import com.qmth.teachcloud.common.bean.dto.stmms.GroupDetailDTO;
import com.qmth.teachcloud.common.bean.dto.stmms.PicConfig;
import com.qmth.teachcloud.common.bean.dto.stmms.QuestionBaseDTO;
import com.qmth.teachcloud.common.bean.dto.stmms.QuestionDTO;
import com.qmth.teachcloud.common.config.DictionaryConfig;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicAttachment;
import com.qmth.teachcloud.common.entity.SysOrg;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.enums.SyncFileTypeEnum;
import com.qmth.teachcloud.common.enums.TaskResultEnum;
import com.qmth.teachcloud.common.enums.TaskStatusEnum;
import com.qmth.teachcloud.common.service.BasicAttachmentService;
import com.qmth.teachcloud.common.service.TeachcloudCommonService;
import com.qmth.teachcloud.common.sync.CloudMarkingTaskUtils;
import com.qmth.teachcloud.common.util.ServletUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.*;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * 同步服务类
 */
@Service
public class DataSyncServiceImpl implements DataSyncService {

    private final static Logger log = LoggerFactory.getLogger(DataSyncServiceImpl.class);

    @Resource
    private ExamPrintPlanService examPrintPlanService;

    @Resource
    private TBSyncTaskService tbSyncTaskService;

    @Resource
    private ExamStudentService examStudentService;

    @Resource
    private ExamDetailService examDetailService;

    @Resource
    private ExamCardService examCardService;

    @Resource
    private ExamPaperStructureService examPaperStructureService;


    @Resource
    private TeachcloudCommonService teachcloudCommonService;

    @Resource
    private BasicAttachmentService basicAttachmentService;

    @Resource
    private ExamPaperGroupService examPaperGroupService;

    @Resource
    private ExamPaperGroupMarkerService examPaperGroupMarkerService;

    @Resource
    private CloudMarkingTaskUtils cloudMarkingTaskUtils;

    ExecutorService executorService = Executors.newFixedThreadPool(5);

    @Resource
    DictionaryConfig dictionaryConfig;

    /**
     * 定时任务批量同步
     */
    @Override
    public void syncToCloudReview() {
        // 查询可同步计划（同步状态为空：未同步，false：同步失败）
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        QueryWrapper<ExamPrintPlan> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ExamPrintPlan::getStatus, PrintPlanStatusEnum.END)
                .and(q -> q.isNull(ExamPrintPlan::getSyncStatus).or().eq(ExamPrintPlan::getSyncStatus, false));
        List<ExamPrintPlan> examPrintPlans = examPrintPlanService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(examPrintPlans)) {
            for (ExamPrintPlan examPrintPlan : examPrintPlans) {
//                executorService.execute(syncBaseData(examPrintPlan, null, examPrintPlan.getName(), sysUser));
            }
        }
    }

    @Async
    @Override
    public void syncExamAndStudentAndCard(Long thirdRelateId, String thirdRelateName, Long examEndTime, TBSyncTask tbSyncTask, SysUser sysUser) {
        UpdateWrapper<ExamPrintPlan> updateWrapper = new UpdateWrapper<>();
        ExamPrintPlanSyncStatusEnum syncStatus = ExamPrintPlanSyncStatusEnum.INIT;

        // 同步初始参数
        TaskResultEnum result = null;
        TaskStatusEnum status;
        String errorMessage = null;
        Long schoolId = tbSyncTask.getSchoolId();
        Long printPlanId = tbSyncTask.getObjectId();
        try {
            // 同步中
            status = TaskStatusEnum.RUNNING;
            tbSyncTaskService.updateStatusAndResultById(tbSyncTask.getId(), null, status, null, null);

            // 同步计划 -> 同步到云阅卷考试
            thirdRelateId = saveExam(schoolId, printPlanId, thirdRelateId, thirdRelateName, examEndTime);
            syncStatus = ExamPrintPlanSyncStatusEnum.EXAM_FINISH;
            tbSyncTask.setThirdRelateId(thirdRelateId);
            // 考试同步成功，才能同步考生和题卡
            if (Objects.nonNull(thirdRelateId)) {
                updateWrapper.lambda().set(ExamPrintPlan::getThirdRelateId, thirdRelateId).set(ExamPrintPlan::getThirdRelateName, thirdRelateName);
                // 同步考生
                saveStudent(schoolId, printPlanId, thirdRelateId);
                syncStatus = ExamPrintPlanSyncStatusEnum.STUDENT_FINISH;
                // 同步题卡
                cardUpload(schoolId, printPlanId, thirdRelateId);
                syncStatus = ExamPrintPlanSyncStatusEnum.FINISH;
            } else {
                throw ExceptionResultEnum.ERROR.exception("无法获取云阅卷考试ID，同步数据失败");
            }
            // 任务结果
            result = TaskResultEnum.SUCCESS;
        } catch (Exception e) {
            result = TaskResultEnum.ERROR;
            errorMessage = e.getMessage();
        } finally {
            // 同步结束
            status = TaskStatusEnum.FINISH;

            tbSyncTaskService.updateStatusAndResultById(tbSyncTask.getId(), thirdRelateId, status, result, errorMessage);

            updateWrapper.lambda().set(ExamPrintPlan::getSyncStatus, syncStatus).eq(ExamPrintPlan::getId, printPlanId);
            examPrintPlanService.update(updateWrapper);
            // 同步成功，发送短信
            if (ExamPrintPlanSyncStatusEnum.FINISH.equals(syncStatus)) {
                examPrintPlanService.sendNoticeUploadStructure(printPlanId, sysUser);
            }
        }
    }

    @Async
    @Override
    public void syncPaperStructureAndGroup(ExamPaperStructure examPaperStructure, TBSyncTask tbSyncTask) {
        // 开始同步
        ExamPaperStructureStatusEnum structureStatus = ExamPaperStructureStatusEnum.INIT;
        // 同步初始参数
        TaskResultEnum result = null;
        String mainProgress = "<b>步骤：删除分组->主观题结构->主观题分组->绑定评卷员</b><br>";
        String errorMessage = "";
        try {
            String paperTypes = examPaperStructure.getPaperType();
            if (StringUtils.isBlank(paperTypes)) {
                throw ExceptionResultEnum.ERROR.exception("没有可同步的试卷类型");
            }

            Long schoolId = examPaperStructure.getSchoolId();
            // 云阅卷考试ID
            String examId = String.valueOf(examPaperStructure.getThirdRelateId());
            // 科目代码（课程代码+卷型+课程序号）
            String subjectCode = examPaperStructure.getCourseCode().concat(examPaperStructure.getPaperType()).concat(examPaperStructure.getSequence());

            // 同步中
            tbSyncTaskService.updateStatusAndResultById(tbSyncTask.getId(), examPaperStructure.getThirdRelateId(), TaskStatusEnum.RUNNING, null, null);

            // 同步分组（检查，若存在，先删除）
            errorMessage = "[删除分组]";
            int i = 0;
            deleteGroup(schoolId, examId, subjectCode, i);

            // 同步主观题
            errorMessage = "[主观题结构]";
            String subjectiveStructure = examPaperStructure.getSubjectiveStructure();
            if (StringUtils.isNotBlank(subjectiveStructure)) {
                List<JSONObject> subjectiveJsons = JSONObject.parseArray(subjectiveStructure, JSONObject.class);
                List<QuestionDTO> syncSubjectiveStructureDatas = subjectiveJsons.stream().map(m -> {
                    QuestionDTO syncStructureData = new QuestionDTO();
                    syncStructureData.setMainNumber(m.getInteger("mainNumber"));
                    syncStructureData.setSubNumber(m.getString("subNumber"));
                    syncStructureData.setMainTitle(m.getString("mainTitle"));
                    syncStructureData.setTotalScore(m.getDouble("totalScore"));
                    return syncStructureData;
                }).collect(Collectors.toList());

                cloudMarkingTaskUtils.syncPaperStructure(schoolId, examId, subjectCode, false, null, syncSubjectiveStructureDatas);
            }

            // 清掉云阅卷主观题答案
            String objectiveStructure = examPaperStructure.getObjectiveStructure();
            if (StringUtils.isNotBlank(objectiveStructure)) {
                List<JSONObject> objectiveJsons = JSONObject.parseArray(objectiveStructure, JSONObject.class);
                long count = objectiveJsons.stream().filter(m -> m.containsKey("answer")).count();
                if (objectiveJsons.size() == 0 || count == 0) {
                    List<QuestionDTO> syncObjectiveStructureDatas = new ArrayList<>();
                    cloudMarkingTaskUtils.syncPaperStructure(schoolId, examId, subjectCode, true, null, syncObjectiveStructureDatas);
                }
            }

            structureStatus = ExamPaperStructureStatusEnum.SUBJECTIVE_FINISH;

            errorMessage = "[主观题分组]";
            List<ExamPaperGroup> examPaperGroups = examPaperGroupService.listByExamPaperStructureId(examPaperStructure.getId());
            if (!CollectionUtils.isEmpty(examPaperGroups)) {
                List<GroupDetailDTO> groupDetailDTOS = new ArrayList<>();
                for (ExamPaperGroup examPaperGroup : examPaperGroups) {
                    GroupDetailDTO groupDetailDTO = new GroupDetailDTO();
                    groupDetailDTO.setNumber(examPaperGroup.getGroupNumber());
                    String picListString = examPaperGroup.getPictureConfig();
                    if (StringUtils.isNotBlank(picListString)) {
                        List<PicConfig> picConfigs = JSONObject.parseArray(picListString, PicConfig.class);
                        groupDetailDTO.setPicConfig(picConfigs);
                    }
                    groupDetailDTO.setDoubleRate(examPaperGroup.getDoubleRate());
                    groupDetailDTO.setArbitrateThreshold(examPaperGroup.getArbitrateThreshold());
                    groupDetailDTO.setScorePolicy(examPaperGroup.getScorePolicy().getValue());
//                    groupDetailDTO.setEnableAllZero();
//                    groupDetailDTO.setMarkMode(null);
                    String questionsString = examPaperGroup.getQuestionInfo();
                    if (StringUtils.isNotBlank(questionsString)) {
                        List<JSONObject> jsonObjects = JSONObject.parseArray(questionsString, JSONObject.class);
                        List<QuestionBaseDTO> questionBaseDTOS = jsonObjects.stream().map(m -> {
                            QuestionBaseDTO questionBaseDTO = new QuestionBaseDTO();
                            questionBaseDTO.setMainNumber(m.getInteger("mainNumber"));
                            questionBaseDTO.setSubNumber(m.getString("subNumber"));
                            return questionBaseDTO;
                        }).collect(Collectors.toList());
                        groupDetailDTO.setQuestions(questionBaseDTOS);
                    }
                    groupDetailDTOS.add(groupDetailDTO);
                }
                cloudMarkingTaskUtils.saveMarkerGroup(schoolId, examId, subjectCode, 0, groupDetailDTOS);
            }
            structureStatus = ExamPaperStructureStatusEnum.GROUP_FINISH;

            // 同步绑定评卷员
            errorMessage = "[绑定评卷员]";
            for (ExamPaperGroup examPaperGroup : examPaperGroups) {
                List<ExamPaperGroupMarker> examPaperGroupMarkers = examPaperGroupMarkerService.listByGroupId(examPaperGroup.getId());
                for (ExamPaperGroupMarker examPaperGroupMarker : examPaperGroupMarkers) {
                    cloudMarkingTaskUtils.saveMarker(schoolId, examId, subjectCode, examPaperGroup.getGroupNumber(), examPaperGroupMarker.getLoginName());
                }
            }
            structureStatus = ExamPaperStructureStatusEnum.FINISH;
            result = TaskResultEnum.SUCCESS;
        } catch (ApiException e) {
            result = TaskResultEnum.ERROR;
            errorMessage = errorMessage + e.getMessage();
        } finally {
            examPaperStructure.setStatus(structureStatus);
            examPaperStructureService.updateById(examPaperStructure);

            tbSyncTaskService.updateStatusAndResultById(tbSyncTask.getId(), examPaperStructure.getThirdRelateId(), TaskStatusEnum.FINISH, result, mainProgress + errorMessage);
        }
    }

    /**
     * 云阅卷分组删除是异步任务
     *
     * @param schoolId    学校ID
     * @param examId      考试ID
     * @param subjectCode 科目代码
     */
    private boolean deleteGroup(Long schoolId, String examId, String subjectCode, int i) {
        if (i >= 5) {
            throw ExceptionResultEnum.ERROR.exception("云阅卷分组未删除");
        }
        // 同步分组
        int countGroup = cloudMarkingTaskUtils.countGroup(schoolId, examId, subjectCode);
        // 如果存在分组，先删掉
        boolean deleteGroup = false;
        if (countGroup > 0) {
            // 第一次进行调用删除
            if (i == 0) {
                deleteGroup = cloudMarkingTaskUtils.deleteGroup(schoolId, examId, subjectCode);
            }
        } else {
            return true;
        }
        // 调用成功，再查询判断是否还有分组
        if (deleteGroup) {
            countGroup = cloudMarkingTaskUtils.countGroup(schoolId, examId, subjectCode);
            if (countGroup > 0) {
                // 等待3秒
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException ignored) {
                }
                i++;
                deleteGroup(schoolId, examId, subjectCode, i);
            }
        } else {
            throw ExceptionResultEnum.ERROR.exception("云阅卷分组删除异常");
        }
        return false;
    }

    @Async
    @Override
    public void syncPaperAndAnswer(ExamPaperStructure examPaperStructure, TBSyncTask tbSyncTask) {
        // 同步初始参数
        TaskResultEnum result = null;
        String errorMessage = null;
        try {
            Long schoolId = examPaperStructure.getSchoolId();
            // 云阅卷考试ID
            String examId = String.valueOf(examPaperStructure.getThirdRelateId());
            // 科目代码（课程代码+卷型+课程序号）
            String subjectCode = examPaperStructure.getCourseCode().concat(examPaperStructure.getPaperType()).concat(examPaperStructure.getSequence());

            // 同步中
            tbSyncTaskService.updateStatusAndResultById(tbSyncTask.getId(), examPaperStructure.getThirdRelateId(), TaskStatusEnum.RUNNING, null, null);

            String paperAnswer = examPaperStructure.getPaperAnswer();
            if (StringUtils.isNotBlank(paperAnswer)) {
                List<JSONObject> paperAnswerJsons = JSONObject.parseArray(paperAnswer, JSONObject.class);
                for (JSONObject paperAnswerJson : paperAnswerJsons) {
                    if (paperAnswerJson.containsKey("paperType") && paperAnswerJson.containsKey("paper")) {
                        String paperType = paperAnswerJson.getString("paperType");
                        // 同步试卷
                        String paper = paperAnswerJson.getString("paper");
                        if (StringUtils.isAnyBlank(paperType, paper)) {
                            continue;
                        }
                        // 同步试卷文件
                        File paperFile = downFileFromFss(paper, paperType, SyncFileTypeEnum.PAPER);
                        String syncPaperFileUrl = cloudMarkingTaskUtils.syncFile(schoolId, examId, subjectCode, SyncFileTypeEnum.PAPER, paperFile);
                        // 试卷文件保存url
                        paperAnswerJson.put("paperUrl", syncPaperFileUrl);

                        // 同步标答
                        String answer = paperAnswerJson.getString("answer");
                        if (StringUtils.isAnyBlank(paperType, answer)) {
                            continue;
                        }
                        // 同步标答文件
                        File answerFile = downFileFromFss(answer, paperType, SyncFileTypeEnum.ANSWER);
                        String syncAnswerFileUrl = cloudMarkingTaskUtils.syncFile(schoolId, examId, subjectCode, SyncFileTypeEnum.ANSWER, answerFile);
                        // 标答文件保存url
                        paperAnswerJson.put("answerUrl", syncAnswerFileUrl);
                    }
                }
                String paperAnswerUrl = JSONObject.toJSONString(paperAnswerJsons);

                // 更新url
                UpdateWrapper<ExamPaperStructure> updateWrapper = new UpdateWrapper<>();
                updateWrapper.lambda().set(ExamPaperStructure::getPaperAnswer, paperAnswerUrl).eq(ExamPaperStructure::getId, examPaperStructure.getId());
                examPaperStructureService.update(updateWrapper);
            }

            result = TaskResultEnum.SUCCESS;
        } catch (ApiException e) {
            result = TaskResultEnum.ERROR;
            errorMessage = e.getMessage();
        } finally {
            tbSyncTaskService.updateStatusAndResultById(tbSyncTask.getId(), examPaperStructure.getThirdRelateId(), TaskStatusEnum.FINISH, result, errorMessage);
        }
    }

    @Async
    @Override
    public void syncObjectiveStructure(ExamPaperStructure examPaperStructure, TBSyncTask tbSyncTask) {
        // 同步初始参数
        TaskResultEnum result = null;
        String errorMessage = null;
        try {
            Long schoolId = examPaperStructure.getSchoolId();
            // 云阅卷考试ID
            String examId = String.valueOf(examPaperStructure.getThirdRelateId());
            // 科目代码（课程代码+卷型+课程序号）
            String subjectCode = examPaperStructure.getCourseCode().concat(examPaperStructure.getPaperType()).concat(examPaperStructure.getSequence());
            // 同步客观题
            String objectiveStructure = examPaperStructure.getObjectiveStructure();
            if (StringUtils.isNotBlank(objectiveStructure)) {
                List<JSONObject> objectiveJsons = JSONObject.parseArray(objectiveStructure, JSONObject.class);
                List<QuestionDTO> syncObjectiveStructureDatas = objectiveJsons.stream().map(m -> {
                    QuestionDTO syncStructureData = new QuestionDTO();
                    syncStructureData.setMainNumber(m.getInteger("mainNumber"));
                    syncStructureData.setSubNumber(m.getString("subNumber"));
                    syncStructureData.setMainTitle(m.getString("mainTitle"));
                    syncStructureData.setTotalScore(m.getDouble("totalScore"));
                    syncStructureData.setAnswer(m.getString("answer"));
                    return syncStructureData;
                }).collect(Collectors.toList());
                cloudMarkingTaskUtils.syncPaperStructure(schoolId, examId, subjectCode, true, null, syncObjectiveStructureDatas);
            }

            result = TaskResultEnum.SUCCESS;
        } catch (ApiException e) {
            result = TaskResultEnum.ERROR;
            errorMessage = e.getMessage();
        } finally {
            tbSyncTaskService.updateStatusAndResultById(tbSyncTask.getId(), examPaperStructure.getThirdRelateId(), TaskStatusEnum.FINISH, result, errorMessage);
        }
    }

    /**
     * 创建考试
     *
     * @param schoolId        学校ID
     * @param printPlanId     计划ID
     * @param thirdRelateId   云阅卷考试ID
     * @param thirdRelateName 云阅卷考试名称
     * @param examEndTime     考试时间
     */
    public Long saveExam(Long schoolId, Long printPlanId, Long thirdRelateId, String thirdRelateName, Long examEndTime) {
        try {
            if (Objects.isNull(thirdRelateId)) {
                String code = String.valueOf(printPlanId);
                String examTime = DateUtil.format(new Date(examEndTime), CloudMarkingTaskUtils.DATE_FORMAT);
                thirdRelateId = cloudMarkingTaskUtils.syncExam(schoolId, code, thirdRelateName, examTime);
            }
            return thirdRelateId;
        } catch (Exception e) {
            throw ExceptionResultEnum.ERROR.exception(e.getMessage());
        }
    }

    /**
     * 新增考生
     *
     * @param schoolId        学校ID
     * @param examPrintPlanId 计划ID
     * @param thirdRelateId   云阅卷考试ID
     */
    public void saveStudent(Long schoolId, Long examPrintPlanId, Long thirdRelateId) {
        List<SyncExamStudentDto> examStudents = examStudentService.listStudentByPrintPlanIdAndSyncStatus(examPrintPlanId);
        for (SyncExamStudentDto examStudent : examStudents) {
            try {
                //参数
                String examId = String.valueOf(thirdRelateId);
                String examNumber = examStudent.getTicketNumber();
                String studentCode = examStudent.getStudentCode();
                String name = examStudent.getStudentName();
                SysOrg sysOrg = examStudentService.getSysOrgByBelongOrgId(studentCode, schoolId);
                String college = Objects.nonNull(sysOrg) && StringUtils.isNotBlank(sysOrg.getName()) ? sysOrg.getName() : "无";
                String className = StringUtils.isBlank(examStudent.getClazzName()) ? getClassName(examStudent.getExtendFields()) : examStudent.getClazzName();
                String teacher = "无";
                String subjectCode = examStudent.getCourseCode() + examStudent.getPaperType() + examStudent.getSequence(); // 取试卷编号
                String subjectName = examStudent.getCourseName();
                boolean syncStudent = cloudMarkingTaskUtils.syncStudent(schoolId, examId, examNumber, studentCode, name, college, className, teacher, subjectCode, subjectName, null, null, null, null);

                if (syncStudent) {
                    UpdateWrapper<ExamStudent> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.lambda().set(ExamStudent::getSyncStatus, true).eq(ExamStudent::getId, examStudent.getId());
                    examStudentService.update(updateWrapper);
                }
            } catch (Exception e) {
                throw ExceptionResultEnum.ERROR.exception(e.getMessage());
            }
        }
    }

    /**
     * 同步题卡
     *
     * @param schoolId        学校ID
     * @param examPrintPlanId 计划ID
     * @param thirdRelateId   云阅卷考试ID
     */
    public void cardUpload(Long schoolId, Long examPrintPlanId, Long thirdRelateId) {
        List<ExamDetailCourse> examDetailCourses = examDetailService.listSyncPaperNumberByPrintPlanId(examPrintPlanId);
        if (CollectionUtils.isEmpty(examDetailCourses)) {
            return;
        }
        for (ExamDetailCourse examDetailCours : examDetailCourses) {
            List<SyncExamCardDto> syncExamCardDtos = examCardService.listSyncCardByCourseCodeAndPaperNumber(examDetailCours.getSchoolId(), examDetailCours.getCourseCode(), examDetailCours.getPaperNumber());
            if (CollectionUtils.isEmpty(syncExamCardDtos)) {
                return;
            }
            if (syncExamCardDtos.size() > 1) {
                log.info("数据异常，通过学校：{},课程代码：{},试卷编号：{}查出{}个题卡数据", examDetailCours.getSchoolId(), examDetailCours.getCourseCode(), examDetailCours.getPaperNumber(), syncExamCardDtos.size());
                return;
            }
            String paperType = examDetailCours.getPaperType();
            if (StringUtils.isBlank(paperType)) {
                log.info("数据异常，通过学校：{},课程代码：{},试卷编号：{}查出绑定试卷类型为空", examDetailCours.getSchoolId(), examDetailCours.getCourseCode(), examDetailCours.getPaperNumber());
                return;
            }
            SyncExamCardDto syncExamCardDto = syncExamCardDtos.get(0);
            if (StringUtils.isNotEmpty(syncExamCardDto.getContent())) {
                for (String s : paperType.split(",")) {
                    //生成json文件
                    File file = null;
                    try {
                        // 文件临时目录
                        String filePath = getTempDir(SyncFileTypeEnum.CARD);
                        file = createJsonFile(filePath, syncExamCardDto.getContent());
                        if (file.exists()) {
                            String uploadCardUrl = cloudMarkingTaskUtils.syncFile(schoolId, String.valueOf(thirdRelateId), syncExamCardDto.getCourseCode() + s + syncExamCardDto.getSequence(), SyncFileTypeEnum.CARD, file);
                            if (StringUtils.isNotBlank(uploadCardUrl)) {
                                UpdateWrapper<ExamCard> updateWrapper = new UpdateWrapper<>();
                                updateWrapper.lambda().set(ExamCard::getSyncStatus, true).eq(ExamCard::getId, syncExamCardDto.getId());
                                examCardService.update(updateWrapper);
                            }
                        }
                    } catch (Exception e) {
                        throw ExceptionResultEnum.ERROR.exception(e.getMessage());
                    } finally {
                        if (Objects.nonNull(dictionaryConfig.sysDomain()) && dictionaryConfig.sysDomain().isOss()) {
                            if (file != null && file.exists()) {
                                file.delete();
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 上传文件临时目录
     *
     * @param type 同步类型
     */
    private String getTempDir(SyncFileTypeEnum type) {
        return SystemConstant.TEMP_FILES_DIR + File.separator + "upload-temp" + File.separator + type.name().toLowerCase() + File.separator + System.currentTimeMillis();
    }

    /**
     * 通过扩展字段，获取班级名称
     *
     * @param extendColumn 扩展字段
     */
    private String getClassName(String extendColumn) {
        List<Map> mapList = JSONObject.parseArray(extendColumn, Map.class);
        for (Map map : mapList) {
            if (Objects.equals("className", map.get("code").toString())
                    || Objects.equals("clazzName", map.get("code").toString())) {
                return map.get("value").toString();
            }
        }
        return "无";
    }

    /**
     * 生成文件
     *
     * @param url     文件路径+文件名称
     * @param content 要生成的文件内容
     */
    public static File createJsonFile(String url, String content) {

        File file = new File(url);
        if (!file.exists()) {
            file.mkdirs();
        }
        BufferedWriter out = null;
        file = new File(file, UUID.randomUUID().toString() + ".json");
        try {
            file.createNewFile();
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
            out.write(content);
        } catch (Exception e) {
        } finally {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
        return file;
    }

    /**
     * 下载附件临时文件
     *
     * @param attachmentId 附件ID
     * @param name         文件名称
     * @param type         文件类型
     */
    private File downFileFromFss(String attachmentId, String name, SyncFileTypeEnum type) {
        try {
            if (Objects.nonNull(attachmentId)) {
                BasicAttachment attachment = basicAttachmentService.getById(attachmentId);
                if (attachment == null) {
                    throw ExceptionResultEnum.ERROR.exception("附件数据异常");
                }
                String fileName = attachment.getName() + "-" + name + attachment.getType();
                return teachcloudCommonService.copyFile(getTempDir(type), fileName, attachment);
            }
        } catch (Exception e) {
            throw ExceptionResultEnum.ERROR.exception(e.getMessage());
        }
        return null;
    }
}
