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.StudentAttendanceStatusEnum;
import com.ym.mec.education.enums.TeachTypeEnum;
import com.ym.mec.education.mapper.VipGroupMapper;
import com.ym.mec.education.req.VipGroupReq;
import com.ym.mec.education.resp.VipClassAttendanceResp;
import com.ym.mec.education.resp.VipClassScheduleResp;
import com.ym.mec.education.resp.VipGroupResp;
import com.ym.mec.education.service.*;
import com.ym.mec.education.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * vip课 服务实现类
 * </p>
 *
 * @author lemeng
 * @since 2019-09-25
 */
@Service("IVipGroupService")
public class VipGroupServiceImpl extends ServiceImpl<VipGroupMapper, VipGroup> implements IVipGroupService {

    @Autowired
    private ICourseScheduleService courseScheduleService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IClassGroupService classGroupService;
    @Autowired
    private IClassGroupStudentMapperService classGroupStudentMapperService;
    @Autowired
    private IVipGroupClassGroupMapperService vipGroupClassGroupMapperService;

    @Autowired
    private IStudentAttendanceService studentAttendanceService;
    @Autowired
    private IClassGroupTeacherMapperService classGroupTeacherMapperService;

    @Override
    public BaseResponse getInfo(VipGroupReq vipGroupReq) {
        if (Objects.isNull(vipGroupReq.getVipGroupId())) {
            return BaseResponse.errorParam();
        }
        VipGroupResp vipGroupResp = new VipGroupResp();
        QueryWrapper<VipGroupClassGroupMapper> vipGroupClassGroupMapperQueryWrapper = new QueryWrapper<>();
        vipGroupClassGroupMapperQueryWrapper.lambda().eq(VipGroupClassGroupMapper::getVipGroupId, vipGroupReq.getVipGroupId());
        VipGroupClassGroupMapper vipGroupClassGroupMapper = vipGroupClassGroupMapperService.getOne(vipGroupClassGroupMapperQueryWrapper);
        if (Objects.nonNull(vipGroupClassGroupMapper)) {
            QueryWrapper<ClassGroupTeacherMapper> classGroupTeacherMapperQueryWrapper = new QueryWrapper();
            classGroupTeacherMapperQueryWrapper.lambda().eq(ClassGroupTeacherMapper::getClassGroupId, vipGroupClassGroupMapper.getClassGroupId())
                    .eq(ClassGroupTeacherMapper::getTeacherRole, TeachTypeEnum.BISHOP.getCode());
            ClassGroupTeacherMapper classGroupTeacherMapper = classGroupTeacherMapperService.getOne(classGroupTeacherMapperQueryWrapper);
            if (Objects.nonNull(classGroupTeacherMapper)) {
                Optional.ofNullable(userService.getById(classGroupTeacherMapper.getUserId())).
                        ifPresent(sysUser -> vipGroupResp.setTeacher(sysUser.getRealName()));
            }
            ClassGroup classGroupResult = classGroupService.getById(vipGroupClassGroupMapper.getClassGroupId());
            Optional.ofNullable(classGroupResult).ifPresent(classGroup -> {
                if (Objects.nonNull(classGroup.getCurrentClassTimes()) && Objects.nonNull(classGroup.getTotalClassTimes())) {
                    vipGroupResp.setCourseProgress(classGroup.getCurrentClassTimes() + "/" + classGroup.getTotalClassTimes());
                }
                QueryWrapper<ClassGroupStudentMapper> classGroupStudentMapperQueryWrapper = new QueryWrapper<>();
                classGroupStudentMapperQueryWrapper.lambda().eq(ClassGroupStudentMapper::getClassGroupId, classGroup.getId());
                List<ClassGroupStudentMapper> classGroupStudentMapperList = classGroupStudentMapperService.list(classGroupStudentMapperQueryWrapper);
                if (!CollectionUtils.isEmpty(classGroupStudentMapperList)) {
                    QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
                    sysUserQueryWrapper.lambda().in(SysUser::getId, classGroupStudentMapperList.stream().map(ClassGroupStudentMapper::getUserId).collect(Collectors.toList()));
                    List<SysUser> studentList = userService.list(sysUserQueryWrapper);
                    if (!CollectionUtils.isEmpty(studentList)) {
                        vipGroupResp.setStudentList(studentList.stream().map(SysUser::getRealName).collect(Collectors.toList()));
                    }
                }
            });
        }
        return BaseResponse.success(vipGroupResp);
    }

