package com.yunzhupaas.service.impl;

import com.yunzhupaas.base.ActionResult;
import com.yunzhupaas.dto.OnlineExamSubmitDTO;
import com.yunzhupaas.entity.*;
import com.yunzhupaas.mapper.TrainTestPaperLibraryMapper;
import com.yunzhupaas.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunzhupaas.model.traintestpaperlibrary.*;
import org.springframework.stereotype.Service;
import com.yunzhupaas.base.service.SuperServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import com.yunzhupaas.util.GeneraterSwapUtil;

import java.sql.Connection;
import java.sql.SQLException;

import lombok.Cleanup;
import com.yunzhupaas.database.plugins.DynamicSourceGeneratorInterface;
import com.yunzhupaas.database.util.DynamicDataSourceUtil;
import org.apache.commons.collections4.CollectionUtils;
import com.yunzhupaas.i18n.util.I18nUtil;
import com.yunzhupaas.exception.DataException;

import java.math.BigDecimal;

import cn.hutool.core.util.ObjectUtil;

import java.lang.reflect.Field;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;

import java.util.regex.Pattern;
import java.util.stream.Collectors;

import com.yunzhupaas.base.model.ColumnDataModel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.yunzhupaas.model.QueryAllModel;

import java.text.SimpleDateFormat;

import com.yunzhupaas.util.*;

import java.util.*;

import com.yunzhupaas.base.UserInfo;
import com.yunzhupaas.permission.entity.UserEntity;
import com.github.pagehelper.PageHelper;

/**
 * 在线考试
 * 版本： V5.2.0
 * 版权： Copyright @ 2025
 * 作者： 浙江尖峰集团股份有限公司
 * 日期： 2024-11-05
 */
