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

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seer.teach.admin.convert.AdminTeachGoalConvert;
import com.seer.teach.admin.request.TeachGoalCheckAndScoreReq;
import com.seer.teach.admin.request.TeachGoalsBatchSaveReq;
import com.seer.teach.admin.request.TeachGoalsQueryReq;
import com.seer.teach.admin.request.TeachGoalsReq;
import com.seer.teach.admin.response.TeachGoalsResp;
import com.seer.teach.admin.service.AdminTeachGoalsService;
import com.seer.teach.teacher.module.entity.ModificationLogEntity;
import com.seer.teach.teacher.module.entity.TeachGoalsEntity;
import com.seer.teach.teacher.module.param.KnowledgePointSearchParam;
import com.seer.teach.teacher.service.KnowledgePointQueryService;
import com.seer.teach.teacher.service.TeachGoalsService;
import com.seer.teach.teacher.util.ModificationLogUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 教学目标管理服务实现类
 * </p>
 *
 * @author Lingma
 * @since 2025-12-04
 */
@Slf4j
@Service
public class AdminTeachGoalsServiceImpl  implements AdminTeachGoalsService {

    @Autowired
    private TeachGoalsService teachGoalsService;

    @Autowired
    private KnowledgePointQueryService knowledgePointQueryService;
    