    /**
     * 点名记录
     *
     * @param vipGroupReq
     * @return
     */
    @Override
    public PageResponse courseList(VipGroupReq vipGroupReq) {
        QueryWrapper<VipGroupClassGroupMapper> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("vip_group_id_", vipGroupReq.getVipGroupId());
        VipGroupClassGroupMapper vipGroupClassGroupMapper = vipGroupClassGroupMapperService.getOne(queryWrapper);
        if (vipGroupClassGroupMapper == null) {
            return PageResponse.errorParam();
        }

        PageResponse response = new PageResponse();

        IPage page = new Page(vipGroupReq.getPageNo() == null ? 1 : vipGroupReq.getPageNo(), vipGroupReq.getPageSize() == null ? 10 : vipGroupReq.getPageSize());

        QueryWrapper<CourseSchedule> scheduleQueryWrapper = new QueryWrapper<>();
        scheduleQueryWrapper.eq("class_group_id_", vipGroupClassGroupMapper.getClassGroupId());
        IPage<CourseSchedule> scheduleIPage = courseScheduleService.page(page, scheduleQueryWrapper);


        List<VipClassScheduleResp> vipClassScheduleRespList = new ArrayList<>();
        List<CourseSchedule> courseSchedules = scheduleIPage.getRecords();
        if (!CollectionUtils.isEmpty(courseSchedules)) {
            ClassGroup classGroup = classGroupService.getById(vipGroupClassGroupMapper.getClassGroupId());
            courseSchedules.forEach(e -> {
                VipClassScheduleResp vipClassScheduleResp = new VipClassScheduleResp();
                vipClassScheduleResp.setClassGroupId(e.getClassGroupId());
                vipClassScheduleResp.setClassName(e.getName());
                vipClassScheduleResp.setDateStr(DateUtil.date2String(e.getClassDate(), DateUtil.DATE_FORMAT));
                vipClassScheduleResp.setStartTime(DateUtil.date2String(e.getStartClassTime(), DateUtil.TIME_FORMAT));
                vipClassScheduleResp.setEndTime(DateUtil.date2String(e.getEndClassTime(), DateUtil.TIME_FORMAT));
                vipClassScheduleResp.setStatus(e.getStatus());
                vipClassScheduleResp.setWeek(DateUtil.date2Week(e.getClassDate()));
                if (classGroup != null) {
                    vipClassScheduleResp.setCurrentNum(classGroup.getCurrentClassTimes());
                    vipClassScheduleResp.setTotalNum(classGroup.getTotalClassTimes());
                }
                vipClassScheduleRespList.add(vipClassScheduleResp);
            });

        }

        response.setCurrent(Math.toIntExact(scheduleIPage.getCurrent()));
        response.setSize(Math.toIntExact(scheduleIPage.getSize()));
        response.setTotal(Math.toIntExact(scheduleIPage.getTotal()));
        response.setRecords(vipClassScheduleRespList);
        return response;
    }


