package cn.iocoder.yudao.module.course.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.base.constant.SchoolBaseConstants;
import cn.iocoder.yudao.module.base.entity.SchoolFeedBack;
import cn.iocoder.yudao.module.base.service.SchoolFeedbackService;
import cn.iocoder.yudao.module.base.mapper.SchoolFeedBackMapper;
import cn.iocoder.yudao.module.base.vo.SchoolFeedBackVO;
import cn.iocoder.yudao.module.exam.entity.ExamBatchItem;
import cn.iocoder.yudao.module.exam.service.ExamBatchItemService;
import cn.iocoder.yudao.module.exam.vo.ExamBatchItemVO;
import cn.iocoder.yudao.module.train.entity.Train;
import cn.iocoder.yudao.module.train.service.TrainService;
import cn.iocoder.yudao.module.train.vo.TrainVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.module.base.utils.DriveSchoolBaseUtil.getSubjectStr;

/**
 * 反馈Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-27
 */
@Service
@RequiredArgsConstructor
public class SchoolFeedbackServiceImpl extends ServiceImpl<SchoolFeedBackMapper, SchoolFeedBack> implements SchoolFeedbackService {
    private final TrainService trainService;

    private final ExamBatchItemService examBatchItemService;

    /**
     * 新增评论
     *
     * @param request 请求
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SchoolFeedBackVO request) {
        boolean save = save(request);
        // 判断评价类型修改训练表或考试表
        if (SchoolBaseConstants.EVALUATE_TYPE_TRAIN.equals(request.getEvaluateType())) {
            // 训练表
            trainService.update(Wrappers.<Train>lambdaUpdate()
                    .eq(Train::getId, request.getBusiId())
                    .set(Train::getIfEvaluate, SchoolBaseConstants.COMMON_YES)
                    .set(Train::getEvaluateId, request.getId()));
        } else if (SchoolBaseConstants.EVALUATE_TYPE_EXAM.equals(request.getEvaluateType())) {
            // 考试表
            examBatchItemService.update(Wrappers.<ExamBatchItem>lambdaUpdate()
                    .eq(ExamBatchItem::getId, request.getBusiId())
                    .set(ExamBatchItem::getIfEvaluate, SchoolBaseConstants.COMMON_YES)
                    .set(ExamBatchItem::getEvaluateId, request.getId()));
        }
    }

    /**
     * 分页查询评价
     *
     * @param page    分页
     * @param request 请求
     * @return IPage
     */
    @Override
    public IPage<SchoolFeedBackVO> queryPage(Page<SchoolFeedBack> page, SchoolFeedBackVO request) {
        // 1. 分页查询原始数据
        IPage<SchoolFeedBack> pageList = this.page(page, Wrappers.lambdaQuery(SchoolFeedBack.class)
                .eq(ObjectUtil.isNotEmpty(request.getUserId()), SchoolFeedBack::getUserId, request.getUserId())
                .eq(ObjectUtil.isNotEmpty(request.getEvaluateType()), SchoolFeedBack::getEvaluateType, request.getEvaluateType())
                .orderByDesc(SchoolFeedBack::getCreateTime));

        // 2. 提取训练和考试的ID集合
        List<String> trainIds = pageList.getRecords().stream()
                .filter(item -> SchoolBaseConstants.EVALUATE_TYPE_TRAIN.equals(item.getEvaluateType()))
                .map(SchoolFeedBack::getBusiId)
                .collect(Collectors.toList());

        List<String> examIds = pageList.getRecords().stream()
                .filter(item -> SchoolBaseConstants.EVALUATE_TYPE_EXAM.equals(item.getEvaluateType()))
                .map(SchoolFeedBack::getBusiId)
                .collect(Collectors.toList());

        // 3. 批量查询关联数据
        Map<String, TrainVO> trainMap = Optional.ofNullable(trainService.listJoinBatchByIds(trainIds))
                .orElse(Collections.emptyList()) // 如果为 null，返回空列表
                .stream()
                .collect(Collectors.toMap(
                        TrainVO::getId,
                        train -> train
                ));

        Map<String, ExamBatchItemVO> examMap = Optional.ofNullable(examBatchItemService.listJoinBatchByIds(examIds))
                .orElse(Collections.emptyList()) // 如果返回 null，替换成空列表
                .stream()
                .collect(Collectors.toMap(
                        ExamBatchItemVO::getId,
                        exam -> exam
                ));

        // 4. 转换为VO列表
        List<SchoolFeedBackVO> voList = pageList.getRecords().stream().map(item -> {
            SchoolFeedBackVO vo = BeanUtil.copyProperties(item, SchoolFeedBackVO.class);
            if (SchoolBaseConstants.EVALUATE_TYPE_TRAIN.equals(item.getEvaluateType())) {
                // 设置标题
                vo.setBusiName(getSubjectStr(trainMap.get(item.getBusiId()).getSubject()) + "训练");
                // 设置课程类型和教练名
                vo.setCourseType(trainMap.get(item.getBusiId()).getCourseType());
                vo.setCoachName(trainMap.get(item.getBusiId()).getCoachName());
            } else if (SchoolBaseConstants.EVALUATE_TYPE_EXAM.equals(item.getEvaluateType())) {
                // 设置标题
                vo.setBusiName(getSubjectStr(examMap.get(item.getBusiId()).getSubject()) + "考试");
                // 设置课程类型和教练名
                vo.setCourseType(examMap.get(item.getBusiId()).getCourseType());
                vo.setCoachName(examMap.get(item.getBusiId()).getCoachName());
            }
            return vo;
        }).collect(Collectors.toList());

        // 5. 构建返回的IPage对象
        IPage<SchoolFeedBackVO> resultPage = new Page<>();
        BeanUtil.copyProperties(pageList, resultPage); // 复制分页信息
        resultPage.setRecords(voList); // 设置VO数据

        return resultPage;
    }
}
