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

import com.ym.mec.biz.dal.dao.ClassGroupStudentMapperDao;
import com.ym.mec.biz.dal.entity.*;
import com.ym.mec.biz.dal.enums.ClassGroupStudentStatusEnum;
import com.ym.mec.biz.dal.enums.ClassGroupTypeEnum;
import com.ym.mec.biz.dal.enums.GroupType;
import com.ym.mec.biz.service.*;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.entity.ImGroupMember;
import com.ym.mec.common.entity.ImGroupModel;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.im.ImFeignService;
import com.ym.mec.util.http.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ClassGroupStudentMapperServiceImpl extends BaseServiceImpl<Long, ClassGroupStudentMapper> implements ClassGroupStudentMapperService {

    @Autowired
    private ClassGroupStudentMapperDao classGroupStudentMapperDao;

    @Autowired
    private CourseScheduleService courseScheduleService;
    @Autowired
    StudentRegistrationService studentRegistrationService;
    @Autowired
    private CourseScheduleStudentPaymentService courseScheduleStudentPaymentService;
    @Autowired
    private ClassGroupService classGroupService;
    @Autowired
    private ClassGroupRelationService classGroupRelationService;
    @Autowired
    private ImFeignService imFeignService;

    private static String holidayUrl = "http://tool.bitefu.net/jiari/?d=";

    @Override
    public BaseDAO<Long, ClassGroupStudentMapper> getDAO() {
        return classGroupStudentMapperDao;
    }

    @Override
    public ClassGroupStudentMapper findClassStudentMapperByUserIdAndClassGroupId(Integer userId, Integer classGroupId,String status) {
        return classGroupStudentMapperDao.findClassStudentMapperByUserIdAndClassGroupId(userId, classGroupId, status);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delClassGroupStudent(Integer userId, Integer classGroupId) throws Exception {
        ClassGroupStudentMapper classStudentMapper = findClassStudentMapperByUserIdAndClassGroupId(userId, classGroupId,"NORMAL");
        if (classStudentMapper == null) {
            throw new BizException("班级学生不存在");
        }
        //1、删除班级学生对应班级关系
        classStudentMapper.setStatus(ClassGroupStudentStatusEnum.QUIT);
        update(classStudentMapper);
        StudentRegistration student = studentRegistrationService.findStudentByClassGroupIdAndUserId(userId, classGroupId);
        if (student != null) {
            student.setClassGroupId(0);
            studentRegistrationService.update(student);
        }

        //2、班级人数调整
        classGroupService.updateClassStudentNum(classGroupId.longValue(), -1);

        //3、删除学生对应班级的课程
        List<CourseSchedule> courseScheduleList = courseScheduleService.findNoStartCoursesByClassGroupId(classGroupId);
        if (courseScheduleList.size() > 0) {
            courseScheduleStudentPaymentService.deleteStudentCourseSchedule(userId, courseScheduleList);
        }

        //4、学生退出班级群组
        ClassGroup classGroup = classGroupService.get(classGroupId);

        ImGroupMember[] imGroupMembers = {new ImGroupMember(userId.toString())};
        // 退出群组
        imFeignService.groupQuit(new ImGroupModel(classGroup.getId().toString(), imGroupMembers, classGroup.getName()));
        return true;
    }

    @Override
    public List<StudentRegistration> findClassStudentList(Integer classGroupId, ClassGroupStudentStatusEnum status) {
        return classGroupStudentMapperDao.findClassStudentList(classGroupId, status);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean adjustClassGroup(Integer userId, Integer oldClassGroupId, Integer classGroupId) throws Exception {
        ClassGroupStudentMapper classStudentMapper = findClassStudentMapperByUserIdAndClassGroupId(userId, oldClassGroupId,"NORMAL");
        if (classStudentMapper == null) {
            throw new BizException("原班级学生不存在");
        }
        Date date = new Date();
        //1、更新学生对应班级关系
        classStudentMapper.setClassGroupId(classGroupId);
        update(classStudentMapper);
        //班级人数调整
        classGroupService.updateClassStudentNum(oldClassGroupId.longValue(), -1);
        classGroupService.updateClassStudentNum(classGroupId.longValue(), 1);

        //2、删除学生对应原班级未开始课程
        List<CourseSchedule> courseScheduleList = courseScheduleService.findNoStartCoursesByClassGroupId(oldClassGroupId);
        courseScheduleStudentPaymentService.deleteStudentCourseSchedule(userId, courseScheduleList);

        //3、学生加入新班级未开始课程
        courseScheduleList = courseScheduleService.findNoStartCoursesByClassGroupId(classGroupId);

        BigDecimal coursePrice = new BigDecimal("0");
        List<CourseScheduleStudentPayment> courseScheduleStudentPayments = new ArrayList<>();
        for (CourseSchedule courseSchedule : courseScheduleList) {
            CourseScheduleStudentPayment courseScheduleStudentPayment = new CourseScheduleStudentPayment();
            courseScheduleStudentPayment.setGroupType(courseSchedule.getGroupType());
            courseScheduleStudentPayment.setMusicGroupId(courseSchedule.getMusicGroupId());
            courseScheduleStudentPayment.setCourseScheduleId(courseSchedule.getId());
            courseScheduleStudentPayment.setUserId(userId);
            courseScheduleStudentPayment.setExpectPrice(coursePrice);
            courseScheduleStudentPayment.setClassGroupId(classGroupId);
            courseScheduleStudentPayment.setCreateTime(date);
            courseScheduleStudentPayment.setUpdateTime(date);
            courseScheduleStudentPayments.add(courseScheduleStudentPayment);
        }
        if (courseScheduleStudentPayments.size() == 0) {
            return true;
        }

        courseScheduleStudentPaymentService.batchInsert(courseScheduleStudentPayments);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addStudents(Integer classGroupId, String userIdsStr, GroupType groupType) throws Exception {
        ClassGroup classGroup = classGroupService.get(classGroupId);
        if (classGroup == null) {
            throw new BizException("添加学员的班级不存在");
        }
        Date nowDate = new Date();
        HashSet<String> userIdStrSet = new HashSet<>(Arrays.asList(userIdsStr.split(",")));

        //1、班级关系添加
        List<ClassGroupStudentMapper> classGroupStudentMappers = new ArrayList<>();
        List<ImGroupMember> imGroupMemberList = new ArrayList<>();

        ClassGroupRelation classGroupRelation = classGroupRelationService.findClassGroupRelation(classGroupId);

        Iterator<String> iterator = userIdStrSet.iterator();
        while (iterator.hasNext()) {
            Integer userId = Integer.parseInt(iterator.next());
            List<ClassGroupStudentMapper> highClassGroupHasUser = classGroupStudentMapperDao.findHighClassGroupHasUser(classGroup.getMusicGroupId(), userId, classGroup.getType());
            if (!classGroup.getType().equals(ClassGroupTypeEnum.SNAP) && highClassGroupHasUser != null && highClassGroupHasUser.size() > 0) {
                iterator.remove();
                continue;
            }
            
            ClassGroupStudentMapper classGroupStudentMapper = new ClassGroupStudentMapper();
            classGroupStudentMapper.setMusicGroupId(classGroup.getMusicGroupId());
            classGroupStudentMapper.setClassGroupId(classGroupId);
            classGroupStudentMapper.setUserId(userId);
            classGroupStudentMapper.setCreateTime(nowDate);
            classGroupStudentMapper.setStatus(ClassGroupStudentStatusEnum.NORMAL);
            classGroupStudentMapper.setGroupType(GroupType.MUSIC);
            classGroupStudentMappers.add(classGroupStudentMapper);

            if (classGroup.getType().equals(ClassGroupTypeEnum.NORMAL)) {
                StudentRegistration studentRegistration = studentRegistrationService.queryByUserIdAndMusicGroupId(userId, classGroup.getMusicGroupId());
                studentRegistration.setClassGroupId(classGroupId);
                studentRegistrationService.update(studentRegistration);
            }
            imGroupMemberList.add(new ImGroupMember(userId.toString()));
        }
        if (classGroupStudentMappers.size() > 0) {
            classGroupStudentMapperDao.classGroupStudentsInsert(classGroupStudentMappers);
        }

        //添加进IM群组
        ImGroupMember[] imGroupMembers = imGroupMemberList.toArray(new ImGroupMember[imGroupMemberList.size()]);
        imFeignService.groupJoin(new ImGroupModel(classGroup.getId().toString(), imGroupMembers, classGroup.getName()));

        //2、班级人数调整
        classGroupService.updateClassStudentNum(classGroupId.longValue(), userIdStrSet.size());

        //3、学生加入新班级未开始课程
        List<CourseSchedule> courseScheduleList = courseScheduleService.findNoStartCoursesByClassGroupId(classGroupId);

        List<CourseScheduleStudentPayment> courseScheduleStudentPayments = new ArrayList<>();
        for (CourseSchedule courseSchedule : courseScheduleList) {
            for (String userIdStr : userIdStrSet) {
                CourseScheduleStudentPayment courseScheduleStudentPayment = new CourseScheduleStudentPayment();
                courseScheduleStudentPayment.setGroupType(classGroup.getGroupType());
                courseScheduleStudentPayment.setMusicGroupId(classGroup.getMusicGroupId());
                courseScheduleStudentPayment.setCourseScheduleId(courseSchedule.getId());
                courseScheduleStudentPayment.setUserId(Integer.parseInt(userIdStr));
                courseScheduleStudentPayment.setExpectPrice(BigDecimal.ZERO);
                courseScheduleStudentPayment.setClassGroupId(classGroupId);
                courseScheduleStudentPayment.setCreateTime(nowDate);
                courseScheduleStudentPayment.setUpdateTime(nowDate);
                courseScheduleStudentPayments.add(courseScheduleStudentPayment);
            }
        }

        if (courseScheduleStudentPayments.size() > 0) {
            courseScheduleStudentPaymentService.batchInsert(courseScheduleStudentPayments);
        }
        //乐团在合奏班
        if (classGroupRelation != null) {
            addStudents(classGroupRelation.getClassGroupId(), userIdsStr, GroupType.MUSIC);
        }

        return true;
    }

    @Override
    public Object queryHoliday(String year) throws IOException {
        return HttpUtil.get(holidayUrl + year, null);
    }

    @Override
    public List<ClassGroupStudentMapper> findMusicGroupClassGroupByType(String musicGroupId, ClassGroupTypeEnum type) {
        return classGroupStudentMapperDao.findMusicGroupClassGroupByType(musicGroupId, type);
    }

    @Override
    public void classGroupStudentsInsert(List<ClassGroupStudentMapper> classGroupStudentMappers) {
        classGroupStudentMapperDao.classGroupStudentsInsert(classGroupStudentMappers);
    }
}