    @Override
    public IPage<TeachGoalsResp> pageTeachGoals(TeachGoalsQueryReq req) {
        log.info("分页查询教学目标列表, 查询参数: {}", req);
        Page<TeachGoalsEntity> page = new Page<>(req.getPageNo(), req.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<TeachGoalsEntity> queryWrapper = new LambdaQueryWrapper<>();

        // 根据年级和科目查询知识点
        if (Objects.nonNull(req.getGradeId()) || Objects.nonNull(req.getSubjectId()) || Objects.nonNull(req.getVersionId())|| Objects.nonNull(req.getKnowName())  || Objects.nonNull(req.getKnowId()) || Objects.nonNull(req.getGradeType())) {
            KnowledgePointSearchParam knowledgePointSearchParam = AdminTeachGoalConvert.INSTANCE.req2KnowledgePointSearchParam(req);
            Collection<Integer> knowIdList = knowledgePointQueryService.getKnowIdsByConditions(knowledgePointSearchParam);
            if (knowIdList.isEmpty()) {
                log.info("根据年级和学科筛选后无匹配的知识点，返回空结果");
                return new Page<>(req.getPageNo(), req.getPageSize());
            }
            queryWrapper.in(TeachGoalsEntity::getKnowId, knowIdList);
        }
        if (Objects.nonNull(req.getKnowId())) {
            queryWrapper.eq(TeachGoalsEntity::getKnowId, req.getKnowId());
        }
        if (Objects.nonNull(req.getGoal())) {
            queryWrapper.like(TeachGoalsEntity::getGoal, req.getGoal());
        }
        if (Objects.nonNull(req.getPoint())) {
            queryWrapper.like(TeachGoalsEntity::getPoint, req.getPoint());
        }
        IPage<TeachGoalsEntity> pageResult = teachGoalsService.page(page, queryWrapper);

        // 转换为响应对象
        IPage<TeachGoalsResp> respPage = pageResult.convert(AdminTeachGoalConvert.INSTANCE::toTeachGoalsResp);

        log.info("分页查询教学目标列表成功, 总数: {}", respPage.getTotal());
        return respPage;
    }

    @Override
    public TeachGoalsResp getTeachGoalById(Integer id) {
        log.info("根据ID查询教学目标详情, ID: {}", id);
        TeachGoalsEntity entity = teachGoalsService.getById(id);
        if (entity == null) {
            return null;
        }

        TeachGoalsResp resp = AdminTeachGoalConvert.INSTANCE.toTeachGoalsResp(entity);
        log.info("查询教学目标详情成功, ID: {}", id);
        return resp;
    }

    @Override
    public boolean addTeachGoal(TeachGoalsReq req) {
        log.info("新增教学目标, 请求参数: {}", req);
        TeachGoalsEntity entity = AdminTeachGoalConvert.INSTANCE.toTeachGoalsEntity(req);
        boolean result = teachGoalsService.save(entity);
        log.info("新增教学目标结果: {}, ID: {}", result, entity.getId());
        if (result) {
            ModificationLogUtils.logModification(
                    ModificationLogEntity.TARGET_TYPE_TEACH_GOAL,
                    entity.getId(),
                    "新增教学目标",
                    ModificationLogEntity.OPERATION_TYPE_ADD,
                    null,
                    entity,
                    StpUtil.getLoginIdAsInt());
        }
        return result;
    }

    @Override
    public boolean updateTeachGoal(Integer id, TeachGoalsReq req) {
        log.info("更新教学目标, ID: {}, 请求参数: {}", id, req);
        TeachGoalsResp oldResp = getTeachGoalById(id);
        TeachGoalsEntity entity = AdminTeachGoalConvert.INSTANCE.toTeachGoalsEntity(req);
        entity.setId(id);
        boolean result = teachGoalsService.updateById(entity);
        if (result) {
            TeachGoalsResp newResp = getTeachGoalById(id);
            ModificationLogUtils.logModification(
                    ModificationLogEntity.TARGET_TYPE_TEACH_GOAL,
                    id,
                    "修改教学目标",
                    ModificationLogEntity.OPERATION_TYPE_UPDATE,
                    oldResp, newResp,
                    StpUtil.getLoginIdAsInt());
        }
        log.info("更新教学目标结果: {}", result);
        return result;
    }

    @Override
    public boolean deleteTeachGoal(Integer id) {
        log.info("删除教学目标, ID: {}", id);
        boolean result = teachGoalsService.removeById(id);
        log.info("删除教学目标结果: {}", result);
        if (result) {
            TeachGoalsResp oldResp = getTeachGoalById(id);
            ModificationLogUtils.logModification(
                    ModificationLogEntity.TARGET_TYPE_TEACH_GOAL,
                    id,
                    "删除教学目标",
                    ModificationLogEntity.OPERATION_TYPE_DELETE,
                    oldResp, null,
                    StpUtil.getLoginIdAsInt());
        }
        return result;
    }

    @Override
    public boolean updateTeachGoalCheckAndScore(Integer id, TeachGoalCheckAndScoreReq req) {
        log.info("更新教学目标检查状态和评分, ID: {}, 请求参数: {}", id, req);
        TeachGoalsEntity entity = new TeachGoalsEntity();
        entity.setId(id);
        entity.setIsChecked(req.getIsChecked());
        entity.setScore(req.getScore());
        boolean result = teachGoalsService.updateById(entity);
        log.info("更新教学目标检查状态和评分结果: {}", result);
        return result;
    }

    @Override
    public boolean batchSaveGeneratedTeachGoals(TeachGoalsBatchSaveReq req) {
        log.info("批量保存生成的教学目标, 请求参数: {}", req);
        List<TeachGoalsEntity> goals = req.getGoals().stream().map(goalItem -> {
            TeachGoalsEntity entity = new TeachGoalsEntity();
            entity.setKnowId(req.getKnowId());
            entity.setSort(goalItem.getSort());
            entity.setGoal(goalItem.getGoal());
            entity.setPoint(goalItem.getPoint());
            return entity;
        }).collect(Collectors.toList());

        boolean result = teachGoalsService.saveBatch(goals);
        log.info("批量保存生成的教学目标结果: {}", result);
        return result;
    }

    @Override
    public boolean updateTeachGoalSort(Integer id, Integer sort) {
        log.info("更新教学目标的排序, ID: {}, 请求参数: {}", id, sort);
        TeachGoalsResp oldResp = getTeachGoalById(id);
        TeachGoalsEntity entity = new TeachGoalsEntity();
        entity.setId(id);
        entity.setSort(sort);
        boolean result = teachGoalsService.updateById(entity);
        if (result) {
            TeachGoalsResp newResp = getTeachGoalById(id);
            ModificationLogUtils.logModification(
                    ModificationLogEntity.TARGET_TYPE_TEACH_GOAL,
                    id,
                    "修改教学目标的排序",
                    ModificationLogEntity.OPERATION_TYPE_UPDATE,
                    oldResp, newResp,
                    StpUtil.getLoginIdAsInt());
        }
        log.info("更新教学目标的排序结果: {}", result);
        return result;
    }

}