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

import static com.ym.mec.biz.dal.entity.MusicGroupPaymentCalender.PayUserType.STUDENT;
import static com.ym.mec.biz.dal.entity.MusicGroupPaymentCalender.PaymentCalenderStatusEnum.AUDITING;
import static com.ym.mec.biz.dal.entity.MusicGroupStudentFee.PaymentStatus.NON_PAYMENT;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import com.ym.mec.biz.dal.entity.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ym.mec.biz.dal.dao.MusicGroupDao;
import com.ym.mec.biz.dal.dao.MusicGroupPaymentCalenderCourseSettingsDao;
import com.ym.mec.biz.dal.dao.MusicGroupPaymentCalenderDao;
import com.ym.mec.biz.dal.dao.MusicGroupPaymentCalenderDetailDao;
import com.ym.mec.biz.dal.dao.MusicGroupPaymentStudentCourseDetailDao;
import com.ym.mec.biz.dal.dao.MusicGroupStudentFeeDao;
import com.ym.mec.biz.dal.dao.SysConfigDao;
import com.ym.mec.biz.dal.dto.FeeStudentDto;
import com.ym.mec.biz.dal.dto.SimpleUserDto;
import com.ym.mec.biz.dal.entity.MusicGroupPaymentCalender.PaymentCalenderStatusEnum;
import com.ym.mec.biz.dal.entity.MusicGroupStudentFee.PaymentStatus;
import com.ym.mec.biz.dal.enums.MessageTypeEnum;
import com.ym.mec.biz.service.MusicGroupPaymentCalenderDetailService;
import com.ym.mec.biz.service.MusicGroupPaymentCalenderService;
import com.ym.mec.biz.service.SysConfigService;
import com.ym.mec.biz.service.SysMessageService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.thirdparty.message.MessageSenderPluginContext;
import com.ym.mec.util.collection.MapUtil;

@Service
public class MusicGroupPaymentCalenderDetailServiceImpl extends BaseServiceImpl<Long, MusicGroupPaymentCalenderDetail>  implements MusicGroupPaymentCalenderDetailService {
	
	@Autowired
	private MusicGroupPaymentCalenderDetailDao musicGroupPaymentCalenderDetailDao;
	@Autowired
	private MusicGroupPaymentCalenderDao musicGroupPaymentCalenderDao;
	@Autowired
	private MusicGroupPaymentCalenderService musicGroupPaymentCalenderService;
	
	@Autowired
	private MusicGroupPaymentCalenderCourseSettingsDao musicGroupPaymentCalenderCourseSettingsDao;
	
	@Autowired
	private MusicGroupPaymentStudentCourseDetailDao musicGroupPaymentStudentCourseDetailDao;
	
	@Autowired
	private MusicGroupDao musicGroupDao;
	@Autowired
	private SysConfigDao sysConfigDao;
	@Autowired
	private MusicGroupStudentFeeDao musicGroupStudentFeeDao;
	@Autowired
	private SysMessageService sysMessageService;

