package com.seer.teach.admin.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seer.teach.admin.convert.KnowledgePointsConvert;
import com.seer.teach.admin.request.AddKnowledgePointUnitMappingReq;
import com.seer.teach.admin.request.CheckAndScoreReq;
import com.seer.teach.admin.request.KnowledgePointsPageQueryReq;
import com.seer.teach.admin.request.KnowledgePointsReq;
import com.seer.teach.admin.response.KnowledgePointsResp;
import com.seer.teach.admin.service.AdminKnowledgePointsService;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.exception.CommonException;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.common.utils.SubjectUtils;
import com.seer.teach.teacher.module.entity.BankOptionsEntity;
import com.seer.teach.teacher.module.entity.BankQuestionsEntity;
import com.seer.teach.teacher.module.entity.ExampleQuestionsEntity;
import com.seer.teach.teacher.module.entity.KnowSummaryEntity;
import com.seer.teach.teacher.module.entity.KnowledgePointEntity;
import com.seer.teach.teacher.module.entity.MaterialEntity;
import com.seer.teach.teacher.module.entity.ModificationLogEntity;
import com.seer.teach.teacher.module.entity.QuestionOptionsEntity;
import com.seer.teach.teacher.module.entity.UnitKnowMappingEntity;
import com.seer.teach.teacher.module.entity.UnitsEntity;
import com.seer.teach.teacher.module.entity.VersionsEntity;
import com.seer.teach.teacher.service.BankOptionsService;
import com.seer.teach.teacher.service.BankQuestionsService;
import com.seer.teach.teacher.service.ExampleQuestionsService;
import com.seer.teach.teacher.service.KnowSummaryService;
import com.seer.teach.teacher.service.KnowledgePointQueryService;
import com.seer.teach.teacher.service.KnowledgePointService;
import com.seer.teach.teacher.service.ModificationLogService;
import com.seer.teach.teacher.service.QuestionOptionsService;
import com.seer.teach.teacher.service.UnitKnowMappingService;
import com.seer.teach.user.api.UserInfoServiceApi;
import com.seer.teach.user.api.dto.UserInfoDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 知识点管理服务实现类
 * </p>
 *
 * @author ZS
 * @since 2025-10-24
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminKnowledgePointsServiceImpl implements AdminKnowledgePointsService {

    private final KnowledgePointService knowledgePointService;

    private final KnowSummaryService knowSummaryService;

    private final UnitKnowMappingService unitKnowMappingService;

    private final ExampleQuestionsService exampleQuestionsService;

    private final QuestionOptionsService questionOptionsService;

    private final KnowledgePointQueryService knowledgePointQueryService;

    private final BankOptionsService bankOptionsService;

    private final BankQuestionsService bankQuestionsService;
    
    private final UserInfoServiceApi userInfoServiceApi;

    private final ModificationLogService modificationLogService;

    /**
     * 分页查询知识点列表
     *
     * @param req 查询条件封装对象，包含分页信息、单元ID、知识点名称等查询条件
     * @return 返回分页结果，包含知识点信息及摘要内容
     */
    @Override
    public IPage<KnowledgePointsResp> pageKnowledgePoints(KnowledgePointsPageQueryReq req) {
        log.info("开始分页查询知识点列表，查询条件：pageNo={}, pageSize={}, unitId={}, knowledgePointName={}",
                req.getPageNo(), req.getPageSize(), req.getUnitId(), req.getKnowledgePointName());

        // 构建分页对象
        Page<KnowledgePointEntity> page = new Page<>(req.getPageNo(), req.getPageSize());
        // 构建查询条件
        LambdaQueryWrapper<KnowledgePointEntity> queryWrapper = new LambdaQueryWrapper<>();
        Map<Integer, UnitKnowMappingEntity> knowMappingMap = new HashMap<>();
        Set<Integer> knowIds = new HashSet<>();
        if (Objects.nonNull(req.getUnitId())) {
            log.debug("查询条件：单元ID={}", req.getUnitId());
            Collection<UnitKnowMappingEntity> mappings = unitKnowMappingService.getListByUnitId(req.getUnitId());
            if (CollectionUtil.isEmpty(mappings)) {
                return new Page<>(req.getPageNo(), req.getPageSize());
            }
            knowIds.addAll(mappings.stream().map(UnitKnowMappingEntity::getKnowledgePointId).collect(Collectors.toSet()));
            knowMappingMap.putAll(mappings.stream().collect(Collectors.toMap(UnitKnowMappingEntity::getKnowledgePointId, Function.identity(), (e1, e2) -> e1)));
        }
        if (Objects.nonNull(req.getKnowledgeSummary())) {
            List<KnowSummaryEntity> summaryEntities = knowSummaryService.list(new LambdaQueryWrapper<>(KnowSummaryEntity.class).like(KnowSummaryEntity::getSummary, req.getKnowledgeSummary()));
            if(CollectionUtil.isEmpty(summaryEntities)){
                return new Page<>(req.getPageNo(), req.getPageSize());
            }
            knowIds.addAll(summaryEntities.stream().map(KnowSummaryEntity::getKnowId).collect(Collectors.toSet()));
        }
        if (CollectionUtil.isNotEmpty(knowIds)) {
            queryWrapper.in(KnowledgePointEntity::getId, knowIds);
        }
        if (req.getKnowledgePointName() != null && !req.getKnowledgePointName().isEmpty()) {
            queryWrapper.like(KnowledgePointEntity::getKnowledgePointName, req.getKnowledgePointName());
        }
        if (Objects.nonNull(req.getIsChecked())) {
            queryWrapper.eq(KnowledgePointEntity::getIsChecked, req.getIsChecked());
        }
        if (CollUtil.isNotEmpty(req.getUpdateBy())) {
            queryWrapper.in(KnowledgePointEntity::getUpdateBy, req.getUpdateBy());
        }
        if (CollUtil.isNotEmpty(req.getSubjectIds())) {
            queryWrapper.in(KnowledgePointEntity::getSubjectId, req.getSubjectIds());
        }
        if (Objects.nonNull(req.getGradeType())) {
            queryWrapper.eq(KnowledgePointEntity::getGradeType, req.getGradeType());
        }
        // 添加年级和学科筛选条件
        if (CollUtil.isNotEmpty(req.getGradeIds()) || CollUtil.isNotEmpty(req.getVersionIds())) {
            // 获取这些单元下的知识点ID
            Collection<Integer> knowIdList = knowledgePointQueryService.getKnowIdsByGradeIdsAndVersionIds(req.getGradeIds(), req.getVersionIds());
            if (knowIdList.isEmpty()) {
                // 如果没有匹配的知识点，则返回空结果
                log.info("根据年级和学科筛选后无匹配的知识点，返回空结果");
                return new Page<>(req.getPageNo(), req.getPageSize());
            }
            queryWrapper.in(KnowledgePointEntity::getId, knowIdList);
        }
        queryWrapper.orderByAsc(KnowledgePointEntity::getId);
        IPage<KnowledgePointEntity> pageResult = knowledgePointService.page(page, queryWrapper);

        // 转换为响应对象
        IPage<KnowledgePointsResp> resp = pageResult.convert(KnowledgePointsConvert.INSTANCE::toResp);
        // 如果查询结果为空，直接返回空页面
        if (CollectionUtil.isEmpty(resp.getRecords())) {
            log.info("知识点列表查询结果为空");
            return new Page<>(req.getPageNo(), req.getPageSize());
        }
        // 提取知识点ID集合
        Set<Integer> KnowledgePointIds = resp.getRecords().stream().map(KnowledgePointsResp::getId).collect(Collectors.toSet());
        log.debug("需要查询摘要信息的知识点数量：{}", KnowledgePointIds.size());

        // 根据知识点ID批量查询摘要信息
        List<KnowSummaryEntity> knowSummariesEntities = knowSummaryService.getListByKnowIds(KnowledgePointIds);
        log.debug("查询到的摘要信息数量：{}", knowSummariesEntities.size());

        // 构建摘要信息Map，以知识点ID为键
        Map<Integer, KnowSummaryEntity> knowSummariesEntityMap = knowSummariesEntities.stream().collect(Collectors.toMap(KnowSummaryEntity::getKnowId, Function.identity(), (knowSummariesEntity, knowSummariesEntity2) -> knowSummariesEntity2));
        // 将摘要信息填充到知识点响应对象中
        setResponse(resp.getRecords(), knowSummariesEntityMap, knowMappingMap);

        log.info("分页查询知识点列表完成，共查询到{}条记录", resp.getRecords().size());
        return resp;
    }

    @Override
    public List<KnowledgePointsResp> getKnowledgePointsByUnitId(Integer unitId,KnowledgePointsPageQueryReq KnowledgePointQueryReq) {
        Collection<UnitKnowMappingEntity> mappings = unitKnowMappingService.getListByUnitId(unitId);
        if (CollUtil.isEmpty(mappings)) {
            return Collections.emptyList();
        }

        Set<Integer> knowIdList = mappings.stream().map(UnitKnowMappingEntity::getKnowledgePointId).collect(Collectors.toSet());
        Collection<KnowledgePointEntity> knowledgePointList = knowledgePointQueryService.getKnowledgePointListByKnowIdsOrName(knowIdList,KnowledgePointQueryReq.getKnowledgePointName());
        if (CollUtil.isEmpty(knowledgePointList)) {
            return Collections.emptyList();
        }
        List<KnowledgePointsResp> resps = KnowledgePointsConvert.INSTANCE.converEntity2RespList(knowledgePointList);

        // 根据知识点ID批量查询摘要信息
        List<KnowSummaryEntity> knowSummariesEntities = knowSummaryService.getListByKnowIds(knowIdList);

        // 构建摘要信息Map，以知识点ID为键
        Map<Integer, KnowSummaryEntity> knowSummariesEntityMap = knowSummariesEntities.stream().collect(Collectors.toMap(KnowSummaryEntity::getKnowId, Function.identity(), (knowSummariesEntity, knowSummariesEntity2) -> knowSummariesEntity2));
        Map<Integer, UnitKnowMappingEntity> knowMappingMap = mappings.stream().collect(Collectors.toMap(UnitKnowMappingEntity::getKnowledgePointId, Function.identity(), (e1, e2) -> e1));

        setResponse(resps, knowSummariesEntityMap, knowMappingMap);

        resps.sort((r1, r2) -> {
            Integer sort1 = r1.getSort();
            Integer sort2 = r2.getSort();
            if (sort1 == null && sort2 == null) return 0;
            if (sort1 == null) return 1;
            if (sort2 == null) return -1;
            return sort1.compareTo(sort2);
        });
        return resps;
    }

    private void setResponse(List<KnowledgePointsResp> resps, Map<Integer, KnowSummaryEntity> knowSummariesEntityMap, Map<Integer, UnitKnowMappingEntity> knowMappingMap) {
        // 收集所有需要查询的用户ID
        Set<Integer> updateUserIds = knowMappingMap.values().stream()
                .filter(item -> Objects.nonNull(item.getUpdateBy()))
                .map(item-> Integer.valueOf(item.getUpdateBy()))
                .collect(Collectors.toSet());
        
        // 批量获取用户信息
        Map<Integer, String> updateUserNamesMap = new HashMap<>();
        if (CollUtil.isNotEmpty(updateUserIds)) {
            try {
                List<UserInfoDTO> userInfoList = userInfoServiceApi.getListByUserIds(updateUserIds);
                updateUserNamesMap = userInfoList.stream()
                        .filter(Objects::nonNull)
                        .filter(userInfo -> userInfo.getId() != null)
                        .filter(userInfo -> userInfo.getUserName() != null)
                        .collect(Collectors.toMap(UserInfoDTO::getId, UserInfoDTO::getUserName));
            } catch (Exception e) {
                log.warn("获取用户信息失败，错误信息：{}", e.getMessage());
            }
        }
        for(KnowledgePointsResp knowledgePointsResp : resps){
            KnowSummaryEntity knowSummaryEntity = knowSummariesEntityMap.get(knowledgePointsResp.getId());
            if (knowSummaryEntity != null) {
                knowledgePointsResp.setSummary(knowSummaryEntity.getSummary());
                knowledgePointsResp.setSummaryId(knowSummaryEntity.getId());
            }
            UnitKnowMappingEntity unitKnowMapping = knowMappingMap.get(knowledgePointsResp.getId());
            if (Objects.nonNull(unitKnowMapping)) {
                knowledgePointsResp.setUnitId(unitKnowMapping.getUnitId());
                knowledgePointsResp.setSort(unitKnowMapping.getSort());
                knowledgePointsResp.setIsChecked(unitKnowMapping.getIsChecked());
                knowledgePointsResp.setScore(unitKnowMapping.getScore());
                knowledgePointsResp.setUpdateBy(unitKnowMapping.getUpdateBy());
                knowledgePointsResp.setUpdateTime(unitKnowMapping.getUpdateTime());
                knowledgePointsResp.setCreateTime(unitKnowMapping.getCreateTime());
                knowledgePointsResp.setIsStandardVersion(unitKnowMapping.getIsStandardVersion());

                // 设置更新人姓名
                String updateBy = unitKnowMapping.getUpdateBy();
                if (updateBy != null) {
                    knowledgePointsResp.setUpdateByName(updateUserNamesMap.get(Integer.valueOf(updateBy)));
                }
            } else {
                knowledgePointsResp.setSort(null);
            }
        }
    }

    /**
     * 根据ID获取知识点详情
     *
     * @param id 知识点ID
     * @return 知识点详细信息，包括摘要内容
     */
    @Override
    public KnowledgePointsResp getKnowledgePointById(Integer id) {
        log.info("开始查询ID为{}的知识点详情", id);

        // 根据ID查询知识点实体
        KnowledgePointEntity entity = knowledgePointService.getById(id);
        // 如果实体不存在，返回null
        if (Objects.isNull(entity)) {
            log.warn("未找到ID为{}的知识点", id);
            return null;
        }
        // 转换为响应对象
        KnowledgePointsResp resp = KnowledgePointsConvert.INSTANCE.toResp(entity);
        // 查询对应的知识点摘要信息
        KnowSummaryEntity knowSummaryEntity = knowSummaryService.getOneByKnowId(entity.getId());
        // 如果摘要存在，设置摘要信息
        if (knowSummaryEntity != null) {
            resp.setSummary(knowSummaryEntity.getSummary());
            resp.setSummaryId(knowSummaryEntity.getId());
        }

        log.info("查询ID为{}的知识点详情完成", id);
        return resp;
    }

    /**
     * 添加知识点
     *
     * @param req 知识点请求对象，包含要添加的知识点信息
     * @return 是否添加成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addKnowledgePoint(KnowledgePointsReq req) {
        log.info("开始添加知识点，知识点名称：{}", req.getKnowledgePointName());

        // 将请求对象转换为实体对象
        KnowledgePointEntity entity = KnowledgePointsConvert.INSTANCE.convertReq2Entity(req);
        // 保存知识点实体
        boolean result = knowledgePointService.save(entity);

        if (result) {
            UnitKnowMappingEntity mappingEntity = new UnitKnowMappingEntity();
            mappingEntity.setUnitId(req.getUnitId());
            mappingEntity.setKnowledgePointId(entity.getId());
            mappingEntity.setSort(req.getSort());
            mappingEntity.setCreateTime(LocalDateTime.now());
            boolean saved = unitKnowMappingService.save(mappingEntity);
            if (saved) {
                log.info("单元知识点映射保存成功，单元知识点映射ID：{}", mappingEntity.getId());
                // 如果知识点保存成功且包含摘要信息，则同时保存摘要信息
                if (StringUtils.hasText(req.getSummary())) {
                    KnowSummaryEntity summaryEntity = new KnowSummaryEntity();
                    summaryEntity.setKnowId(entity.getId());
                    summaryEntity.setSummary(req.getSummary());
                    knowSummaryService.save(summaryEntity);
                    log.info("知识点摘要保存成功，摘要ID：{}", summaryEntity.getId());
                }
            } else {
                log.error("单元知识点映射保存失败，单元ID：{}，知识点ID：{}", req.getUnitId(), entity.getId());
            }
        }
        return result;
    }


    /**
     * 更新知识点
     *
     * @param id  要更新的知识点ID
     * @param req 知识点请求对象，包含更新后的知识点信息
     * @return 是否更新成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateKnowledgePoint(Integer id, KnowledgePointsReq req) {
        log.info("开始更新ID为{}的知识点，更新后的知识点名称：{}", id, req.getKnowledgePointName());
        String subjectName = SubjectUtils.getSubjectNameBySubjectId(req.getSubjectId());
        AssertUtils.notNull(subjectName,ResultCodeEnum.SUBJECT_NOT_EXIST);
        // 先根据ID查询原知识点实体
        KnowledgePointEntity entity = knowledgePointService.getById(id);
        AssertUtils.notNull(entity,ResultCodeEnum.KNOW_NOT_EXIST);

        Collection<UnitKnowMappingEntity> unitKnowMappings = knowledgePointQueryService.getUnitKnowMappingListByKnowId(id);
        AssertUtils.notEmpty(unitKnowMappings,ResultCodeEnum.KNOW_NOT_EXIST);

        Optional<UnitKnowMappingEntity> unitKnowMappingEntity = unitKnowMappings.stream().filter(item -> item.getUnitId().equals(req.getUnitId())).findFirst();
        AssertUtils.isTrue(unitKnowMappingEntity.isPresent(),ResultCodeEnum.KNOW_NOT_EXIST);

        UnitKnowMappingEntity unitKnowMapping = unitKnowMappingEntity.get();
        Integer isStandardVersion = unitKnowMapping.getIsStandardVersion();
        if(Objects.isNull(isStandardVersion)){
            UnitsEntity unit = knowledgePointQueryService.getUnitByUnitId(unitKnowMapping.getUnitId());
            AssertUtils.notNull(unit, ResultCodeEnum.UNIT_NOT_EXIST);
            MaterialEntity material = knowledgePointQueryService.getMaterialByMaterialId(unit.getMaterialId());
            AssertUtils.notNull(material, ResultCodeEnum.MATERIAL_NOT_EXIST);
            VersionsEntity version = knowledgePointQueryService.getVersionByVersionId(material.getVersionId());
            AssertUtils.notNull(version, ResultCodeEnum.VERSION_NOT_EXIST);
            isStandardVersion = version.getIsStandardVersion();
            boolean updated = unitKnowMappingService.update(new LambdaUpdateWrapper<>(UnitKnowMappingEntity.class).eq(UnitKnowMappingEntity::getId, unitKnowMapping.getId()).set(UnitKnowMappingEntity::getIsStandardVersion, isStandardVersion));
            log.info("单元知识点映射更新成功，单元知识点映射ID：{}", updated);
        }
        if(isStandardVersion == 1 || unitKnowMappings.size() == 1){
            return updateKnowledgePointByKnowId(id,req);
        }
        Optional<UnitKnowMappingEntity> standardVersionMapping = unitKnowMappings.stream().filter(item-> item.getIsStandardVersion() == 1).findFirst();
        AssertUtils.isTrue(!standardVersionMapping.isPresent(),ResultCodeEnum.KNOWLEDGE_POINT_IS_STANDARD);

        return updateKnowledgePointByKnowId(id,req);
    }


    private boolean updateKnowledgePointByKnowId(Integer id, KnowledgePointsReq req) {
        // 将请求对象转换为实体对象
        KnowledgePointEntity knowledgePointEntity = KnowledgePointsConvert.INSTANCE.convertReq2Entity(req);
        knowledgePointEntity.setId(id);
        knowledgePointEntity.setUpdateTime(LocalDateTime.now());
        // 执行更新操作
        boolean result = knowledgePointService.updateById(knowledgePointEntity);
        // 如果更新成功且包含摘要信息，则同时更新摘要信息
        if (result ) {
            log.info("知识点更新成功，更新后的知识点名称：{}", req.getKnowledgePointName());
            if( req.getSummary() != null){
                KnowSummaryEntity summaryEntity = knowSummaryService.getOneByKnowId(id);
                if (summaryEntity == null) {
                    // 如果摘要不存在则创建新的摘要
                    summaryEntity = new KnowSummaryEntity();
                    summaryEntity.setKnowId(id);
                    summaryEntity.setSummary(req.getSummary());
                    knowSummaryService.save(summaryEntity);
                    log.info("知识点摘要创建成功，摘要ID：{}", summaryEntity.getId());
                } else {
                    // 如果摘要存在则更新摘要内容
                    summaryEntity.setSummary(req.getSummary());
                    summaryEntity.setUpdateTime(LocalDateTime.now());
                    knowSummaryService.updateById(summaryEntity);
                    log.info("知识点摘要更新成功，摘要ID：{}", summaryEntity.getId());
                }
            }
            if(Objects.nonNull(req.getUnitId()) && Objects.nonNull(req.getSort())){
                unitKnowMappingService.updateKnowledgePointOrder(id, req.getUnitId(), req.getSort());
            }
        }

        if (result) {
            log.info("知识点更新成功，知识点ID：{}", id);
        } else {
            log.error("知识点更新失败，知识点ID：{}", id);
        }
        return result;
    }

    @Override
    public boolean updateKnowledgePointCheckAndScore(Integer id, CheckAndScoreReq req) {
        return unitKnowMappingService.updateKnowledgePointCheckAndScore(id,req.getUnitId(),req.getIsChecked(),req.getScore());
    }

    @Override
    public boolean batchUpdateKnowledgePointCheck(List<Integer> ids, Integer unitId,Integer isChecked) {
        List<UnitKnowMappingEntity> entities = unitKnowMappingService.list(new LambdaQueryWrapper<>(UnitKnowMappingEntity.class)
                .in(UnitKnowMappingEntity::getKnowledgePointId,ids)
                .eq(UnitKnowMappingEntity::getUnitId,unitId));
        if(CollectionUtil.isEmpty(entities)){
            return false;
        }
        entities.forEach(entity -> {
            entity.setIsChecked(isChecked);
            entity.setUpdateTime(LocalDateTime.now());
            entity.setUpdateBy(StpUtil.getLoginIdAsString());
        });
        return unitKnowMappingService.updateBatchById(entities);
    }

    /**
     * 删除知识点及其关联的摘要信息、示例题目和选项
     *
     * @param id 要删除的知识点ID
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteKnowledgePoint(Integer id,Integer unitId) {
        log.info("开始删除ID为{}的知识点", id);

        // 先检查知识点是否存在
        KnowledgePointEntity entity = knowledgePointService.getById(id);
        if (Objects.isNull(entity)) {
            log.warn("尝试删除知识点时未找到对应记录，知识点ID：{}", id);
            return false;
        }

        // 删除关联的知识点摘要信息
        boolean deletedSummaries = knowSummaryService.remove(
                new LambdaQueryWrapper<KnowSummaryEntity>()
                        .eq(KnowSummaryEntity::getKnowId, id));
        log.info("删除知识点摘要完成，结果：{}", deletedSummaries);

        Collection<UnitKnowMappingEntity> UnitKnowMappings = knowledgePointQueryService.getUnitKnowMappingListByKnowId(id);
        if(CollectionUtil.isEmpty(UnitKnowMappings)){
            log.warn("知识点没有关联单元，请检查");
            return  false;
        }

        Set<Integer> unitIds = UnitKnowMappings.stream().map(UnitKnowMappingEntity::getUnitId).collect(Collectors.toSet());
        if(UnitKnowMappings.size() == 1 && unitIds.contains(unitId)){
            unitKnowMappingService.remove(new LambdaQueryWrapper<>(UnitKnowMappingEntity.class).eq(UnitKnowMappingEntity::getKnowledgePointId, id));
            boolean remove = unitKnowMappingService.remove(new LambdaQueryWrapper<>(UnitKnowMappingEntity.class).eq(UnitKnowMappingEntity::getKnowledgePointId, id));
            log.info("删除知识点单元映射完成，结果：{}", remove);

            // 查询该知识点下的所有示例题目
            List<ExampleQuestionsEntity> exampleQuestionsList = exampleQuestionsService.getQuestionsByKnowleId(id);
            log.info("查询到 {} 个示例题目需要删除", exampleQuestionsList.size());

            if (CollectionUtil.isNotEmpty(exampleQuestionsList)) {
                // 获取题目ID列表
                List<Integer> questionIds = exampleQuestionsList.stream()
                        .map(ExampleQuestionsEntity::getId)
                        .collect(Collectors.toList());

                // 删除题目选项
                boolean deletedOptions = questionOptionsService.remove(
                        new LambdaQueryWrapper<QuestionOptionsEntity>()
                                .in(QuestionOptionsEntity::getQuestionId, questionIds));
                log.info("删除了 {} 条题目选项", deletedOptions);

                // 删除题目
                boolean deletedQuestions = exampleQuestionsService.removeBatchByIds(questionIds);
                log.info("删除了 {} 条示例题目", deletedQuestions);
            }

            List<BankQuestionsEntity> bankQuestions = bankQuestionsService.list(new LambdaQueryWrapper<>(BankQuestionsEntity.class).eq(BankQuestionsEntity::getKnowId, id));
            if (CollectionUtil.isNotEmpty(bankQuestions)) {
                List<Integer> questionIds = bankQuestions.stream()
                        .map(BankQuestionsEntity::getId)
                        .collect(Collectors.toList());
                boolean bankOptionsRemoved = bankOptionsService.remove(new LambdaQueryWrapper<>(BankOptionsEntity.class).in(BankOptionsEntity::getQuestionId, questionIds));
                log.info("删除知识点题库选项完成，结果：{}", bankOptionsRemoved);
                boolean bankQuestionRemoved = bankQuestionsService.removeBatchByIds(questionIds);
                log.info("删除知识点题库题目完成，结果：{}", bankQuestionRemoved);
            }
            // 删除知识点本身
            boolean result = knowledgePointService.removeById(id);

            if (result) {
                log.info("知识点删除成功，知识点ID：{}", id);
            } else {
                log.error("知识点删除失败，知识点ID：{}", id);
            }
            return result;
        }else{
            return unitKnowMappingService.remove(new LambdaQueryWrapper<>(UnitKnowMappingEntity.class).eq(UnitKnowMappingEntity::getKnowledgePointId, id)
                    .eq(UnitKnowMappingEntity::getUnitId,unitId));
        }
    }

    @Override
    public KnowledgePointsResp getKnowledgePointByUnitIdAndKnowId(Integer unitId, Integer knowId) {
        KnowledgePointEntity knowledgePoint = knowledgePointService.getById(knowId);
        KnowledgePointsResp resp = KnowledgePointsConvert.INSTANCE.toResp(knowledgePoint);
        if (Objects.nonNull(resp)) {
            UnitKnowMappingEntity mapping = unitKnowMappingService.getOneByUnitIdAndKnowId(unitId, knowId);
            if(Objects.nonNull( mapping)){
                resp.setUnitId(mapping.getUnitId());
                resp.setSort(mapping.getSort());
                resp.setIsChecked(mapping.getIsChecked());
                resp.setScore(mapping.getScore());
                resp.setIsStandardVersion(mapping.getIsStandardVersion());
            }
            // 查询对应的知识点摘要信息
            KnowSummaryEntity knowSummaryEntity = knowSummaryService.getOneByKnowId(knowId);
            // 如果摘要存在，设置摘要信息
            if (knowSummaryEntity != null) {
                resp.setSummary(knowSummaryEntity.getSummary());
                resp.setSummaryId(knowSummaryEntity.getId());
            }

            ModificationLogEntity modificationLog = new ModificationLogEntity();
            modificationLog.setTargetId(knowId);
            modificationLog.setTargetType(ModificationLogEntity.TARGET_TYPE_KNOWLEDGE_POINT);
            modificationLog.setTargetName(knowledgePoint.getKnowledgePointName());
            modificationLog.setRemark("查看知识点");
            modificationLog.setOperationType(ModificationLogEntity.OPERATION_TYPE_VIEW);
            modificationLog.setOperatorId(StpUtil.getLoginIdAsInt());
            modificationLogService.save(modificationLog);

        }
        return resp;
    }
}