package com.qmth.distributed.print.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.distributed.print.business.bean.params.CourseEvaluationParam;
import com.qmth.distributed.print.business.bean.result.CourseEvaluationResult;
import com.qmth.distributed.print.business.entity.CourseEvaluation;
import com.qmth.distributed.print.business.entity.CourseWeight;
import com.qmth.distributed.print.business.entity.TeachCourse;
import com.qmth.distributed.print.business.enums.CourseEvaluationTypeEnum;
import com.qmth.distributed.print.business.enums.CourseSettingTypeEnum;
import com.qmth.distributed.print.business.mapper.CourseEvaluationMapper;
import com.qmth.distributed.print.business.service.CourseEvaluationService;
import com.qmth.distributed.print.business.service.CourseWeightService;
import com.qmth.distributed.print.business.service.TeachCourseService;
import com.qmth.teachcloud.common.base.BaseEntity;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.util.ServletUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程评价方式 服务实现类
 * </p>
 *
 * @author CaoZixuan
 * @since 2024-02-22
 */
@Service
public class CourseEvaluationServiceImpl extends ServiceImpl<CourseEvaluationMapper, CourseEvaluation> implements CourseEvaluationService {

    @Resource
    private TeachCourseService teachCourseService;
    @Resource
    private CourseWeightService courseWeightService;

    @Override
    public List<CourseEvaluationResult> findCourseEvaluationList(Long teachCourseId) {
        TeachCourse teachCourse = teachCourseService.getById(teachCourseId);
        if (Objects.isNull(teachCourse)) {
            throw ExceptionResultEnum.ERROR.exception("教学课程不存在");
        }
        return this.baseMapper.findCourseEvaluationList(teachCourseId);
    }

    @Transactional
    @Override
    public void saveCourseEvaluation(CourseEvaluationParam courseEvaluationParam) {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();

        Long id = courseEvaluationParam.getId();
        Long teachCourseId = courseEvaluationParam.getTeachCourseId();
        String evaluation = courseEvaluationParam.getEvaluation();
        String evaluationDesc = courseEvaluationParam.getEvaluationDesc();
        CourseEvaluationTypeEnum type = courseEvaluationParam.getType();
        TeachCourse teachCourse = teachCourseService.getById(teachCourseId);
        if (Objects.isNull(teachCourse)) {
            throw ExceptionResultEnum.ERROR.exception("教学课程不存在");
        }
        Long examId = teachCourse.getExamId();
        String courseCode = teachCourse.getCourseCode();

        if (SystemConstant.longNotNull(id)) {
            // 编辑（只允许更改评价方式描述）
            CourseEvaluation db = this.getById(id);
            if (Objects.isNull(db)) {
                throw ExceptionResultEnum.ERROR.exception("评价方式不存在");
            }
            if (!Objects.equals(db.getEvaluationDesc(), evaluationDesc)) {
                db.updateInfo(requestUser.getId());
                db.setEvaluationDesc(evaluationDesc);
                this.updateById(db);

                // 重置权重设置标识
                teachCourseService.update(new UpdateWrapper<TeachCourse>().lambda().eq(TeachCourse::getId, teachCourseId)
                        .set(TeachCourse::getWeightSettingSign, SystemConstant.getDbUuid()));
            }
        } else {
            // 新增
            if (this.count(
                    new QueryWrapper<CourseEvaluation>().lambda().eq(CourseEvaluation::getTeachCourseId, teachCourseId)
                            .eq(CourseEvaluation::getEvaluation, evaluation)) > 0) {
                throw ExceptionResultEnum.ERROR.exception("评价方式重复");
            }
            CourseEvaluation courseEvaluation = new CourseEvaluation();
            courseEvaluation.setTeachCourseId(teachCourseId);
            courseEvaluation.setSchoolId(teachCourse.getSchoolId());
            courseEvaluation.setExamId(examId);
            courseEvaluation.setCourseCode(courseCode);
            courseEvaluation.setUserId(teachCourse.getUserId());
            courseEvaluation.setType(type);
            courseEvaluation.setEvaluation(evaluation);
            courseEvaluation.setEvaluationDesc(evaluationDesc);
            courseEvaluation.insertInfo(requestUser.getId());
            this.save(courseEvaluation);
        }
    }

    @Transactional
    @Override
    public void deleteCourseEvaluation(Long id) {
        CourseEvaluation courseEvaluation = this.getById(id);
        if (Objects.nonNull(courseEvaluation)) {
            if (CourseEvaluationTypeEnum.DEFAULT.equals(courseEvaluation.getType())) {
                throw ExceptionResultEnum.ERROR.exception(String.format("[%s]的评价方式不能删除", CourseEvaluationTypeEnum.DEFAULT.getType()));
            }
            Long teachCourseId = courseEvaluation.getTeachCourseId();

            // 该评价方式涉及到的权重
            List<CourseWeight> courseWeightList = courseWeightService.list(
                    new QueryWrapper<CourseWeight>().lambda().eq(CourseWeight::getTeachCourseId, teachCourseId)
                            .eq(CourseWeight::getEvaluationId, id));

            if (CollectionUtils.isNotEmpty(courseWeightList)) {
                if (courseWeightList.stream().anyMatch(CourseWeight::getEnable)) {
                    // 该评价方式有被用到，删除所有权重设置
                    teachCourseService.clearCourseSetting(teachCourseId, CourseSettingTypeEnum.COURSE_EVALUATION);
                } else {
                    // 该评价方式没有用到，删除权重中涉及该评价方式的记录
                    teachCourseService.removeByIds(courseWeightList.stream().map(BaseEntity::getId).collect(Collectors.toList()));
                }
            }
            this.removeById(id);
        }
    }

    @Transactional
    @Override
    public void createDefaultCourseEvaluation(Long teachCourseId) {
        // 创建默认评价方式
        CourseEvaluationTypeEnum type = CourseEvaluationTypeEnum.DEFAULT;
        CourseEvaluationParam courseEvaluationParam = new CourseEvaluationParam();
        courseEvaluationParam.setTeachCourseId(teachCourseId);
        courseEvaluationParam.setEvaluation(type.getName());
        courseEvaluationParam.setEvaluationDesc(type.getValue());
        courseEvaluationParam.setType(type);
        this.saveCourseEvaluation(courseEvaluationParam);
    }
}