package com.yonge.cooleshow.biz.dal.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonge.cooleshow.biz.dal.vo.CourseHomeworkDetailVo;
import org.springframework.stereotype.Service;
import com.yonge.cooleshow.biz.dal.entity.StudentCourseHomework;
import com.yonge.cooleshow.biz.dal.vo.StudentCourseHomeworkVo;
import com.yonge.cooleshow.biz.dal.dto.search.StudentCourseHomeworkSearch;
import com.yonge.cooleshow.biz.dal.dao.StudentCourseHomeworkDao;
import com.yonge.cooleshow.biz.dal.service.StudentCourseHomeworkService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Service
public class StudentCourseHomeworkServiceImpl extends ServiceImpl<StudentCourseHomeworkDao, StudentCourseHomework> implements StudentCourseHomeworkService {

	@Override
    public StudentCourseHomeworkVo detail(Long id) {
        StudentCourseHomeworkVo detail = baseMapper.detail(id);
        return detail;
    }
    
     @Override
    public IPage<StudentCourseHomeworkVo> selectPage(IPage<StudentCourseHomeworkVo> page, StudentCourseHomeworkSearch query){
        return page.setRecords(baseMapper.selectPage(page, query));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean reviewCourseHome(Long studentHomeworkId, String review) {
        return this.lambdaUpdate()
                .eq(StudentCourseHomework::getId,studentHomeworkId)
                .set(StudentCourseHomework::getTeacherReplied,review)
                .update();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean submitCourseHome(CourseHomeworkDetailVo courseHomeworkDetailVo, String submit, Long studentId) {

        StudentCourseHomework studentCourseHomework = this.lambdaQuery()
                                        .eq(StudentCourseHomework::getStudentId, studentId)
                                        .eq(StudentCourseHomework::getCourseScheduleId, courseHomeworkDetailVo.getCourseScheduleId())
                                        .last("limit 1")
                                        .one();
        if (studentCourseHomework == null) {
            studentCourseHomework = new StudentCourseHomework();
            studentCourseHomework.setSubmitTime(new Date());
        }
        studentCourseHomework.setCourseHomeworkId(courseHomeworkDetailVo.getId());
        studentCourseHomework.setCourseGroupType(courseHomeworkDetailVo.getCourseType().getCode());
        studentCourseHomework.setCourseGroupId(courseHomeworkDetailVo.getCourseGroupId());
        studentCourseHomework.setCourseScheduleId(courseHomeworkDetailVo.getCourseScheduleId());
        studentCourseHomework.setStudentId(studentId);
        studentCourseHomework.setAttachments(submit);
        studentCourseHomework.setTeacherReplied("");
        return this.saveOrUpdate(studentCourseHomework);
    }

}