package com.rongwei.trainingcommon.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rongwei.rwcommon.base.BaseDo;
import com.rongwei.rwcommon.base.R;
import com.rongwei.training.domain.CourseDo;
import com.rongwei.training.domain.PlanCourseDo;
import com.rongwei.training.domain.PlanDo;
import com.rongwei.trainingcommon.sys.dao.CourseDao;
import com.rongwei.trainingcommon.sys.dao.PlanCourseDao;
import com.rongwei.trainingcommon.sys.dao.PlanDao;
import com.rongwei.trainingcommon.sys.service.CourseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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


@Service("courseService")
public class CourseServiceImpl extends ServiceImpl<CourseDao, CourseDo> implements CourseService {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private PlanCourseDao planCourseDao;
    @Autowired
    private PlanDao planDao;
    @Autowired
    private CourseService courseService;

    @Override
    public R checkCourse(List<String> courseIds) {
        QueryWrapper<PlanCourseDo> queryWrapper = new QueryWrapper<>();
        // 获取培训计划课程表
        List<PlanCourseDo> planCourseDos = planCourseDao.selectList(queryWrapper.lambda().in(PlanCourseDo::getCourseid, courseIds)
                .eq(BaseDo::getDeleted, "0"));
        log.info("获取培训计划和课程的关系: {}", planCourseDos);
        // 没有引用
        if (planCourseDos.isEmpty()) {
            log.info("当前课程没有被培训计划引用");
            LambdaUpdateWrapper<CourseDo> lambdaUpdateEmpWrapper = new LambdaUpdateWrapper<CourseDo>();
            lambdaUpdateEmpWrapper.in(CourseDo::getId, courseIds).set(BaseDo::getDeleted, 1);
            courseService.update(lambdaUpdateEmpWrapper);
            return R.ok();
        }
        // 根据课程名称分组
        Map<String, List<String>> collect = planCourseDos.stream()
                .collect(Collectors.groupingBy(PlanCourseDo::getCoursename,
                        Collectors.mapping(PlanCourseDo::getTrainingplanid, Collectors.toList())));
        for (Map.Entry<String, List<String>> mapInfo : collect.entrySet()) {
            // 获取培训计划
            List<PlanDo> planDos = planDao.selectList(new QueryWrapper<PlanDo>().lambda().in(PlanDo::getId, mapInfo.getValue()).eq(BaseDo::getDeleted, "0"));
            log.info("根据培训计划关联课程获取培训计划:{}", planDos);
            if (!planDos.isEmpty()) {
                return R.errorWithMsg("课程主题:" + mapInfo.getKey()
                        + "已被 课程培训计划:" +
                        planDos.stream().map(PlanDo::getCoursename).collect(Collectors.joining(","))
                        + "使用不可删除");
            }
        }
        return R.ok();
    }
}