@Service
public class TrainTestPaperLibraryServiceImpl
        extends SuperServiceImpl<TrainTestPaperLibraryMapper, TrainTestPaperLibraryEntity>
        implements TrainTestPaperLibraryService {
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private TrainTestPaperLibraryMapper trainTestPaperLibraryMapper;
    @Autowired
    private TrainLibrarySingleService trainLibrarySingleService;
    @Autowired
    private TrainLibraryMoreService trainLibraryMoreService;
    @Autowired
    private TrainLibraryJudgmentService trainLibraryJudgmentService;
    @Autowired
    private TrainLibraryEssayQuestionService trainLibraryEssayQuestionService;

    @Override
    public List<TrainTestPaperLibraryEntity> getList(TrainTestPaperLibraryPagination trainTestPaperLibraryPagination) {
        return getTypeList(trainTestPaperLibraryPagination, trainTestPaperLibraryPagination.getDataType());
    }

    /**
     * 列表查询
     */
    @Override
    public List<TrainTestPaperLibraryEntity> getTypeList(
            TrainTestPaperLibraryPagination trainTestPaperLibraryPagination, String dataType) {
        String userId = userProvider.get().getUserId();
        Map<String, Class> tableClassMap = new HashMap<>();
        tableClassMap.put("make_train_test_paper_library", TrainTestPaperLibraryEntity.class);
        tableClassMap.put("make_train_library_essay_question", TrainLibraryEssayQuestionEntity.class);
        tableClassMap.put("make_train_library_judgment", TrainLibraryJudgmentEntity.class);
        tableClassMap.put("make_train_library_more", TrainLibraryMoreEntity.class);
        tableClassMap.put("make_train_library_single", TrainLibrarySingleEntity.class);

        MPJLambdaWrapper<TrainTestPaperLibraryEntity> wrapper = JoinWrappers
                .lambda("make_train_test_paper_library", TrainTestPaperLibraryEntity.class)
                .selectCollection(TrainLibraryEssayQuestionEntity.class,
                        TrainTestPaperLibraryEntity::getTrainLibraryEssayQuestion)
                .leftJoin(TrainLibraryEssayQuestionEntity.class, "make_train_library_essay_question",
                        TrainLibraryEssayQuestionEntity::getFbankId, TrainTestPaperLibraryEntity::getId)
                .selectCollection(TrainLibraryJudgmentEntity.class,
                        TrainTestPaperLibraryEntity::getTrainLibraryJudgment)
                .leftJoin(TrainLibraryJudgmentEntity.class, "make_train_library_judgment",
                        TrainLibraryJudgmentEntity::getFbankId, TrainTestPaperLibraryEntity::getId)
                .selectCollection(TrainLibraryMoreEntity.class, TrainTestPaperLibraryEntity::getTrainLibraryMore)
                .leftJoin(TrainLibraryMoreEntity.class, "make_train_library_more", TrainLibraryMoreEntity::getFbankId,
                        TrainTestPaperLibraryEntity::getId)
                .selectCollection(TrainLibrarySingleEntity.class, TrainTestPaperLibraryEntity::getTrainLibrarySingle)
                .leftJoin(TrainLibrarySingleEntity.class, "make_train_library_single",
                        TrainLibrarySingleEntity::getFbankId, TrainTestPaperLibraryEntity::getId)
                .selectAll(TrainTestPaperLibraryEntity.class);
        MPJLambdaWrapper<TrainTestPaperLibraryEntity> wrapper2 = JoinWrappers
                .lambda("make_train_test_paper_library", TrainTestPaperLibraryEntity.class)
                .leftJoin(TrainLibraryEssayQuestionEntity.class, "make_train_library_essay_question",
                        TrainLibraryEssayQuestionEntity::getFbankId, TrainTestPaperLibraryEntity::getId)
                .leftJoin(TrainLibraryJudgmentEntity.class, "make_train_library_judgment",
                        TrainLibraryJudgmentEntity::getFbankId, TrainTestPaperLibraryEntity::getId)
                .leftJoin(TrainLibraryMoreEntity.class, "make_train_library_more", TrainLibraryMoreEntity::getFbankId,
                        TrainTestPaperLibraryEntity::getId)
                .leftJoin(TrainLibrarySingleEntity.class, "make_train_library_single",
                        TrainLibrarySingleEntity::getFbankId, TrainTestPaperLibraryEntity::getId)
                .distinct().select(TrainTestPaperLibraryEntity::getId);

        QueryAllModel queryAllModel = new QueryAllModel();
        queryAllModel.setWrapper(wrapper);
        queryAllModel.setClassMap(tableClassMap);
        queryAllModel.setDbLink(TrainTestPaperLibraryConstant.DBLINKID);
        // 数据过滤
        boolean isPc = ServletUtil.getHeader("yunzhupaas-origin").equals("pc");
        String columnData = !isPc ? TrainTestPaperLibraryConstant.getAppColumnData()
                : TrainTestPaperLibraryConstant.getColumnData();
        ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(columnData, ColumnDataModel.class);
        String ruleJson = !isPc ? JsonUtil.getObjectToString(columnDataModel.getRuleListApp())
                : JsonUtil.getObjectToString(columnDataModel.getRuleList());
        queryAllModel.setRuleJson(ruleJson);
        // 高级查询
        boolean hasSuperQuery = true;
        if (hasSuperQuery) {
            queryAllModel.setSuperJson(trainTestPaperLibraryPagination.getSuperQueryJson());
        }
        // 数据权限
        boolean pcPermission = true;
        boolean appPermission = false;
        if (isPc && pcPermission && !userProvider.get().getIsAdministrator()) {
            queryAllModel.setModuleId(trainTestPaperLibraryPagination.getMenuId());
            queryAllModel.setModuleId(trainTestPaperLibraryPagination.getMenuId());
        }
        if (!isPc && appPermission && !userProvider.get().getIsAdministrator()) {
            queryAllModel.setModuleId(trainTestPaperLibraryPagination.getMenuId());
        }
        // 拼接复杂条件
        wrapper = generaterSwapUtil.getConditionAllTable(queryAllModel);
        queryAllModel.setWrapper(wrapper2);
        wrapper2 = generaterSwapUtil.getConditionAllTable(queryAllModel);
        // 其他条件拼接
        otherConditions(trainTestPaperLibraryPagination, wrapper, isPc);
        otherConditions(trainTestPaperLibraryPagination, wrapper2, isPc);

        if ("0".equals(dataType)) {
            com.github.pagehelper.Page<Object> objects = PageHelper.startPage(
                    (int) trainTestPaperLibraryPagination.getCurrentPage(),
                    (int) trainTestPaperLibraryPagination.getPageSize(), true);
            List<TrainTestPaperLibraryEntity> userIPage = this.selectJoinList(TrainTestPaperLibraryEntity.class,
                    wrapper2);
            List<Object> collect = userIPage.stream().map(t -> t.getId()).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                wrapper.in(TrainTestPaperLibraryEntity::getId, collect);
            }
            List<TrainTestPaperLibraryEntity> result = this.selectJoinList(TrainTestPaperLibraryEntity.class, wrapper);
            return trainTestPaperLibraryPagination.setData(result, objects.getTotal());
        } else {
            List<TrainTestPaperLibraryEntity> list = this.selectJoinList(TrainTestPaperLibraryEntity.class, wrapper);
            if ("2".equals(dataType)) {
                List<String> selectIds = Arrays.asList(trainTestPaperLibraryPagination.getSelectIds());
                return list.stream().filter(t -> selectIds.contains(t.getId().toString())).collect(Collectors.toList());
            } else {
                return list;
            }
        }

    }

    /**
     * 其他条件拼接
     */
    private void otherConditions(TrainTestPaperLibraryPagination trainTestPaperLibraryPagination,
            MPJLambdaWrapper<TrainTestPaperLibraryEntity> wrapper, boolean isPc) {
        String databaseName;
        try {
            @Cleanup
            Connection cnn = DynamicDataSourceUtil.getCurrentConnection();
            databaseName = cnn.getMetaData().getDatabaseProductName().trim();
        } catch (SQLException e) {
            throw new DataException(e.getMessage());
        }
        wrapper.isNull(TrainTestPaperLibraryEntity::getFlowId);
        // 关键词
        if (ObjectUtil.isNotEmpty(trainTestPaperLibraryPagination.getYunzhupaasKeyword())) {
        }
        // 普通查询
        if (isPc) {
            if (ObjectUtil.isNotEmpty(trainTestPaperLibraryPagination.getFfullName())) {
                String value = trainTestPaperLibraryPagination.getFfullName() instanceof List
                        ? JsonUtil.getObjectToString(trainTestPaperLibraryPagination.getFfullName())
                        : String.valueOf(trainTestPaperLibraryPagination.getFfullName());
                wrapper.like(TrainTestPaperLibraryEntity::getFfullName, value);
            }

            if (ObjectUtil.isNotEmpty(trainTestPaperLibraryPagination.getFsort())) {
                List<String> idList = new ArrayList<>();
                try {
                    String[][] fsort = JsonUtil.getJsonToBean(trainTestPaperLibraryPagination.getFsort(),
                            String[][].class);
                    for (int i = 0; i < fsort.length; i++) {
                        if (fsort[i].length > 0) {
                            idList.add(JsonUtil.getObjectToString(Arrays.asList(fsort[i])));
                        }
                    }
                } catch (Exception e1) {
                    try {
                        List<String> fsort = JsonUtil.getJsonToList(trainTestPaperLibraryPagination.getFsort(),
                                String.class);
                        if (fsort.size() > 0) {
                            idList.addAll(fsort);
                        }
                    } catch (Exception e2) {
                        idList.add(String.valueOf(trainTestPaperLibraryPagination.getFsort()));
                    }
                }
                wrapper.and(t -> {
                    idList.forEach(tt -> {
                        if (StringUtil.isNotEmpty(tt) && "Microsoft SQL Server".equalsIgnoreCase(databaseName)) {
                            tt = tt.replaceFirst("\\[", "[[]");
                        }
                        t.like(TrainTestPaperLibraryEntity::getFsort, tt).or();
                    });
                });
            }

        }
        // 排序
        if (StringUtil.isEmpty(trainTestPaperLibraryPagination.getSidx())) {
            wrapper.orderByDesc(TrainTestPaperLibraryEntity::getId);
        } else {
            try {
                String[] split = trainTestPaperLibraryPagination.getSidx().split(",");
                for (String sidx : split) {
                    TrainTestPaperLibraryEntity trainTestPaperLibraryEntity = new TrainTestPaperLibraryEntity();
                    String oderTableField = trainTestPaperLibraryEntity.getClass().getAnnotation(TableName.class)
                            .value();
                    if (sidx.startsWith("-")) {
                        Field declaredField = trainTestPaperLibraryEntity.getClass()
                                .getDeclaredField(sidx.substring(1));
                        declaredField.setAccessible(true);
                        oderTableField = oderTableField + "." + declaredField.getAnnotation(TableField.class).value();
                        wrapper.select(oderTableField);
                        wrapper.orderByDesc(oderTableField);
                    } else {
                        Field declaredField = trainTestPaperLibraryEntity.getClass().getDeclaredField(sidx);
                        declaredField.setAccessible(true);
                        oderTableField = oderTableField + "." + declaredField.getAnnotation(TableField.class).value();
                        wrapper.select(oderTableField);
                        wrapper.orderByAsc(oderTableField);
                    }
                }
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public TrainTestPaperLibraryEntity getInfo(String id) {
        MPJLambdaWrapper<TrainTestPaperLibraryEntity> wrapper = JoinWrappers
                .lambda("make_train_test_paper_library", TrainTestPaperLibraryEntity.class)
                .selectCollection(TrainLibraryEssayQuestionEntity.class,
                        TrainTestPaperLibraryEntity::getTrainLibraryEssayQuestion)
                .leftJoin(TrainLibraryEssayQuestionEntity.class, "make_train_library_essay_question",
                        TrainLibraryEssayQuestionEntity::getFbankId, TrainTestPaperLibraryEntity::getId)
                .selectCollection(TrainLibraryJudgmentEntity.class,
                        TrainTestPaperLibraryEntity::getTrainLibraryJudgment)
                .leftJoin(TrainLibraryJudgmentEntity.class, "make_train_library_judgment",
                        TrainLibraryJudgmentEntity::getFbankId, TrainTestPaperLibraryEntity::getId)
                .selectCollection(TrainLibraryMoreEntity.class, TrainTestPaperLibraryEntity::getTrainLibraryMore)
                .leftJoin(TrainLibraryMoreEntity.class, "make_train_library_more", TrainLibraryMoreEntity::getFbankId,
                        TrainTestPaperLibraryEntity::getId)
                .selectCollection(TrainLibrarySingleEntity.class, TrainTestPaperLibraryEntity::getTrainLibrarySingle)
                .leftJoin(TrainLibrarySingleEntity.class, "make_train_library_single",
                        TrainLibrarySingleEntity::getFbankId, TrainTestPaperLibraryEntity::getId)
                .selectAll(TrainTestPaperLibraryEntity.class);
        wrapper.and(
                t -> t.eq(TrainTestPaperLibraryEntity::getId, id)
                        .or().eq(TrainTestPaperLibraryEntity::getFlowTaskId, id));
        return this.selectJoinOne(TrainTestPaperLibraryEntity.class, wrapper);
    }

    @Override
    public void create(TrainTestPaperLibraryEntity entity) {
        this.save(entity);
    }

    @Override
    public boolean update(String id, TrainTestPaperLibraryEntity entity) {
        return this.updateById(entity);
    }

    @Override
    public void delete(TrainTestPaperLibraryEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }
    }

    /**
     * 验证表单唯一字段，正则，非空 i-0新增-1修改
     */
    @Override
    public String checkForm(TrainTestPaperLibraryForm form, int i) {
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        Object id = null;
        String countRecover = "";
        String fieldTipName = "";
        String canNotNull = I18nUtil.getMessageStr("sys.validate.textRequiredSuffix", "不能为空");
        String canNotRepeated = I18nUtil.getMessageStr("EXIST103", "不能重复");
        if (isUp) {
            id = form.getId();
        }
        // 主表字段验证
        fieldTipName = "试卷名称";
        if (StringUtil.isEmpty(form.getFfullName())) {
            return fieldTipName + canNotNull;
        }
        fieldTipName = "试题分类";
        fieldTipName = "创建用户";
        fieldTipName = "创建时间";
        fieldTipName = "修改用户";
        fieldTipName = "修改时间";
        fieldTipName = "所属组织";
        // 子表字段验证
        if (form.getTrainLibrarySingleList() != null) {

            fieldTipName = "单选题"
                    + "-" + "题目难度";

            fieldTipName = "单选题"
                    + "-" + "分类";

            fieldTipName = "单选题"
                    + "-" + "题目名称";

            fieldTipName = "单选题"
                    + "-" + "解析";

            fieldTipName = "单选题"
                    + "-" + "答案";

            fieldTipName = "单选题"
                    + "-" + "题目类型";

            fieldTipName = "单选题"
                    + "-" + "选项A";

            fieldTipName = "单选题"
                    + "-" + "选项B";

            fieldTipName = "单选题"
                    + "-" + "选项C";

            fieldTipName = "单选题"
                    + "-" + "选项D";

            fieldTipName = "单选题"
                    + "-" + "所属组织";

            fieldTipName = "单选题"
                    + "-" + "修改时间";

            fieldTipName = "单选题"
                    + "-" + "修改用户";

            fieldTipName = "单选题"
                    + "-" + "创建时间";

            fieldTipName = "单选题"
                    + "-" + "创建用户";

        }
        if (form.getTrainLibraryMoreList() != null) {

            fieldTipName = "多选题"
                    + "-" + "题目难度";

            fieldTipName = "多选题"
                    + "-" + "分类";

            fieldTipName = "多选题"
                    + "-" + "题目名称";

            fieldTipName = "多选题"
                    + "-" + "解析";

            fieldTipName = "多选题"
                    + "-" + "答案";

            fieldTipName = "多选题"
                    + "-" + "题目类型";

            fieldTipName = "多选题"
                    + "-" + "选项A";

            fieldTipName = "多选题"
                    + "-" + "选项B";

            fieldTipName = "多选题"
                    + "-" + "选项C";

            fieldTipName = "多选题"
                    + "-" + "选项D";

            fieldTipName = "多选题"
                    + "-" + "所属组织";

            fieldTipName = "多选题"
                    + "-" + "修改时间";

            fieldTipName = "多选题"
                    + "-" + "修改用户";

            fieldTipName = "多选题"
                    + "-" + "创建时间";

            fieldTipName = "多选题"
                    + "-" + "创建用户";

        }
        if (form.getTrainLibraryJudgmentList() != null) {

            fieldTipName = "判断题"
                    + "-" + "题目难度";

            fieldTipName = "判断题"
                    + "-" + "分类";

            fieldTipName = "判断题"
                    + "-" + "题目名称";

            fieldTipName = "判断题"
                    + "-" + "解析";

            fieldTipName = "判断题"
                    + "-" + "答案";

            fieldTipName = "判断题"
                    + "-" + "题目类型";

            fieldTipName = "判断题"
                    + "-" + "所属组织";

            fieldTipName = "判断题"
                    + "-" + "修改时间";

            fieldTipName = "判断题"
                    + "-" + "修改用户";

            fieldTipName = "判断题"
                    + "-" + "创建时间";

            fieldTipName = "判断题"
                    + "-" + "创建用户";

        }
        if (form.getTrainLibraryEssayQuestionList() != null) {

            fieldTipName = "问答题"
                    + "-" + "题目难度";

            fieldTipName = "问答题"
                    + "-" + "分类";

            fieldTipName = "问答题"
                    + "-" + "题目名称";

            fieldTipName = "问答题"
                    + "-" + "解析";

            fieldTipName = "问答题"
                    + "-" + "答案";

            fieldTipName = "问答题"
                    + "-" + "题目类型";

            fieldTipName = "问答题"
                    + "-" + "所属组织";

            fieldTipName = "问答题"
                    + "-" + "修改时间";

            fieldTipName = "问答题"
                    + "-" + "修改用户";

            fieldTipName = "问答题"
                    + "-" + "创建时间";

            fieldTipName = "问答题"
                    + "-" + "创建用户";

        }
        return countRecover;
    }

    /**
     * 新增修改数据(事务回滚)
     *
     * @param id
     * @param trainTestPaperLibraryForm
     * @return
     */
    @Override
    @Transactional
    public void saveOrUpdate(TrainTestPaperLibraryForm trainTestPaperLibraryForm, String id, boolean isSave)
            throws Exception {
        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        trainTestPaperLibraryForm = JsonUtil.getJsonToBean(
                generaterSwapUtil.swapDatetime(TrainTestPaperLibraryConstant.getFormData(), trainTestPaperLibraryForm,
                        TrainTestPaperLibraryConstant.TABLERENAMES),
                TrainTestPaperLibraryForm.class);
        TrainTestPaperLibraryEntity entity = JsonUtil.getJsonToBean(trainTestPaperLibraryForm,
                TrainTestPaperLibraryEntity.class);
        String mainUuid = StringUtil.isEmpty(id) ? RandomUtil.uuId() : id;
        if (isSave) {
            entity.setFlowTaskId(mainUuid);
            entity.setFcreatorUserId(userInfo.getUserId());
            entity.setFcreatorTime(DateUtil.getNowDate());
            entity.setFlastModifyUserId(null);
            entity.setFlastModifyTime(null);
            entity.setForganizeId(generaterSwapUtil.getCurrentOrgIds(userInfo.getOrganizeId(), "last"));
            entity.setId(mainUuid);
        } else {
            entity.setFcreatorUserId(null);
            entity.setFcreatorTime(null);
            entity.setFlastModifyUserId(userInfo.getUserId());
            entity.setFlastModifyTime(DateUtil.getNowDate());
            entity.setForganizeId(null);
        }
        this.saveOrUpdate(entity);

        // TrainLibrarySingle子表数据新增修改
        QueryWrapper<TrainLibrarySingleEntity> TrainLibrarySinglequeryWrapper = new QueryWrapper<>();
        TrainLibrarySinglequeryWrapper.lambda().eq(TrainLibrarySingleEntity::getFbankId, entity.getId());
        if (!isSave && !CollectionUtils.isNotEmpty(trainTestPaperLibraryForm.getTrainLibrarySingleList())) {
            trainLibrarySingleService.remove(TrainLibrarySinglequeryWrapper);
        }
        if (CollectionUtils.isNotEmpty(trainTestPaperLibraryForm.getTrainLibrarySingleList())) {
            List<TrainLibrarySingleEntity> tableField103 = JsonUtil.getJsonToList(
                    trainTestPaperLibraryForm.getTrainLibrarySingleList(), TrainLibrarySingleEntity.class);
            // 移除的数据
            List<Object> childIds = tableField103.stream().filter(t -> t.getId() != null)
                    .map(TrainLibrarySingleEntity::getId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(childIds)) {
                TrainLibrarySinglequeryWrapper.lambda().notIn(TrainLibrarySingleEntity::getId, childIds);
            }
            trainLibrarySingleService.remove(TrainLibrarySinglequeryWrapper);
            for (TrainLibrarySingleEntity entitys : tableField103) {
                entitys.setFbankId(entity.getId());
                if (isSave || entitys.getId() == null) {
                    entitys.setForganizeId(generaterSwapUtil.getCurrentOrgIds(userInfo.getOrganizeId(), "last"));
                    entitys.setFlastModifyTime(null);
                    entitys.setFlastModifyUserId(null);
                    entitys.setFcreatorTime(DateUtil.getNowDate());
                    entitys.setFcreatorUserId(userInfo.getUserId());
                } else {
                    entitys.setForganizeId(null);
                    entitys.setFlastModifyTime(DateUtil.getNowDate());
                    entitys.setFlastModifyUserId(userInfo.getUserId());
                    entitys.setFcreatorTime(null);
                    entitys.setFcreatorUserId(null);
                }
                if (entitys.getId() == null) {
                    entitys.setId(RandomUtil.uuId());
                }
                trainLibrarySingleService.saveOrUpdate(entitys);
            }
        }
        // TrainLibraryMore子表数据新增修改
        QueryWrapper<TrainLibraryMoreEntity> TrainLibraryMorequeryWrapper = new QueryWrapper<>();
        TrainLibraryMorequeryWrapper.lambda().eq(TrainLibraryMoreEntity::getFbankId, entity.getId());
        if (!isSave && !CollectionUtils.isNotEmpty(trainTestPaperLibraryForm.getTrainLibraryMoreList())) {
            trainLibraryMoreService.remove(TrainLibraryMorequeryWrapper);
        }
        if (CollectionUtils.isNotEmpty(trainTestPaperLibraryForm.getTrainLibraryMoreList())) {
            List<TrainLibraryMoreEntity> tableField131 = JsonUtil
                    .getJsonToList(trainTestPaperLibraryForm.getTrainLibraryMoreList(), TrainLibraryMoreEntity.class);
            // 移除的数据
            List<Object> childIds = tableField131.stream().filter(t -> t.getId() != null)
                    .map(TrainLibraryMoreEntity::getId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(childIds)) {
                TrainLibraryMorequeryWrapper.lambda().notIn(TrainLibraryMoreEntity::getId, childIds);
            }
            trainLibraryMoreService.remove(TrainLibraryMorequeryWrapper);
            for (TrainLibraryMoreEntity entitys : tableField131) {
                entitys.setFbankId(entity.getId());
                if (isSave || entitys.getId() == null) {
                    entitys.setForganizeId(generaterSwapUtil.getCurrentOrgIds(userInfo.getOrganizeId(), "last"));
                    entitys.setFlastModifyTime(null);
                    entitys.setFlastModifyUserId(null);
                    entitys.setFcreatorTime(DateUtil.getNowDate());
                    entitys.setFcreatorUserId(userInfo.getUserId());
                } else {
                    entitys.setForganizeId(null);
                    entitys.setFlastModifyTime(DateUtil.getNowDate());
                    entitys.setFlastModifyUserId(userInfo.getUserId());
                    entitys.setFcreatorTime(null);
                    entitys.setFcreatorUserId(null);
                }
                if (entitys.getId() == null) {
                    entitys.setId(RandomUtil.uuId());
                }
                trainLibraryMoreService.saveOrUpdate(entitys);
            }
        }
        // TrainLibraryJudgment子表数据新增修改
        QueryWrapper<TrainLibraryJudgmentEntity> TrainLibraryJudgmentqueryWrapper = new QueryWrapper<>();
        TrainLibraryJudgmentqueryWrapper.lambda().eq(TrainLibraryJudgmentEntity::getFbankId, entity.getId());
        if (!isSave && !CollectionUtils.isNotEmpty(trainTestPaperLibraryForm.getTrainLibraryJudgmentList())) {
            trainLibraryJudgmentService.remove(TrainLibraryJudgmentqueryWrapper);
        }
        if (CollectionUtils.isNotEmpty(trainTestPaperLibraryForm.getTrainLibraryJudgmentList())) {
            List<TrainLibraryJudgmentEntity> tableField147 = JsonUtil.getJsonToList(
                    trainTestPaperLibraryForm.getTrainLibraryJudgmentList(), TrainLibraryJudgmentEntity.class);
            // 移除的数据
            List<Object> childIds = tableField147.stream().filter(t -> t.getId() != null)
                    .map(TrainLibraryJudgmentEntity::getId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(childIds)) {
                TrainLibraryJudgmentqueryWrapper.lambda().notIn(TrainLibraryJudgmentEntity::getId, childIds);
            }
            trainLibraryJudgmentService.remove(TrainLibraryJudgmentqueryWrapper);
            for (TrainLibraryJudgmentEntity entitys : tableField147) {
                entitys.setFbankId(entity.getId());
                if (isSave || entitys.getId() == null) {
                    entitys.setForganizeId(generaterSwapUtil.getCurrentOrgIds(userInfo.getOrganizeId(), "last"));
                    entitys.setFlastModifyTime(null);
                    entitys.setFlastModifyUserId(null);
                    entitys.setFcreatorTime(DateUtil.getNowDate());
                    entitys.setFcreatorUserId(userInfo.getUserId());
                } else {
                    entitys.setForganizeId(null);
                    entitys.setFlastModifyTime(DateUtil.getNowDate());
                    entitys.setFlastModifyUserId(userInfo.getUserId());
                    entitys.setFcreatorTime(null);
                    entitys.setFcreatorUserId(null);
                }
                if (entitys.getId() == null) {
                    entitys.setId(RandomUtil.uuId());
                }
                trainLibraryJudgmentService.saveOrUpdate(entitys);
            }
        }
        // TrainLibraryEssayQuestion子表数据新增修改
        QueryWrapper<TrainLibraryEssayQuestionEntity> TrainLibraryEssayQuestionqueryWrapper = new QueryWrapper<>();
        TrainLibraryEssayQuestionqueryWrapper.lambda().eq(TrainLibraryEssayQuestionEntity::getFbankId, entity.getId());
        if (!isSave && !CollectionUtils.isNotEmpty(trainTestPaperLibraryForm.getTrainLibraryEssayQuestionList())) {
            trainLibraryEssayQuestionService.remove(TrainLibraryEssayQuestionqueryWrapper);
        }
        if (CollectionUtils.isNotEmpty(trainTestPaperLibraryForm.getTrainLibraryEssayQuestionList())) {
            List<TrainLibraryEssayQuestionEntity> tableField180 = JsonUtil.getJsonToList(
                    trainTestPaperLibraryForm.getTrainLibraryEssayQuestionList(),
                    TrainLibraryEssayQuestionEntity.class);
            // 移除的数据
            List<Object> childIds = tableField180.stream().filter(t -> t.getId() != null)
                    .map(TrainLibraryEssayQuestionEntity::getId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(childIds)) {
                TrainLibraryEssayQuestionqueryWrapper.lambda().notIn(TrainLibraryEssayQuestionEntity::getId, childIds);
            }
            trainLibraryEssayQuestionService.remove(TrainLibraryEssayQuestionqueryWrapper);
            for (TrainLibraryEssayQuestionEntity entitys : tableField180) {
                entitys.setFbankId(entity.getId());
                if (isSave || entitys.getId() == null) {
                    entitys.setForganizeId(generaterSwapUtil.getCurrentOrgIds(userInfo.getOrganizeId(), "last"));
                    entitys.setFlastModifyTime(null);
                    entitys.setFlastModifyUserId(null);
                    entitys.setFcreatorTime(DateUtil.getNowDate());
                    entitys.setFcreatorUserId(userInfo.getUserId());
                } else {
                    entitys.setForganizeId(null);
                    entitys.setFlastModifyTime(DateUtil.getNowDate());
                    entitys.setFlastModifyUserId(userInfo.getUserId());
                    entitys.setFcreatorTime(null);
                    entitys.setFcreatorUserId(null);
                }
                if (entitys.getId() == null) {
                    entitys.setId(RandomUtil.uuId());
                }
                trainLibraryEssayQuestionService.saveOrUpdate(entitys);
            }
        }
    }

    @Override
    @Transactional
    public ActionResult onlineExamSubmit(OnlineExamSubmitDTO onlineExamSubmitDTO) {
        TrainTestPaperLibraryEntity libraryEntity = trainTestPaperLibraryMapper.selectById(onlineExamSubmitDTO.getId());
        TrainExamRecordsEntity recordsEntity = new TrainExamRecordsEntity();
        recordsEntity.setId(RandomUtil.uuId()).setFlibraryId(onlineExamSubmitDTO.getId())
                .setFnumber(libraryEntity.getFnumber())
                .setFexaminers(userProvider.get().getUserId()).setFfullName(libraryEntity.getFfullName())
                .setFsort(libraryEntity.getFsort()).setFmark("100")
                .setFquestionFlag("不存在").setFquestionStatus("已完成").setFquestionScore(0)
                .setFcreatorTime(DateUtil.getNowDate()).setFcreatorUserId(userProvider.get().getUserId())
                .setForganizeId(userProvider.get().getOrganizeId());
        List<TrainLibrarySingleEntity> singleEntities = onlineExamSubmitDTO.getSingleEntities();
        List<TrainLibraryMoreEntity> moreEntities = onlineExamSubmitDTO.getMoreEntities();
        List<TrainLibraryJudgmentEntity> judgmentEntities = onlineExamSubmitDTO.getJudgmentEntities();
        List<TrainLibraryEssayQuestionEntity> essayQuestionEntities = onlineExamSubmitDTO.getEssayQuestionEntities();
        int totalCount = 0;
        int correctCount = 0;
        List<TrainLibrarySingleEntity> resultSingleEntities = new ArrayList<>();
        List<TrainLibraryMoreEntity> resultMoreEntities = new ArrayList<>();
        List<TrainLibraryJudgmentEntity> resultJudgmentEntities = new ArrayList<>();
        List<TrainLibraryEssayQuestionEntity> resultEssayQuestionEntities = new ArrayList<>();

        if (!singleEntities.isEmpty()) {
            totalCount += singleEntities.size();
            List<TrainLibrarySingleEntity> realSingleEntities = trainLibrarySingleService
                    .getListByParentId(onlineExamSubmitDTO.getId());
            for (TrainLibrarySingleEntity singleEntity : singleEntities) {
                for (TrainLibrarySingleEntity entity : realSingleEntities) {
                    if (singleEntity.getId().equals(entity.getId())) {
                        System.out.println("正确答案： " + entity.getFanswer() + "  用户答案： " + singleEntity.getFanswer());
                        if (singleEntity.getFanswer().equals(entity.getFanswer())) {
                            correctCount++;
                        }
                    }
                }
                singleEntity.setId(RandomUtil.uuId()).setFbankId(recordsEntity.getId())
                        .setFfullName(singleEntity.getFfullName());
                resultSingleEntities.add(singleEntity);
            }
        }
        if (!moreEntities.isEmpty()) {
            totalCount += moreEntities.size();
            List<TrainLibraryMoreEntity> realMoreEntities = trainLibraryMoreService
                    .getListByParentId(onlineExamSubmitDTO.getId());
            for (TrainLibraryMoreEntity moreEntity : moreEntities) {
                for (TrainLibraryMoreEntity entity : realMoreEntities) {
                    if (moreEntity.getId().equals(entity.getId())) {
                        System.out.println("正确答案： " + entity.getFanswer() + "  用户答案： " + moreEntity.getFanswer());
                        // 判断结果
                        List<String> userAnswerList = Arrays
                                .asList(moreEntity.getFanswer().replace("[", "").replace("]", "").split(","));
                        List<String> correctAnswerList = Arrays
                                .asList(entity.getFanswer().replace("[", "").replace("]", "").split(","));
                        // 将 List 转换为 Set 以去除重复项并忽略顺序
                        Set<String> userAnswerSet = new HashSet<>(userAnswerList);
                        Set<String> correctAnswerSet = new HashSet<>(correctAnswerList);
                        // 比较集合是否相等
                        boolean isCorrect = userAnswerSet.equals(correctAnswerSet);
                        if (isCorrect) {
                            correctCount++;
                        }
                    }
                }
                moreEntity.setId(RandomUtil.uuId()).setFbankId(recordsEntity.getId())
                        .setFfullName(moreEntity.getFfullName());
                resultMoreEntities.add(moreEntity);
            }
        }
        if (!judgmentEntities.isEmpty()) {
            totalCount += judgmentEntities.size();
            List<TrainLibraryJudgmentEntity> realJudgmentEntities = trainLibraryJudgmentService
                    .getListByParentId(onlineExamSubmitDTO.getId());
            for (TrainLibraryJudgmentEntity judgmentEntity : judgmentEntities) {
                for (TrainLibraryJudgmentEntity entity : realJudgmentEntities) {
                    if (judgmentEntity.getId().equals(entity.getId())) {
                        System.out.println("正确答案： " + entity.getFanswer() + "  用户答案： " + judgmentEntity.getFanswer());
                        if (judgmentEntity.getFanswer().equals(entity.getFanswer())) {
                            correctCount++;
                        }
                    }
                }
                judgmentEntity.setId(RandomUtil.uuId()).setFbankId(recordsEntity.getId())
                        .setFfullName(judgmentEntity.getFfullName());
                resultJudgmentEntities.add(judgmentEntity);
            }
        }
        if (!essayQuestionEntities.isEmpty()) {
            recordsEntity.setFquestionFlag("存在");
            recordsEntity.setFquestionStatus("未完成");
            totalCount += essayQuestionEntities.size();
            // List<TrainLibraryEssayQuestionEntity> realEssayQuestionEntities =
            // trainLibraryEssayQuestionService.getListByParentId(onlineExamSubmitDTO.getId());
            for (TrainLibraryEssayQuestionEntity essayQuestionEntity : essayQuestionEntities) {
                essayQuestionEntity.setId(RandomUtil.uuId()).setFbankId(recordsEntity.getId())
                        .setFfullName(essayQuestionEntity.getFfullName());
                resultEssayQuestionEntities.add(essayQuestionEntity);
            }
        }
        if (totalCount > 0) {
            // 计算每题的平均得分并四舍五入
            double averageScorePerQuestion = 100.0 / totalCount;
            int roundedAverageScorePerQuestion = Math.toIntExact(Math.round(averageScorePerQuestion));// 每题得分

            int totalScore = roundedAverageScorePerQuestion * totalCount;// 总分

            recordsEntity.setFmark(String.valueOf(totalScore));
            recordsEntity.setFresultScore(String.valueOf(roundedAverageScorePerQuestion * correctCount));
            recordsEntity.setFperQuestion(roundedAverageScorePerQuestion);
            recordsEntity.setFquestionNum(totalCount);
            System.out.println("总题数: " + totalCount);
            System.out.println("每题得分: " + roundedAverageScorePerQuestion);
            System.out.println("总分: " + totalScore);
            System.out.println("正确答案数量: " + correctCount);
            System.out.println("最终得分: " + roundedAverageScorePerQuestion * correctCount);

        } else {
            return ActionResult.fail("提交失败,该试卷中不含题目,请联系相关人员!");
        }

        // TODO 插入考试记录,单选+多选+判断+问答
        trainLibrarySingleService.saveBatch(resultSingleEntities);
        trainLibraryMoreService.saveBatch(resultMoreEntities);
        trainLibraryJudgmentService.saveBatch(resultJudgmentEntities);
        trainLibraryEssayQuestionService.saveBatch(resultEssayQuestionEntities);
        trainTestPaperLibraryMapper.saveRecords(recordsEntity);

        return ActionResult.success("提交成功");
    }
}