    /**
     * @param vipGroupReq
     * @return
     */
    @Override
    public PageResponse attendanceList(VipGroupReq vipGroupReq) {
        QueryWrapper<VipGroupClassGroupMapper> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("vip_group_id_", vipGroupReq.getVipGroupId());
        VipGroupClassGroupMapper vipGroupClassGroupMapper = vipGroupClassGroupMapperService.getOne(queryWrapper);
        if (vipGroupClassGroupMapper == null) {
            return PageResponse.errorParam();
        }

        PageResponse response = new PageResponse();

        IPage page = new Page(vipGroupReq.getPageNo() == null ? 1 : vipGroupReq.getPageNo(), vipGroupReq.getPageSize() == null ? 10 : vipGroupReq.getPageSize());

        QueryWrapper<StudentAttendance> studentAttendanceQueryWrapper = new QueryWrapper<>();
        studentAttendanceQueryWrapper.eq("class_group_id_", vipGroupClassGroupMapper.getClassGroupId());
        IPage<StudentAttendance> studentAttendanceIPage = studentAttendanceService.page(page, studentAttendanceQueryWrapper);


        List<StudentAttendance> studentAttendanceList = studentAttendanceIPage.getRecords();
        if (!CollectionUtils.isEmpty(studentAttendanceList)) {
            List<String> studentList = new ArrayList<>();
            int leaveNum = 0;
            QueryWrapper<StudentAttendance> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("class_group_id_", vipGroupClassGroupMapper.getClassGroupId());
            List<StudentAttendance> allList = studentAttendanceService.list(queryWrapper1);


            if (!CollectionUtils.isEmpty(allList)) {

                List<StudentAttendance> norList = allList.stream().filter(e -> StudentAttendanceStatusEnum.NORMAL.getCode().equals(e.getStatus())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(norList)) {
                    List<Integer> userIds = norList.stream().map(StudentAttendance::getUserId).collect(Collectors.toList());
                    QueryWrapper<SysUser> queryWrapper2 = new QueryWrapper<>();
                    queryWrapper2.in("id_", userIds);
                    List<SysUser> sysUserList = userService.list(queryWrapper2);
                    if (!CollectionUtils.isEmpty(sysUserList)) {
                        studentList = sysUserList.stream().map(SysUser::getRealName).collect(Collectors.toList());
                    }
                }

                List<StudentAttendance> leaveList = allList.stream().filter(e -> StudentAttendanceStatusEnum.LEAVE.getCode().equals(e.getStatus())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(leaveList)) {
                    leaveNum = leaveList.size();
                }
            }

            List<String> finalStudentList = studentList;
            int finalLeaveNum = leaveNum;
            List<VipClassAttendanceResp> vipClassAttendanceRespList = new ArrayList<>();
            studentAttendanceList.forEach(e -> {
                VipClassAttendanceResp vipClassAttendanceResp = new VipClassAttendanceResp();
                vipClassAttendanceResp.setClassGroupId(vipGroupClassGroupMapper.getClassGroupId());

                CourseSchedule courseSchedule = courseScheduleService.getById(e.getCourseScheduleId());
                if (courseSchedule != null) {
                    vipClassAttendanceResp.setDateStr(DateUtil.date2String(courseSchedule.getClassDate(), DateUtil.DATE_FORMAT));
                    vipClassAttendanceResp.setStartTime(DateUtil.date2String(courseSchedule.getStartClassTime(), DateUtil.TIME_FORMAT));
                    vipClassAttendanceResp.setEndTime(DateUtil.date2String(courseSchedule.getEndClassTime(), DateUtil.TIME_FORMAT));
                    vipClassAttendanceResp.setWeek(DateUtil.date2Week(courseSchedule.getClassDate()));
                    vipClassAttendanceResp.setClassName(courseSchedule.getName());
                }
                ClassGroup classGroup = classGroupService.getById(vipGroupClassGroupMapper.getClassGroupId());
                if (classGroup != null) {
                    vipClassAttendanceResp.setCurrentNum(classGroup.getCurrentClassTimes());
                    vipClassAttendanceResp.setTotalNum(classGroup.getTotalClassTimes());
                }
                vipClassAttendanceResp.setStudentList(finalStudentList);
                vipClassAttendanceResp.setLeaveNum(finalLeaveNum);
                vipClassAttendanceRespList.add(vipClassAttendanceResp);
            });
            response.setCurrent(Math.toIntExact(studentAttendanceIPage.getCurrent()));
            response.setSize(Math.toIntExact(studentAttendanceIPage.getSize()));
            response.setTotal(Math.toIntExact(studentAttendanceIPage.getTotal()));
            response.setRecords(vipClassAttendanceRespList);
            return response;

        }

        return PageResponse.success(studentAttendanceIPage);
    }


}
