package com.ym.mec.education.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ym.mec.education.base.BaseResponse;
import com.ym.mec.education.base.PageResponse;
import com.ym.mec.education.entity.*;
import com.ym.mec.education.enums.ReturnCodeEnum;
import com.ym.mec.education.mapper.StudentCourseHomeworkMapper;
import com.ym.mec.education.req.HomeWorkDetailReq;
import com.ym.mec.education.req.HomeWorkReq;
import com.ym.mec.education.resp.CourseHomeworkResp;
import com.ym.mec.education.resp.HomeWrokDetailResp;
import com.ym.mec.education.resp.HomeWrokResp;
import com.ym.mec.education.resp.HomeworkReplyResp;
import com.ym.mec.education.service.*;
import com.ym.mec.education.utils.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 学生课程作业 服务实现类
 * </p>
 *
 * @author lemeng
 * @since 2019-09-25
 */
@Service("IStudentCourseHomeworkService")
public class StudentCourseHomeworkServiceImpl extends ServiceImpl<StudentCourseHomeworkMapper, StudentCourseHomework> implements IStudentCourseHomeworkService {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IClassGroupService classGroupService;

    @Autowired
    private IMusicGroupService musicGroupService;

    @Autowired
    private IStudentCourseHomeworkReplyService studentCourseHomeworkReplyService;

    @Autowired
    private ICourseScheduleService courseScheduleService;

    @Autowired
    private ICourseHomeworkService courseHomeworkService;

    @Override
    public PageResponse workList(HomeWorkReq req) {

        PageResponse response = new PageResponse();
        QueryWrapper<SysUser> userQueryWrapper = new QueryWrapper<>();

        List<SysUser> userList = null;
        if(req != null && StringUtils.isEmpty(req.getName())){
            userQueryWrapper.like("real_name_",req.getName());
            userList = sysUserService.list(userQueryWrapper);
        }

        List<Integer> userIds = null;
        if(!CollectionUtils.isEmpty(userList)){
            userIds = userList.stream().map(SysUser::getId).collect(Collectors.toList());
        }
        IPage ipage = new Page(req.getPageNo() == null ? 1: req.getPageNo(),req.getPageSize() == null ? 10:req.getPageSize());
        QueryWrapper<StudentCourseHomework> queryWrapper = new QueryWrapper<>();
      if(userIds != null && !userIds.isEmpty()){
            queryWrapper.in("user_id_",userIds);
        }
        queryWrapper.eq("course_schedule_id_",req.getCourseScheduleId());
        IPage<StudentCourseHomework> homeworkIPage =  this.page(ipage,queryWrapper);

        List<StudentCourseHomework> courseHomeworkList = homeworkIPage.getRecords();

        List<HomeWrokResp> homeWrokRespList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(courseHomeworkList)){
            courseHomeworkList.forEach(e ->{
                HomeWrokResp homeWrokResp = new HomeWrokResp();
                BeanUtils.copyProperties(e,homeWrokResp);
                homeWrokResp.setId(e.getId());
                homeWrokResp.setCourseHomeworkId(e.getCourseHomeworkId());
                SysUser sysUser = sysUserService.getById(e.getUserId());
                if(sysUser != null){
                    homeWrokResp.setAvatar(sysUser.getAvatar());
                    homeWrokResp.setName(sysUser.getRealName());
                }
                homeWrokRespList.add(homeWrokResp);
            });

        }