	@Override
	public BaseDAO<Long, MusicGroupPaymentCalenderDetail> getDAO() {
		return musicGroupPaymentCalenderDetailDao;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateExpectAmount(BigDecimal expectAmount,String ids) {
		if(expectAmount == null || StringUtils.isEmpty(ids)){
			throw new BizException("参数校验失败");
		}
		//获取缴费列表
		List<MusicGroupPaymentCalenderDetail> calenderDetails = musicGroupPaymentCalenderDetailDao.queryListByIds(ids);
		if(calenderDetails.size() == 0){
			throw new BizException("缴费记录不存在");
		}
		Date date = new Date();
		MusicGroupPaymentCalender calender = musicGroupPaymentCalenderService.get(calenderDetails.get(0).getMusicGroupPaymentCalenderId());
		Set<Integer> studentIds = new HashSet<>();
				calenderDetails.forEach(e->{
			if(e.getPaymentStatus() == null || e.getPaymentStatus() != NON_PAYMENT){
				throw new BizException("修改失败,缴费状态不匹配");
			}
			if(expectAmount.doubleValue() != 0){

			}
			/*if(expectAmount.doubleValue() == 0){
				e.setPaymentStatus(PAID_COMPLETED);
			}*/
			e.setUpdateTime(date);
			e.setExpectAmount(expectAmount);
			if(expectAmount.doubleValue() > 0){
				if((e.getOpen() != null && e.getOpen() == 1) || calender.getStatus() == PaymentCalenderStatusEnum.OPEN){
					studentIds.add(e.getUserId());
				}
			}
		});
		/*if(expectAmount.doubleValue() == 0){
			//如果是设置为0元
			MusicGroupPaymentCalender calender = musicGroupPaymentCalenderDao.get(calenderDetails.get(0).getMusicGroupPaymentCalenderId());
			if(calender.getType() == ONLINE){
				//剩余网管课可购买次数加一
				musicGroupStudentFeeDao.remainNetworkClassTimesAdd(ids);
			}
			//缴费完成
			musicGroupStudentFeeDao.setPaidCompleted(calenderDetails);
		}*/
		musicGroupPaymentCalenderDetailDao.batchUpdate(calenderDetails);
		//推送消息
		if (calender.getPayUserType() == STUDENT && studentIds.size() > 0) {
			String musicGroupId = calenderDetails.get(0).getMusicGroupId();
			Map<Integer, String> push = new HashMap<>();
			for (Integer userId : studentIds) {
				push.put(userId, userId + "");
			}
			MusicGroup musicGroup = musicGroupDao.get(musicGroupId);
			String baseUrl = sysConfigDao.findConfigValue(SysConfigService.BASE_API_URL);
			String memo = "4?" + baseUrl + "/#/musicGroupRenew?calenderId="+calender.getId()+"&id=" + calender.getMusicGroupId();
			// 发送续费通知
			sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.STUDENT_PUSH_WAIT_RENEW_MESSAGE, push,
					null, 0, memo,"STUDENT",musicGroup.getName());

			//获取未缴费且不是0元的学员列表
			Map<Integer,String> studentMaps = MapUtil.convertMybatisMap(musicGroupPaymentCalenderDetailDao.queryNoPaymentAndNotZeroStudent(calender.getId(),studentIds));
			if(studentMaps.size() > 0){
				sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.AWSMS, MessageTypeEnum.STUDENT_PUSH_WAIT_RENEW_MESSAGE, studentMaps,
						null, 0, memo, null, musicGroup.getName());
			}
		}
//		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public String openPayment(String ids) {
		if(StringUtils.isEmpty(ids)){
			throw new BizException("参数校验失败");
		}
		//获取可开启缴费列表
		List<MusicGroupPaymentCalenderDetail> calenderDetails = musicGroupPaymentCalenderDetailDao.queryCanOpenList(ids);
		if(calenderDetails.size() == 0){
			return "操作失败：所选学员已开启缴费，或已完成缴费";
		}
		int length = ids.split(",").length;
		Date date = new Date();
		Long calenderId = calenderDetails.get(0).getMusicGroupPaymentCalenderId();
		MusicGroupPaymentCalender calender = musicGroupPaymentCalenderService.get(calenderId);
		calenderDetails.forEach(e->{
			e.setUpdateTime(date);
			e.setOpen(1);
			e.setStartPaymentDate(date);
			e.setDeadlinePaymentDate(date);
		});
		musicGroupPaymentCalenderDetailDao.batchUpdate(calenderDetails);
		Set<Integer> studentIds = calenderDetails.stream().map(e -> e.getUserId()).collect(Collectors.toSet());
		//推送消息
		if (calender.getPayUserType() == STUDENT && studentIds.size() > 0) {
			Map<Integer, String> push = new HashMap<>();
			for (Integer userId : studentIds) {
				push.put(userId, userId + "");
			}
			MusicGroup musicGroup = musicGroupDao.get(calender.getMusicGroupId());
			String baseUrl = sysConfigDao.findConfigValue(SysConfigService.BASE_API_URL);
			String memo = "4?" + baseUrl + "/#/musicGroupRenew?calenderId="+calender.getId()+"&id=" + calender.getMusicGroupId();
			// 发送续费通知
			sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.STUDENT_PUSH_WAIT_RENEW_MESSAGE, push,
					null, 0, memo,"STUDENT",musicGroup.getName());
			//获取未缴费且不是0元的学员列表
			Map<Integer,String> studentMaps = MapUtil.convertMybatisMap(musicGroupPaymentCalenderDetailDao.queryNoPaymentAndNotZeroStudent(calender.getId(),studentIds));
			if(studentMaps.size() > 0){
				sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.AWSMS, MessageTypeEnum.STUDENT_PUSH_WAIT_RENEW_MESSAGE, studentMaps,
						null, 0, memo, null, musicGroup.getName());
			}
		}
		StringBuffer append = new StringBuffer("操作成功: 成功开启缴费").append(studentIds.size()).append("条,失败").append(length - studentIds.size()).append("条");
		return append.toString();
	}

	@Override
	public List<SimpleUserDto> findMusicGroupStudentWithSubject(String musicGroupId, Integer subjectId) {
		if(Objects.isNull(musicGroupId)){
			throw new BizException("请指定乐团");
		}
		return musicGroupPaymentCalenderDetailDao.findMusicGroupStudentWithSubject(musicGroupId, subjectId);
	}

	@Override
	public void refreshUserMusicGroupPaymentStatusTask() {
		musicGroupPaymentCalenderDetailDao.refreshUserMusicGroupPaymentStatusTask();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void add(Long musicGroupPaymentCalenderId, Integer userId) {
		if(musicGroupPaymentCalenderId == null || userId == null){
			throw new BizException("参数校验异常");
		}
		MusicGroupPaymentCalender calender = musicGroupPaymentCalenderService.get(musicGroupPaymentCalenderId);
		if(calender == null){
			throw new BizException("缴费信息不存在");
		}
		MusicGroupPaymentCalenderDetail musicGroupPaymentCalenderDetail = musicGroupPaymentCalenderDetailDao.findByCalenderIdAndUserId(musicGroupPaymentCalenderId, userId);
		if(musicGroupPaymentCalenderDetail != null){
			throw new BizException("新增失败，已经存在缴费记录");
		}
		
		List<MusicGroupPaymentCalenderCourseSettings> courseSettingsList = musicGroupPaymentCalenderCourseSettingsDao.getWithPaymentCalender(musicGroupPaymentCalenderId);
		
		BigDecimal totalPrice = new BigDecimal(0);
		if (calender.getPayUserType() == STUDENT) {
			for (MusicGroupPaymentCalenderCourseSettings courseSettings : courseSettingsList) {
				// 剔除可选课程
				if (courseSettings.getIsStudentOptional() == false) {
					totalPrice.add(courseSettings.getCourseCurrentPrice());
				}
				totalPrice.add(courseSettings.getCourseCurrentPrice());
			}
		}
		Date date = new Date();
		calender.setUpdateTime(date);
		calender.setExpectNum(calender.getExpectNum() + 1);
		musicGroupPaymentCalenderService.update(calender);
		//生成详情
		musicGroupPaymentCalenderDetail = new MusicGroupPaymentCalenderDetail();
		musicGroupPaymentCalenderDetail.setMusicGroupPaymentCalenderId(calender.getId());
		musicGroupPaymentCalenderDetail.setCreateTime(date);
		musicGroupPaymentCalenderDetail.setExpectAmount(totalPrice);
		if (musicGroupPaymentCalenderDetail.getExpectAmount().compareTo(totalPrice) == 0) {
			musicGroupPaymentCalenderDetail.setPaymentStatus(MusicGroupStudentFee.PaymentStatus.PAID_COMPLETED);
		} else {
			musicGroupPaymentCalenderDetail.setPaymentStatus(MusicGroupStudentFee.PaymentStatus.NON_PAYMENT);
		}
		musicGroupPaymentCalenderDetail.setUpdateTime(date);
		musicGroupPaymentCalenderDetail.setUserId(userId);
		musicGroupPaymentCalenderDetail.setStartPaymentDate(calender.getStartPaymentDate());
		musicGroupPaymentCalenderDetail.setDeadlinePaymentDate(calender.getDeadlinePaymentDate());
		musicGroupPaymentCalenderDetail.setResponsibleUserId(calender.getOperator());
		musicGroupPaymentCalenderDetailDao.insert(musicGroupPaymentCalenderDetail);
		
		List<MusicGroupPaymentStudentCourseDetail> musicGroupPaymentStudentCourseDetailList = new ArrayList<MusicGroupPaymentStudentCourseDetail>();
		MusicGroupPaymentStudentCourseDetail musicGroupPaymentStudentCourseDetail = null;
		for (MusicGroupPaymentCalenderCourseSettings courseSettings : courseSettingsList) {
			if (courseSettings.getIsStudentOptional() == true || courseSettings.getCourseTotalMinuties() == null || courseSettings.getCourseTotalMinuties() == 0) {
				continue;
			}
			musicGroupPaymentStudentCourseDetail = new MusicGroupPaymentStudentCourseDetail();
			musicGroupPaymentStudentCourseDetail.setCourseType(courseSettings.getCourseType());
			musicGroupPaymentStudentCourseDetail.setCreateTime(date);
			musicGroupPaymentStudentCourseDetail.setMusicGroupPaymentCalenderId(musicGroupPaymentCalenderId);
			musicGroupPaymentStudentCourseDetail.setMusicGroupPaymentCalenderDetailId(musicGroupPaymentCalenderDetail.getId());
			musicGroupPaymentStudentCourseDetail.setTotalCourseMinutes(courseSettings.getCourseTotalMinuties());
			musicGroupPaymentStudentCourseDetail.setUpdateTime(date);
			musicGroupPaymentStudentCourseDetail.setUsedCourseMinutes(0);
			musicGroupPaymentStudentCourseDetail.setUserId(userId);

			musicGroupPaymentStudentCourseDetailList.add(musicGroupPaymentStudentCourseDetail);
		}

		if (musicGroupPaymentStudentCourseDetailList.size() > 0) {
			musicGroupPaymentStudentCourseDetailDao.batchInsert(musicGroupPaymentStudentCourseDetailList);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void batchAdd(Long musicGroupPaymentCalenderId, Set<Integer> userIdList) {
		
		MusicGroupPaymentCalender musicGroupPaymentCalender = musicGroupPaymentCalenderService.get(musicGroupPaymentCalenderId);
		if(musicGroupPaymentCalender == null){
			throw new BizException("查询缴费信息失败");
		}
		if(musicGroupPaymentCalender.getPaymentType() == MusicGroupPaymentCalender.PaymentType.MUSIC_APPLY){
			throw new BizException("操作失败：报名缴费项不允许添加学员");
		}
		if (musicGroupPaymentCalender.getStatus() == PaymentCalenderStatusEnum.AUDITING
				|| musicGroupPaymentCalender.getStatus() == PaymentCalenderStatusEnum.REJECT) {
			throw new BizException("当前缴费状态不能添加学生");
		}
		
		//判断学生是否已存在
		Set<Integer> userList = musicGroupPaymentCalenderDetailDao.queryStudentIds(musicGroupPaymentCalenderId);

		if(Collections.disjoint(userList, userIdList) == false){
			throw new BizException("操作失败：包含已存在的学员");
		}
		
		List<MusicGroupPaymentCalenderCourseSettings> courseSettingsList = musicGroupPaymentCalenderCourseSettingsDao.getWithPaymentCalender(musicGroupPaymentCalenderId);
		
		BigDecimal totalPrice = new BigDecimal(0);
		if (musicGroupPaymentCalender.getPayUserType() == STUDENT) {
			for (MusicGroupPaymentCalenderCourseSettings courseSettings : courseSettingsList) {
				// 剔除可选课程
				if (courseSettings.getIsStudentOptional() == false) {
					totalPrice = totalPrice.add(courseSettings.getCourseCurrentPrice());
				}
			}
		}
		
		Date date = new Date();
		MusicGroupPaymentCalenderDetail musicGroupPaymentCalenderDetail = null;
		Map<Integer,MusicGroupPaymentCalenderDetail> userMap = new HashMap<Integer, MusicGroupPaymentCalenderDetail>();
		List<MusicGroupPaymentCalenderDetail> musicGroupPaymentCalenderDetailList = new ArrayList<MusicGroupPaymentCalenderDetail>();
		//创建缴费明细
		for(Integer studentId : userIdList){
			musicGroupPaymentCalenderDetail = new MusicGroupPaymentCalenderDetail();
			musicGroupPaymentCalenderDetail.setMusicGroupPaymentCalenderId(musicGroupPaymentCalenderId);
			musicGroupPaymentCalenderDetail.setCreateTime(date);
			musicGroupPaymentCalenderDetail.setExpectAmount(totalPrice);
			if (musicGroupPaymentCalenderDetail.getExpectAmount().compareTo(totalPrice) == 0) {
				musicGroupPaymentCalenderDetail.setPaymentStatus(PaymentStatus.PAID_COMPLETED);
			} else {
				musicGroupPaymentCalenderDetail.setPaymentStatus(PaymentStatus.NON_PAYMENT);
			}
			musicGroupPaymentCalenderDetail.setUpdateTime(date);
			musicGroupPaymentCalenderDetail.setUserId(studentId);
			musicGroupPaymentCalenderDetail.setStartPaymentDate(musicGroupPaymentCalender.getStartPaymentDate());
			musicGroupPaymentCalenderDetail.setDeadlinePaymentDate(musicGroupPaymentCalender.getDeadlinePaymentDate());
			musicGroupPaymentCalenderDetail.setResponsibleUserId(musicGroupPaymentCalender.getOperator());

			musicGroupPaymentCalenderDetailList.add(musicGroupPaymentCalenderDetail);
		}

		if (musicGroupPaymentCalenderDetailList.size() > 0) {
			musicGroupPaymentCalenderDetailDao.batchInsert(musicGroupPaymentCalenderDetailList);
			for(MusicGroupPaymentCalenderDetail cd : musicGroupPaymentCalenderDetailList){
				userMap.put(cd.getUserId(), cd);
			}
		}
		//更新预计缴费人数
		musicGroupPaymentCalender.setExpectNum(musicGroupPaymentCalender.getExpectNum() + userIdList.size());
		musicGroupPaymentCalender.setUpdateTime(date);
		musicGroupPaymentCalenderService.update(musicGroupPaymentCalender);
		
		List<MusicGroupPaymentStudentCourseDetail> musicGroupPaymentStudentCourseDetailList = new ArrayList<MusicGroupPaymentStudentCourseDetail>();
		MusicGroupPaymentStudentCourseDetail musicGroupPaymentStudentCourseDetail = null;
		//创建学生课排课分钟数
		for(Integer studentId : userIdList){
			for(MusicGroupPaymentCalenderCourseSettings courseSettings : courseSettingsList){
				if (courseSettings.getIsStudentOptional() == true || courseSettings.getCourseTotalMinuties() == null || courseSettings.getCourseTotalMinuties() == 0) {
					continue;
				}
				musicGroupPaymentStudentCourseDetail = new MusicGroupPaymentStudentCourseDetail();
				musicGroupPaymentStudentCourseDetail.setCourseType(courseSettings.getCourseType());
				musicGroupPaymentStudentCourseDetail.setCreateTime(date);
				musicGroupPaymentStudentCourseDetail.setMusicGroupPaymentCalenderId(musicGroupPaymentCalenderId);
				musicGroupPaymentStudentCourseDetail.setMusicGroupPaymentCalenderDetailId(userMap.get(studentId).getId());
				musicGroupPaymentStudentCourseDetail.setTotalCourseMinutes(courseSettings.getCourseTotalMinuties());
				musicGroupPaymentStudentCourseDetail.setUpdateTime(date);
				musicGroupPaymentStudentCourseDetail.setUsedCourseMinutes(0);
				musicGroupPaymentStudentCourseDetail.setUserId(studentId);
				
				musicGroupPaymentStudentCourseDetailList.add(musicGroupPaymentStudentCourseDetail);
			}
		}
		
		if(musicGroupPaymentStudentCourseDetailList.size() > 0){
			musicGroupPaymentStudentCourseDetailDao.batchInsert(musicGroupPaymentStudentCourseDetailList);
		}
		//给学员推送缴费通知
		if(musicGroupPaymentCalender.getPayUserType() == STUDENT && musicGroupPaymentCalender.getStatus() == PaymentCalenderStatusEnum.OPEN){
			musicGroupPaymentCalenderService.pushWaitRenewMessage(musicGroupPaymentCalenderId,musicGroupDao.get(musicGroupPaymentCalender.getMusicGroupId()),userIdList);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void batchAdd(MusicGroupPaymentCalender musicGroupPaymentCalender,List<MusicGroupPaymentCalenderStudentDetail> musicGroupPaymentCalenderStudentDetails) {
		Map<Integer, List<MusicGroupPaymentCalenderStudentDetail>> collect = musicGroupPaymentCalenderStudentDetails.stream().collect(Collectors.groupingBy(e -> e.getUserId()));
		MusicGroupPaymentCalenderDetail musicGroupPaymentCalenderDetail = null;
		Long musicGroupPaymentCalenderId = musicGroupPaymentCalender.getId();
		for (Integer studentId : collect.keySet()) {
			musicGroupPaymentCalenderDetail = new MusicGroupPaymentCalenderDetail();
			musicGroupPaymentCalenderDetail.setMusicGroupPaymentCalenderId(musicGroupPaymentCalenderId);
			musicGroupPaymentCalenderDetail.setPaymentStatus(PaymentStatus.NON_PAYMENT);
			List<MusicGroupPaymentCalenderStudentDetail> calenderStudentDetails = collect.get(studentId);
			BigDecimal totalPrice = calenderStudentDetails.stream().map(e->e.getCourseCurrentPrice()).reduce(BigDecimal.ZERO, BigDecimal::add);
			musicGroupPaymentCalenderDetail.setExpectAmount(totalPrice);
			if(musicGroupPaymentCalender.getStatus() != AUDITING){
				if (totalPrice.doubleValue() == 0d) {
					musicGroupPaymentCalenderDetail.setPaymentStatus(PaymentStatus.PAID_COMPLETED);
					musicGroupPaymentCalenderDetail.setActualAmount(totalPrice);
				}
			}
			musicGroupPaymentCalenderDetail.setMusicGroupId(musicGroupPaymentCalender.getMusicGroupId());
			musicGroupPaymentCalenderDetail.setUserId(studentId);
			musicGroupPaymentCalenderDetail.setStartPaymentDate(musicGroupPaymentCalender.getStartPaymentDate());
			musicGroupPaymentCalenderDetail.setDeadlinePaymentDate(musicGroupPaymentCalender.getDeadlinePaymentDate());
			musicGroupPaymentCalenderDetail.setResponsibleUserId(musicGroupPaymentCalender.getOperator());
			musicGroupPaymentCalenderDetailDao.insert(musicGroupPaymentCalenderDetail);
		}
		musicGroupPaymentCalender.setExpectNum(collect.keySet().size());
		musicGroupPaymentCalenderService.update(musicGroupPaymentCalender);
		//给学员推送缴费通知
		if(musicGroupPaymentCalender.getStatus() == PaymentCalenderStatusEnum.OPEN){
			musicGroupPaymentCalenderService.pushWaitRenewMessage(musicGroupPaymentCalenderId,musicGroupDao.get(musicGroupPaymentCalender.getMusicGroupId()),collect.keySet());
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void batchAdd(String batchNo, Set<Integer> userIdList) {
		
		List<MusicGroupPaymentCalender> musicGroupPaymentCalenderList = musicGroupPaymentCalenderDao.findByBatchNo(batchNo);
		
		List<MusicGroupPaymentStudentCourseDetail> musicGroupPaymentStudentCourseDetailList = new ArrayList<MusicGroupPaymentStudentCourseDetail>();
		
		Long musicGroupPaymentCalenderId = null;
		
		for(MusicGroupPaymentCalender musicGroupPaymentCalender : musicGroupPaymentCalenderList){
			
			musicGroupPaymentCalenderId = musicGroupPaymentCalender.getId();
			
			if(musicGroupPaymentCalender.getPaymentType() == MusicGroupPaymentCalender.PaymentType.MUSIC_APPLY){
				throw new BizException("操作失败：报名缴费项不允许添加学员");
			}
			if (musicGroupPaymentCalender.getStatus() == PaymentCalenderStatusEnum.AUDITING
					|| musicGroupPaymentCalender.getStatus() == PaymentCalenderStatusEnum.REJECT) {
				throw new BizException("当前缴费状态不能添加学生");
			}
			
			//判断学生是否已存在
			Set<Integer> userList = musicGroupPaymentCalenderDetailDao.queryStudentIds(musicGroupPaymentCalenderId);

			if(Collections.disjoint(userList, userIdList) == false){
				throw new BizException("操作失败：包含已存在的学员");
			}
			
			List<MusicGroupPaymentCalenderCourseSettings> courseSettingsList = musicGroupPaymentCalenderCourseSettingsDao.getWithPaymentCalender(musicGroupPaymentCalenderId);
			
			BigDecimal totalPrice = new BigDecimal(0);
			
			if (musicGroupPaymentCalender.getPayUserType() == STUDENT) {
				for (MusicGroupPaymentCalenderCourseSettings courseSettings : courseSettingsList) {
					// 剔除可选课程
					if (courseSettings.getIsStudentOptional() == false) {
						totalPrice = totalPrice.add(courseSettings.getCourseCurrentPrice());
					}
				}
			}
			
			Date date = new Date();
			MusicGroupPaymentCalenderDetail musicGroupPaymentCalenderDetail = null;
			Map<Integer,MusicGroupPaymentCalenderDetail> userMap = new HashMap<Integer, MusicGroupPaymentCalenderDetail>();
			List<MusicGroupPaymentCalenderDetail> musicGroupPaymentCalenderDetailList = new ArrayList<MusicGroupPaymentCalenderDetail>();
			//创建缴费明细
			for(Integer studentId : userIdList){
				musicGroupPaymentCalenderDetail = new MusicGroupPaymentCalenderDetail();
				musicGroupPaymentCalenderDetail.setMusicGroupPaymentCalenderId(musicGroupPaymentCalenderId);
				musicGroupPaymentCalenderDetail.setCreateTime(date);
				musicGroupPaymentCalenderDetail.setExpectAmount(totalPrice);
				if (musicGroupPaymentCalenderDetail.getExpectAmount().compareTo(new BigDecimal(0)) == 0) {
					musicGroupPaymentCalenderDetail.setPaymentStatus(PaymentStatus.PAID_COMPLETED);
				} else {
					musicGroupPaymentCalenderDetail.setPaymentStatus(PaymentStatus.NON_PAYMENT);
				}
				musicGroupPaymentCalenderDetail.setUpdateTime(date);
				musicGroupPaymentCalenderDetail.setUserId(studentId);
				musicGroupPaymentCalenderDetail.setStartPaymentDate(musicGroupPaymentCalender.getStartPaymentDate());
				musicGroupPaymentCalenderDetail.setDeadlinePaymentDate(musicGroupPaymentCalender.getDeadlinePaymentDate());
				musicGroupPaymentCalenderDetail.setResponsibleUserId(musicGroupPaymentCalender.getOperator());
				
				musicGroupPaymentCalenderDetailList.add(musicGroupPaymentCalenderDetail);
			}

			if (musicGroupPaymentCalenderDetailList.size() > 0) {
				musicGroupPaymentCalenderDetailDao.batchInsert(musicGroupPaymentCalenderDetailList);
				for(MusicGroupPaymentCalenderDetail cd : musicGroupPaymentCalenderDetailList){
					userMap.put(cd.getUserId(), cd);
				}
			}
			//更新预计缴费人数
			musicGroupPaymentCalender.setExpectNum(musicGroupPaymentCalender.getExpectNum() + userIdList.size());
			musicGroupPaymentCalender.setUpdateTime(date);
			musicGroupPaymentCalenderService.update(musicGroupPaymentCalender);
			
			MusicGroupPaymentStudentCourseDetail musicGroupPaymentStudentCourseDetail = null;
			//创建学生课排课分钟数
			for(Integer studentId : userIdList){
				for(MusicGroupPaymentCalenderCourseSettings courseSettings : courseSettingsList){
					if (courseSettings.getIsStudentOptional() == true || courseSettings.getCourseTotalMinuties() == null || courseSettings.getCourseTotalMinuties() == 0) {
						continue;
					}
					musicGroupPaymentStudentCourseDetail = new MusicGroupPaymentStudentCourseDetail();
					musicGroupPaymentStudentCourseDetail.setCourseType(courseSettings.getCourseType());
					musicGroupPaymentStudentCourseDetail.setCreateTime(date);
					musicGroupPaymentStudentCourseDetail.setMusicGroupPaymentCalenderId(musicGroupPaymentCalenderId);
					musicGroupPaymentStudentCourseDetail.setMusicGroupPaymentCalenderDetailId(userMap.get(studentId).getId());
					musicGroupPaymentStudentCourseDetail.setTotalCourseMinutes(courseSettings.getCourseTotalMinuties());
					musicGroupPaymentStudentCourseDetail.setUpdateTime(date);
					musicGroupPaymentStudentCourseDetail.setUsedCourseMinutes(0);
					musicGroupPaymentStudentCourseDetail.setUserId(studentId);
					
					musicGroupPaymentStudentCourseDetailList.add(musicGroupPaymentStudentCourseDetail);
				}
			}
		}
		
		if(musicGroupPaymentStudentCourseDetailList.size() > 0){
			musicGroupPaymentStudentCourseDetailDao.batchInsert(musicGroupPaymentStudentCourseDetailList);
		}
		//给学员推送缴费通知
		for (MusicGroupPaymentCalender musicGroupPaymentCalender : musicGroupPaymentCalenderList) {
			if (musicGroupPaymentCalender.getPayUserType() == STUDENT && musicGroupPaymentCalender.getStatus() == PaymentCalenderStatusEnum.OPEN) {
				musicGroupPaymentCalenderService.pushWaitRenewMessage(musicGroupPaymentCalender.getId(),
						musicGroupDao.get(musicGroupPaymentCalender.getMusicGroupId()),userIdList);
			}
		}
	}

	@Override
	public List<FeeStudentDto> queryFeeStudents(String musicGroupId,String search,Integer subjectId) {
		return musicGroupStudentFeeDao.queryFeeStudents(musicGroupId,search,subjectId);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void batchDel(String musicGroupPaymentCalenderDetailIds) {
		List<MusicGroupPaymentCalenderDetail> details = musicGroupPaymentCalenderDetailDao.queryListByIds(musicGroupPaymentCalenderDetailIds);
		if(details == null || details.size() == 0){
			throw new BizException("删除失败: 数据不可为空");
		}
		Long musicGroupPaymentCalenderId = details.get(0).getMusicGroupPaymentCalenderId();
		MusicGroupPaymentCalender musicGroupPaymentCalender = musicGroupPaymentCalenderDao.get(musicGroupPaymentCalenderId);
		
		if(musicGroupPaymentCalender == null){
			throw new BizException("查询缴费项目失败[{}]", musicGroupPaymentCalender);
		}
		
		long count = 0;
		if (musicGroupPaymentCalender.getPayUserType() == STUDENT) {
			// 是否已缴费
			count = details.stream().filter(e -> e.getPaymentStatus() != NON_PAYMENT).count();
			if (count > 0) {
				throw new BizException("删除失败: 存在已缴费的学员");
			}
		}
		List<Long> musicGroupPaymentCalenderDetailIdList = new ArrayList<Long>();
		for(String s : musicGroupPaymentCalenderDetailIds.split(",")){
			musicGroupPaymentCalenderDetailIdList.add(Long.parseLong(s));
		}
		//是否已排课
		List<MusicGroupPaymentStudentCourseDetail> musicGroupPaymentStudentCourseDetailList = musicGroupPaymentStudentCourseDetailDao.queryByMusicGroupPaymentStudentCourseDetailId(musicGroupPaymentCalenderDetailIdList);
		count = musicGroupPaymentStudentCourseDetailList.stream().filter(e -> e.getUsedCourseMinutes() > 0).count();
		if(count > 0){
			throw new BizException("删除失败：存在已排课的学员");
		}
		
		int currentNum = musicGroupPaymentCalender.getExpectNum() - details.size();
		musicGroupPaymentCalender.setExpectNum(currentNum < 0 ? 0 : currentNum);
		musicGroupPaymentCalender.setUpdateTime(new Date());
		musicGroupPaymentCalenderDao.update(musicGroupPaymentCalender);
		
		musicGroupPaymentCalenderDetailDao.batchDel(musicGroupPaymentCalenderDetailIds);
		musicGroupPaymentStudentCourseDetailDao.deleteByMusicGroupPaymentCalenderDetailId(musicGroupPaymentCalenderDetailIdList);
	}
}