        response.setReturnCode(ReturnCodeEnum.CODE_200.getCode());
        response.setMessage(ReturnCodeEnum.CODE_200.getValue());
        response.setRecords(homeWrokRespList);
        response.setTotal(Math.toIntExact(homeworkIPage.getTotal()));
        return response;
    }

    /**
     * 查询作业详情
     * @param req
     * @return
     */
    @Override
    public BaseResponse getHomeWorkDetail(HomeWorkDetailReq req) {

        HomeWrokDetailResp resp = new HomeWrokDetailResp();
       /* MusicGroup musicGroup = musicGroupService.getById(req.getMusicGroupId());
        if(musicGroup == null){
            return  BaseResponse.noDataExists();
        }
        ClassGroup classGroup =  classGroupService.getById(req.getClassGroupId());
        if(classGroup == null){
            return  BaseResponse.noDataExists();
        }*/
        StudentCourseHomework homework = this.getById(req.getWorkId());
        if(homework == null){
            return  BaseResponse.noDataExists();
        }
        BeanUtils.copyProperties(homework,resp);
        //resp.setGroupName(musicGroup.getName());
        //resp.setClassName(classGroup.getName());

        //回复留言
        QueryWrapper<StudentCourseHomeworkReply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_course_homework_id_",req.getWorkId());
        List<StudentCourseHomeworkReply> replyList = studentCourseHomeworkReplyService.list(queryWrapper);
        List<HomeworkReplyResp> replyResps = new ArrayList<>();
        if(!CollectionUtils.isEmpty(replyList)){
            replyList.forEach(r ->{
                HomeworkReplyResp replyResp = new HomeworkReplyResp();
                BeanUtils.copyProperties(r,replyResp);
                SysUser sysUser = sysUserService.getById(r.getUserId());
                if(sysUser != null){
                    replyResp.setName(sysUser.getRealName());
                    replyResp.setAvatar(sysUser.getAvatar());
                }
                replyResps.add(replyResp);
            });
            resp.setHomeworkReplyList(replyResps);
        }
        return BaseResponse.success(resp);
    }

    /**
     * 作业列表
     * @param req
     * @return
     */
    @Override
    public PageResponse homeWorkList(HomeWorkReq req) {
        PageResponse response = new PageResponse();
        IPage ipage = new Page(req.getPageNo() == null ? 1: req.getPageNo(),req.getPageSize() == null ? 10:req.getPageSize());
        QueryWrapper<CourseHomework> queryWrapper = new QueryWrapper<>();
        if(req != null && req.getWorkDate() != null){
            String strDateStr = req.getWorkDate() + " 00:00:00";
            String endDateStr = req.getWorkDate() + " 23:59:59";
            queryWrapper.between("create_time_",strDateStr,endDateStr);
        }
        IPage<CourseHomework> courseScheduleIPage = courseHomeworkService.page(ipage,queryWrapper);

        List<CourseHomework> courseSchedules = courseScheduleIPage.getRecords();
        List<CourseHomeworkResp> courseHomeworkRespList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(courseSchedules)){
            courseSchedules.forEach(e ->{
                CourseHomeworkResp resp = new CourseHomeworkResp();
                BeanUtils.copyProperties(e,resp);
                CourseSchedule courseSchedule =  courseScheduleService.getById(e.getCourseScheduleId());
                if(courseSchedule != null){

                    ClassGroup classGroup = classGroupService.getById(courseSchedule.getClassGroupId());
                    if(classGroup != null){
                       MusicGroup musicGroup = musicGroupService.getById(classGroup.getMusicGroupId());
                       if(musicGroup != null){
                           resp.setGroupName(musicGroup.getName());
                       }
                    }
                    resp.setCourseName(courseSchedule.getName());

                }
                ClassGroup classGroup = classGroupService.getById(e.getClassGroupId());
                if(classGroup != null){
                    resp.setTotalClassTimes(classGroup.getTotalClassTimes());
                    resp.setCurrentClassTimes(classGroup.getCurrentClassTimes());
                }
                courseHomeworkRespList.add(resp);
            });
        }
        response.setRecords(courseHomeworkRespList);
        response.setTotal(Math.toIntExact(courseScheduleIPage.getTotal()));
        response.setCurrent(Math.toIntExact(courseScheduleIPage.getCurrent()));
        response.setSize(Math.toIntExact(courseScheduleIPage.getSize()));
        response.setReturnCode(ReturnCodeEnum.CODE_200.getCode());
        response.setMessage(ReturnCodeEnum.CODE_200.getValue());
        return response;
    }
}
