package com.ssj.service.sys.lesson.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.ssj.bean.kmt.kmt.domain.KmtCourse;
import com.ssj.bean.kmt.kmt.domain.KmtCourseTemplate;
import com.ssj.bean.sys.lesson.domain.LessonGroup;
import com.ssj.bean.sys.lesson.domain.LessonService;
import com.ssj.bean.sys.lesson.domain.LessonServiceApply;
import com.ssj.bean.weixin.libmy.domain.LibVip;
import com.ssj.bean.weixin.libmy.domain.TbLibManager;
import com.ssj.bean.weixin.order.domain.Order;
import com.ssj.bean.weixin.order.domain.OrderRefund;
import com.ssj.bean.weixin.push.domain.SendTemplateShort;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.conch.push.util.PushConstants;
import com.ssj.dao.sys.lesson.dao.LessonServiceDao;
import com.ssj.dao.sys.lesson.dao.LessonServiceQueryDao;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.basic.utils.StringUtils;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.util.StringUtil;
import com.ssj.framework.weixin.util.DateUtil;
import com.ssj.service.conch.schoolmaster.dto.*;
import com.ssj.service.conch.schoolmaster.util.Constant;
import com.ssj.service.conch.teacher.service.ITzybService;
import com.ssj.service.kmt.service.KmtCourseService;
import com.ssj.service.kmt.service.KmtCourseTemplateService;
import com.ssj.service.sys.lesson.service.LessonGroupService;
import com.ssj.service.sys.lesson.service.LessonServiceApplyService;
import com.ssj.service.sys.lesson.service.LessonServiceService;
import com.ssj.service.sys.push.service.SconXingeService;
import com.ssj.service.weixin.library.service.IBookManagerService;
import com.ssj.service.weixin.library.service.ILibVipService;
import com.ssj.service.weixin.order.service.OrderRefundService;
import com.ssj.service.weixin.order.service.OrderService;
import com.ssj.service.weixin.push.service.PushTemplateService;
import com.ssj.service.weixin.sales.service.LibVipServiceService;
import com.ssj.service.weixin.user.service.UserService;
import com.ssj.service.weixin.zuoyb.service.ZuoybDayService;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Transactional
@Service(version = "1.0")
public class LessonServiceServiceImpl extends BaseServiceImpl<LessonService, String> implements LessonServiceService {
	
	private   Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private LessonServiceDao lessonServiceDao;
    
    @Autowired
    private LessonServiceQueryDao lessonServiceQueryDao;
    
    @Autowired
    private LibVipServiceService libVipServiceService;
    
    @Autowired
    private KmtCourseService kmtCourseService;
    
    @Autowired
    private ZuoybDayService zuoybDayService;
    
    @Autowired
    private ILibVipService libVipService;
    
    @Autowired
    private IBookManagerService managerService;
    
    @Autowired
    private LessonServiceApplyService lessonServiceApplyService;
    
    @Autowired
    private OrderRefundService orderRefundService;
    
    @Autowired
    private KmtCourseTemplateService kmtCourseTemplateService;
    
    @Autowired
	private ITzybService zybService;
    
    @Autowired
    private PushTemplateService pushTemplateService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
	private SconXingeService sconXingeService;
    
    @Autowired
    private LessonGroupService lessonGroupService;

    @Override
    public PagingAndSortingRepository<LessonService, String> getDao() {
        return lessonServiceDao;
    }

    @Override
    public LessonService findPayLessonByVipId(String vipId, String masterId) {
        //返回最近的已支付的订单信息
        return lessonServiceDao.findFirstByVipIdAndMasterIdAndStatusOrderByCreateTimeDesc(vipId, masterId, 1);
    }

    public LessonService findLessonServiceByVipIdAndCourse (String vipId, String masterId, String subjectName) {
    	return lessonServiceDao.findFirstByVipIdAndMasterIdAndCourseNameOrderByCreateTimeDesc(vipId, masterId, subjectName);
	}

	@Override
	public void updateLessonStatus(String orderNo) {
		//更新一对一服务表状态为已支付
		LessonService lessonService = lessonServiceDao.findByOrderNo(orderNo);
		lessonService.setStatus(1);
		lessonServiceDao.save(lessonService);
		//更新一对一排课表状态为 2家长已支付
		List<KmtCourse> list = kmtCourseService.findByLessionServiceId(lessonService.getId());
		String teacherId = null;
		for (KmtCourse kmtCourse : list) {
			//有确认意向的那么planStatus状态不变，否则未支付状态改成已支付
			if(kmtCourse.getPlanStatus() == 1) {
				kmtCourse.setPlanStatus(2);
			}
			teacherId = kmtCourse.getTeacherId();
		}
		kmtCourseService.save(list);
		
		//插入服务记录tb_lib_vip_service
		libVipServiceService.saveLibVipService(lessonService.getLibId(), "S010", "C100", lessonService.getVipId(), DateUtil.parse_yyyyMMddHHmmss(lessonService.getStartTime()), DateUtil.parse_yyyyMMddHHmmss(lessonService.getEndTime()), lessonService.getId(), lessonService.getCourseCount());
		for (KmtCourse kmtCourse : list) {
			if(kmtCourse.getIsGroup() == 1) {
				zuoybDayService.saveToday(kmtCourse.getVipId(), 4, kmtCourse.getCourseTime());
			}else {
				zuoybDayService.saveToday(kmtCourse.getVipId(), 3, kmtCourse.getCourseTime());
			}
			
		}
		
		//支付成功推送消息
		//推送家长
		LibVip libVip = libVipService.getById(lessonService.getVipId());
		String parentName = libVip.getParentName();
        User parent = userService.getById(libVip.getUserId());
        if(StringUtils.isBlank(libVip.getParentName())) {
        	parentName = parent.getName();
        }
        String contentMessage = "亲爱的"+parentName+"家长您好，您已完成孩子课程支付！感谢您的信任，让我们与孩子砥砺前行！";
        
        //推送家长
        sconXingeService.asynPushThreadTask(libVip.getUserId(),null,2,contentMessage,PushConstants.PUSH_LESSON);
		
		//小程序提醒
		//推送家长
		Map<String,String> data =new HashMap<String, String>();
		String template_id_short="OPENTM405457626";
		data.put("first", contentMessage);
		//订单时间
		data.put("keyword1", DateUtil.format_yyyyMMddHHmmss(lessonService.getCreateTime()));
		data.put("remark", "您可点击详情查看课程具体安排。");
		if(lessonService.getIsListenTest() == 1) {
			//如果有试听课
			//总课次
			int courseCount = lessonService.getCourseCount()-1;
			//总付费
            BigDecimal sumPrice = lessonService.getPrice().multiply(new BigDecimal(courseCount));
			//课程总价
			data.put("keyword2", sumPrice.toString());
			//课时单价
			data.put("keyword3", lessonService.getPrice().toString());
			//购买课时
			data.put("keyword4", String.valueOf(courseCount));
			//课程类型
			data.put("keyword5", "试听课");
		}else {
			//如果没有试听课
			//总课次
			int courseCount = lessonService.getCourseCount();
			//总付费
            BigDecimal sumPrice = lessonService.getPrice().multiply(new BigDecimal(courseCount));
			//课程总价
			data.put("keyword2", sumPrice.toString());
			//课时单价
			data.put("keyword3", lessonService.getPrice().toString());
			//购买课时
			data.put("keyword4", String.valueOf(courseCount));
			//课程类型
			data.put("keyword5", "正式课");
		}
		SendTemplateShort sendTemplateShort=new SendTemplateShort(parent.getAccount(), template_id_short, null, data);
		pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
		
		//推送校长
		TbLibManager master = managerService.findByUserId(lessonService.getMasterId(), Constant.SCHOOL_MASTER_TYPE);
        String masterName = master.getName();
        User masterUser = userService.getById(master.getUserId());
        if(StringUtils.isBlank(master.getName())) {
        	masterName = masterUser.getName();
        }
        
        contentMessage = "亲爱的"+masterName+"校长您好！您的"+parentName+"家长已完成课程支付，请尽快安排老师上课。";
        //推送校长
        //sconXingeService.asynPushThreadTask(lessonService.getMasterId(),5,contentMessage);
		
		//小程序提醒
		//推送校长
		data.put("first", contentMessage);
		sendTemplateShort=new SendTemplateShort(masterUser.getAccount(), template_id_short, null, data);
		pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
		
		//推送老师
		if(StringUtils.isNotBlank(teacherId)) {
			TbLibManager teacher = managerService.findByUserId(teacherId, Constant.KMT_121_TEACHER_TYPE);
	        String teacherName = teacher.getName();
	        User teacherUser = userService.getById(teacherId);
	        if(StringUtils.isBlank(teacher.getName())) {
	        	teacherName = teacherUser.getName();
	        }
			
	        //推送老师
	        contentMessage = "敬爱的"+teacherName+"老师您好！"+parentName+"家长购买了您的课程，请及时确认上课意向时间。";
	        //sconXingeService.asynPushThreadTask(teacherId,4,contentMessage);
			//小程序提醒
	        /**
	         * OPENTM416282170
				标题：购买成功通知
				详细内容{{first.DATA}}：
				课程名称：{{keyword1.DATA}}
				购买时间：{{keyword2.DATA}}
				{{remark.DATA}}
				
	         */
			//推送老师
	        data.clear();
			data.put("first", contentMessage);
			data.put("keyword1", lessonService.getGrade()+lessonService.getCourseName());
			data.put("keyword2", DateUtil.dateToString(new Date()));
			data.put("remark", "");
			sendTemplateShort=new SendTemplateShort(teacherUser.getAccount(), "OPENTM416282170", null, data);
			pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
		}
	}

	@Override
	public void updateCurrentCount(KmtCourse course) {
		//查询该课程所有课次
		LessonService lessonService = lessonServiceDao.findOne(course.getLessonServiceId());
		
		//判断是一对一还是小课
		if(lessonService.getIsGroup() == 1) {
			LessonGroup lessonGroup = lessonGroupService.getById(lessonService.getLessonGroupId());
			//小课
			if(lessonGroup.getCourseCount() == lessonService.getCurrentCount()) {
				//如果是最后一节课的反馈 那么设置一对一服务为完结
				lessonService.setStatus(2);
			}else {
				//设置当前课次为下节课
				lessonService.setCurrentCount(lessonGroup.getCurrentCount()+1);
			}
		}else {
			//一对一
			if(course.getNum() == lessonService.getCourseCount()) {
				//如果是最后一节课的反馈 那么设置一对一服务为完结
				lessonService.setStatus(2);
			}else {
				//设置当前课次为下节课
				lessonService.setCurrentCount(course.getNum()+1);
			}
		}
		lessonServiceDao.save(lessonService);
	}

	@Override
	public List<VipStudyDto> findByCoursePlan(String masterId) {
		//通过校长查询学生的当前学习计划
		List<VipStudyDto> coursePlanList = new ArrayList<VipStudyDto>();
		List<Map<String,Object>> list = lessonServiceQueryDao.findByCoursePlan(masterId);
		if(CollectionUtils.isNotEmpty(list)) {
			for (Map<String, Object> map : list) {
				//一对一老师类型
				String teacherLever = (String)map.get("teacher_lever");
				String vipId = (String)map.get("vip_id");
				LibVip libVip = libVipService.getById(vipId);
				VipStudyDto vipStudyDto = new VipStudyDto();
				if(Constant.SUPER_TEACHER.equals(teacherLever)) {
					vipStudyDto.setTeacherType("1");
				}else if(Constant.REGISTER_TEACHER.equals(teacherLever)) {
					vipStudyDto.setTeacherType("2");
				}else if(Constant.STAR_TEACHER.equals(teacherLever)) {
					vipStudyDto.setTeacherType("3");
				}else if(Constant.SENIOR_TEACHER.equals(teacherLever)) {
					vipStudyDto.setTeacherType("4");
				}
				
				PlanDto planDto = new PlanDto();
				planDto.setPlanId((String)map.get("id"));
				if(map.get("status").toString().equals("0")) {
					planDto.setIsPay(0);
				}else {
					planDto.setIsPay(1);
				}
				int planStatus = (int)map.get("plan_status");
				planDto.setPlanStatus(planStatus);
				planDto.setCourseType((Integer)map.get("course_type"));
				if(planStatus  == 3) {
					planDto.setIsConfirmSchoolTime(1);
				}else if(planStatus == 4) {
					planDto.setIsConfirmSchoolTime(1);
					planDto.setIsAttendClass(1);
				}else if(planStatus == 5) {
					planDto.setIsConfirmSchoolTime(1);
					planDto.setIsAttendClass(1);
					planDto.setIsFeedback(1);
				}
				
				planDto.setSubjectName((String)map.get("course_name"));
				planDto.setGrade((String)map.get("grade"));
				planDto.setStartTime((String)map.get("start_time"));
				planDto.setEndTime((String)map.get("end_time"));
				
				TbLibManager teacher = managerService.findByUserId((String)map.get("teacher_id"), Constant.KMT_121_TEACHER_TYPE);
				if(teacher != null) {
					planDto.setTeacherName(teacher.getName());
					planDto.setTeacherId(teacher.getUserId());
				}
				
				String attendClassTime = map.get("course_time").toString() +" "+map.get("course_start").toString()+"-"+map.get("course_end").toString();
				planDto.setAttendClassTime(attendClassTime);
				//判断是否有调课申请
				if("1".equals(map.get("is_apply") + "")) {
					//如果有调课/确认换老师申请
					LessonServiceApply apply = lessonServiceApplyService.findFirstByKmtCourseIdAndType((String)map.get("id"), 1);
					if(apply != null) {
						if(apply.getStatus() == 0) {
							vipStudyDto.setApplyType(1);
							planDto.setIsRequestChangeClassTime(1);
							vipStudyDto.setApplyStatus(1);
							vipStudyDto.setApplyReason(apply.getReason());
						}
						//原上课时间
						String oldTime = DateUtil.format_yyyyMMdd(apply.getOldClassTime());
						String start = DateUtil.format_HHmm(apply.getOldClassTime());
						String end = DateUtil.format_HHmm(DateHelper.getAddHour(apply.getOldClassTime(), 2, 0));
						planDto.setAttendClassTime(oldTime+" "+start+"-"+end);
						
						//现申请新调课时间
						String adjustTime = DateUtil.format_yyyyMMdd(apply.getAdjustTime());
						start = DateUtil.format_HHmm(apply.getAdjustTime());
						end = DateUtil.format_HHmm(DateHelper.getAddHour(apply.getAdjustTime(), 2, 0));
						planDto.setRequestAttendClassTime(adjustTime+" "+start+"-"+end);
					}
					apply = lessonServiceApplyService.findByKmtCourseIdAndType((String)map.get("lesson_service_id"), 2);
					boolean flag = true;
					if(apply != null) {
						if(StringUtils.isBlank(apply.getTeacherId())) {
							vipStudyDto.setApplyType(2);
							planDto.setIsRequestChangeTeacher(1);
							vipStudyDto.setApplyStatus(1);
							vipStudyDto.setApplyReason(apply.getReason());
						}else {
							flag = false;
						}
					}
					
					//新增调整理由
					apply = lessonServiceApplyService.findHistoryApplyByKmtCourseIdOrLessonServiceIdOrderByCreateTimeDesc((String)map.get("id"), (String)map.get("lesson_service_id"));
					if(vipStudyDto.getApplyStatus() != 1 && apply != null) {
						String refuseReason = (String)map.get("refuse_reason");
						if(StringUtils.isBlank(refuseReason)) {
							if(StringUtils.isNotBlank(apply.getReason()) && flag) {
								//同意调整
								vipStudyDto.setApplyType(apply.getType());
								vipStudyDto.setApplyStatus(2);
							}
						}else {
							//拒绝调整
							vipStudyDto.setApplyType(apply.getType());
							vipStudyDto.setApplyStatus(3);
							//获取最新的申请理由
							vipStudyDto.setApplyReason(apply.getReason());
							vipStudyDto.setReason(refuseReason);
						}
					}
					
				}
				vipStudyDto.setStudentId(vipId);
				vipStudyDto.setStudentName(libVip.getChildName());
				vipStudyDto.setBizType(1);
				vipStudyDto.setIsHasListenTest((Integer)map.get("is_listen_test"));
				if((Integer)map.get("is_listen_test") == 1) {
					//如果有试听课  0/12
					planDto.setStudyPlanCount((Integer)map.get("course_count")-1);
					planDto.setStudyCount((Integer)map.get("current_count")-1);
				}else {
					//如果没有试听课 1/12
					planDto.setStudyPlanCount((Integer)map.get("course_count"));
					planDto.setStudyCount((Integer)map.get("current_count"));
				}
				vipStudyDto.setPlan(planDto);
				coursePlanList.add(vipStudyDto);
			}
		}
		return coursePlanList;
	}
	
	@Override
	public List<VipStudyDto> findByCourseFeedback(String masterId) {
		//通过校长查询学生的最近的一次学习反馈
		List<VipStudyDto> coursefeedbackList = new ArrayList<VipStudyDto>();
		List<Map<String,Object>> list = lessonServiceQueryDao.findByCourseFeedback(masterId);
		if(CollectionUtils.isNotEmpty(list)) {
			for (Map<String, Object> map : list) {
				String vipId = (String)map.get("vip_id");
				String teacherId = (String)map.get("teacher_id");
				LibVip libVip = libVipService.getById(vipId);
				TbLibManager teacher = managerService.findByUserId(teacherId, Constant.KMT_121_TEACHER_TYPE);
				
				VipStudyDto vipStudyDto = new VipStudyDto();
				//一对一老师类型
				String teacherLever = (String)map.get("teacher_lever");
				if(Constant.SUPER_TEACHER.equals(teacherLever)) {
					vipStudyDto.setTeacherType("1");
				}else if(Constant.REGISTER_TEACHER.equals(teacherLever)) {
					vipStudyDto.setTeacherType("2");
				}else if(Constant.STAR_TEACHER.equals(teacherLever)) {
					vipStudyDto.setTeacherType("3");
				}else if(Constant.SENIOR_TEACHER.equals(teacherLever)) {
					vipStudyDto.setTeacherType("4");
				}
				
				PlanDto planDto = new PlanDto();
				planDto.setPlanId((String)map.get("id"));
				if(map.get("status").toString().equals("0")) {
					planDto.setIsPay(0);
				}else {
					planDto.setIsPay(1);
				}
				int planStatus = (int)map.get("plan_status");
				planDto.setPlanStatus(planStatus);
				planDto.setCourseType((Integer)map.get("course_type"));
				if(planStatus == 5) {
					planDto.setIsConfirmSchoolTime(1);
					planDto.setIsAttendClass(1);
					planDto.setIsFeedback(1);
				}
				planDto.setTeacherName(teacher.getName());
				planDto.setTeacherId(teacherId);
				planDto.setSubjectName((String)map.get("course_name"));
				planDto.setGrade((String)map.get("grade"));
				planDto.setStartTime((String)map.get("start_time"));
				planDto.setEndTime((String)map.get("end_time"));
				planDto.setAttendClassTime(map.get("course_time") + "");
				
				vipStudyDto.setStudentId(vipId);
				vipStudyDto.setStudentName(libVip.getChildName());
				vipStudyDto.setBizType(1);
				vipStudyDto.setIsHasListenTest((Integer)map.get("is_listen_test"));
				if((Integer)map.get("is_listen_test") == 1) {
					//如果有试听课  0/12
					planDto.setStudyPlanCount((Integer)map.get("course_count")-1);
					planDto.setStudyCount((Integer)map.get("num")-1);
				}else {
					//如果没有试听课 1/12
					planDto.setStudyPlanCount((Integer)map.get("course_count"));
					planDto.setStudyCount((Integer)map.get("num"));
				}
				
				//反馈信息
				SupervisionDto supervision = null;
				Map<String, Object> studyMap = zybService.findTodayOneFinishTask(map.get("vip_id").toString(),map.get("lesson_service_id").toString());
              	if(studyMap.get("child_name") !=null){
              		//掌握程度
	           		if(studyMap.get("class_line") != null) {
	           			int masterLevel = Integer.valueOf(studyMap.get("class_line").toString());
	           			planDto.setGraspLevel(masterLevel);
	           		}
	           		//知识模块
	           		planDto.setKnowledgeModule("知识精讲板块");
	           		//错题数量
	           		if(studyMap.get("ztnum") != null) {
	           			int errorsCount = Integer.valueOf(studyMap.get("ztnum").toString());
	           			planDto.setErrorsCount(errorsCount);
	           		}
	           		//家长评价集合
	           		if(studyMap.get("judge_lable") != null) {
	           			String[] commentArray = studyMap.get("judge_lable").toString().split(",");
	           			List<String> commentList = new ArrayList<String>();
	           			Collections.addAll(commentList, commentArray);
	           			planDto.setCommentList(commentList);
	           		}
	           	    //家长满意度
	           		if(studyMap.get("parent_judge_lever") != null) {
	           			int parentJudgeLever = Integer.valueOf(studyMap.get("parent_judge_lever").toString());
	           			planDto.setPatriarchSatisfaction(parentJudgeLever);
	           			
	           		    //意见督促业务模型 三颗星及其以下星级评分须发送通知于校长端
	           			if(parentJudgeLever <= 3) {
	           				supervision = new SupervisionDto();
	           				supervision.setPlanId(planDto.getPlanId());
	           				supervision.setCommentList(planDto.getCommentList());
	           				supervision.setPhone(libVip.getPhone());
	           				supervision.setPatriarchSatisfaction(parentJudgeLever);
	           				supervision.setTeacherName(planDto.getTeacherName());
	           			}
	           		}
	           		
	           		//家长电话
	           		planDto.setPhone(libVip.getPhone());
              	}
				vipStudyDto.setPlan(planDto);
				coursefeedbackList.add(vipStudyDto);
				
				//意见督促业务模型 三颗星及其以下星级评分须发送通知于校长端
				if(supervision != null) {
					VipStudyDto vipStudyDto2 = new VipStudyDto();
					vipStudyDto2.setSupervision(supervision);
					coursefeedbackList.add(vipStudyDto2);
				}
			}
		}
		return coursefeedbackList;
	}

	@Override
	public LessonService findServiceByOrderNo(String orderNo) {
		
		return lessonServiceDao.findServiceByOrderNo(orderNo);
	}

	@Override
	public LessonService findByOrderIdAndStatusIn(String orderId, int[] status) {
    	return lessonServiceDao.findByOrderIdAndStatusIn(orderId, status);
	}

	@Override
	public int countVipIdByMasterId (String masterId){
    	return lessonServiceDao.countDistinctByMasterId(masterId);
	}

	@Override
	public List<VipStudyDto> findByCourseRefund(String masterId) {
		//查询退费申请
		List<VipStudyDto> courseRefundList = new ArrayList<VipStudyDto>();
		List<Map<String,Object>> list = lessonServiceQueryDao.findByCourseRefund(masterId);
		if(CollectionUtils.isNotEmpty(list)) {
			for (Map<String, Object> map : list) {
				String vipId = (String)map.get("vip_id");
				LibVip libVip = libVipService.getById(vipId);
				VipStudyDto vipStudyDto = new VipStudyDto();
				//一对一老师类型
				String teacherLever = (String)map.get("teacher_lever");
				if(Constant.SUPER_TEACHER.equals(teacherLever)) {
					vipStudyDto.setTeacherType("1");
				}else if(Constant.REGISTER_TEACHER.equals(teacherLever)) {
					vipStudyDto.setTeacherType("2");
				}else if(Constant.STAR_TEACHER.equals(teacherLever)) {
					vipStudyDto.setTeacherType("3");
				}else if(Constant.SENIOR_TEACHER.equals(teacherLever)) {
					vipStudyDto.setTeacherType("4");
				}
				
				//退费信息
				RefundDto refund = new RefundDto();
				Integer stat = (Integer)map.get("stat");
				refund.setIsSendRefund(1);
				if(stat == 1) {
					refund.setIsReview(1);
				}else if(stat == 2) {
					refund.setIsReview(2);
				}
				OrderRefund orderRefund = orderRefundService.findByOrderNo((String)map.get("order_no"));
				if(orderRefund != null) {
					refund.setIsRefundFinish(1);
					//退款时间
					refund.setRefundTime(DateUtil.format_yyyyMMddHHmmss(orderRefund.getCreateTime()));
				}
				refund.setOrderId((String)map.get("order_id"));
				refund.setSubjectName((String)map.get("course_name"));
				refund.setGrade((String)map.get("grade"));
				refund.setConsumeDetails((String)map.get("refunds_info"));
				refund.setMoney(map.get("price").toString());
				refund.setReason((String)map.get("refunds_reason"));
				if(map.get("initiate_time") != null) {
					Date initiateTime = (Date)map.get("initiate_time");
					refund.setSendRefundTime(DateUtil.format_HHmm(initiateTime));
				}
				if(map.get("review_time") != null) {
					Date reviewTime = (Date)map.get("review_time");
					refund.setReviewTime(DateUtil.format_HHmm(reviewTime));
				}
				vipStudyDto.setStudentId(vipId);
				vipStudyDto.setStudentName(libVip.getChildName());
				vipStudyDto.setBizType(3);
				vipStudyDto.setIsHasListenTest((Integer)map.get("is_listen_test"));
				vipStudyDto.setRefund(refund);
				courseRefundList.add(vipStudyDto);
			}
		}
		return courseRefundList;
	}

	@Override
	public LessonService findByOrderId(String orderId) {
		return lessonServiceDao.findByOrderId(orderId);
	}

	@Override
	public LessonService findByIdAndMasterIdAndVipIdAndCourseName(String id,String masterId,String vipId,String courseName) {
		return lessonServiceDao.findByIdAndMasterIdAndVipIdAndCourseName(id,masterId,vipId,courseName);
	}

	@Override
	public void deleteByInvalidLessonService() {
		lessonServiceDao.deleteByInvalidLessonService();
	}

	@Override
	public void deleteByLessonGroup() {
		lessonServiceDao.deleteByLessonGroup();
	}

	@Override
	public boolean validateCoursePlan(String teacherId, String planTime) {
		//第一层校验 通过授课老师teacherId和星期  查询老师的开课周期
        Date courseDate = DateUtil.parse_yyyyMMddHHmmss(planTime);
        String week = String.valueOf(DateHelper.getWeekDay(courseDate));
        KmtCourseTemplate template = kmtCourseTemplateService.findTemplateByAnyThing(teacherId, 1, week);
        if(template == null) {
        	//如果排课时间不在老师的开课周期范围
        	return false;
        }
        String beginTime = DateUtil.format_HHmm(courseDate);
		//第二层校验 通过授课老师teacherId和时段 查询老师的开课时段
        template = kmtCourseTemplateService.findTemplateByTeacherId(teacherId, beginTime);
        if(template == null) {
        	//如果排课时间不在老师的开课时段范围
        	return false;
        }
        //排课日期
        String courseTime = DateUtil.format_yyyyMMdd(courseDate);
        //排课开始时间
        String startTime = DateUtil.format_HHmm(courseDate);
        //时段  结束时间(开始时间+2h)
        Date courseEndTime = DateHelper.getAddHour(courseDate, 2, 0);
        String endTime = DateUtil.format_HHmm(courseEndTime);
		//第三层校验 校验老师排课表是否有空闲  查询 kmt_course表无记录则表示老师无空档，有记录则表示老师有空档
        //第三层校验 第二种方法查出记录，然后判断(传入的时间+2.5h <= 排课开始时间 或者 排课结束时间 <= 传入的时间)
        return kmtCourseService.validateTeacherCourse(teacherId, startTime, endTime, courseTime);
	}
	
	@Override
	public boolean validateCourseTeacher(String teacherId, List<String> courseTimeList) {
		boolean flag = true;
		for (String courseTime : courseTimeList) {
			//如果验证不通过
			if(!this.validateCoursePlan(teacherId, courseTime)) {
				flag = false;
				break;
			}
		}
		return flag;
	}

	@Override
	public boolean validateTeacherSupportListenTest(String teacherId, String planTime) {
		//第一层校验 通过授课老师teacherId和星期  查询老师的开课周期
        Date courseDate = DateUtil.parse_yyyyMMddHHmmss(planTime);
        String week = String.valueOf(DateHelper.getWeekDay(courseDate));
        KmtCourseTemplate template = kmtCourseTemplateService.findTemplateByAnyThing(teacherId, 1, week);
        if(template == null || template.getIsPublic() == 0) {
        	//如果排课时间不在老师的开课周期范围,或者该周期不支持试听课
        	return false;
        }
        String beginTime = DateUtil.format_HHmm(courseDate);
		//第二层校验 通过授课老师teacherId和时段 查询老师的开课时段
        template = kmtCourseTemplateService.findTemplateByTeacherId(teacherId, beginTime);
        if(template == null || template.getIsPublic() == 0) {
        	//如果排课时间不在老师的开课时段范围,或者该开课时段不支持试听课
        	return false;
        }
		return true;
	}

	@Override
	public KmtCourseTemplate findTeahcerCourseTemplate(String teacherId, String planTime) {
		//第一层校验 通过授课老师teacherId和星期  查询老师的开课周期
        Date courseDate = DateUtil.parse_yyyyMMddHHmmss(planTime);
        String week = String.valueOf(DateHelper.getWeekDay(courseDate));
        KmtCourseTemplate template = kmtCourseTemplateService.findTemplateByAnyThing(teacherId, 1, week);
        if(template == null) {
        	//如果排课时间不在老师的开课周期范围
        	return null;
        }
        String beginTime = DateUtil.format_HHmm(courseDate);
		//第二层校验 通过授课老师teacherId和时段 查询老师的开课时段
        template = kmtCourseTemplateService.findTemplateByTeacherId(teacherId, beginTime);
        return template;
	}

	@Override
	public List<LessonService> findLessonServiceByVipId(String vipId,String masterId) {
		return lessonServiceDao.findLessonServiceByVipId(vipId, masterId);
	}

	@Override
	public List<String> findByNoPayIsListen(String courseTime) {
		return lessonServiceDao.findByNoPayIsListen(courseTime);
	}

	@Override
	public void deleteKmtCourse(String lessonServiceId) {
		lessonServiceDao.deleteKmtCourse(lessonServiceId);
	}

	@Override
	public List<LessonService> findAllPayLessonService(String masterId, String vipId) {
		return lessonServiceDao.findAllPayLessonService(masterId, vipId);
	}
	
	@Override
	public List<LessonService> findAllPayLessonService(String masterId, String vipId,String courseName) {
		return lessonServiceDao.findAllPayLessonService(masterId, vipId,courseName);
	}

	@Override
	public void refundLessonService(String orderNo) {
		//获取退费的一对一学习计划
		//更改一对一学习计划状态为退款成功
		LessonService lessonService = lessonServiceDao.findByOrderNo(orderNo);
		lessonService.setStatus(4);
		lessonServiceDao.save(lessonService);
		//将学生的一对一服务置为失效
		libVipServiceService.updateVipServiceStat(lessonService.getId());
		//删除zyb_dayy 退费未上课反馈的一对一任务
		zuoybDayService.deleteByVipIdAndType(lessonService.getVipId(),lessonService.getId(), 3);
	}

	@Override
	public FeedbackModelDto findByCourseFeedback(String masterId, String vipId,String courseName) {
		
		List<Map<String, Object>> list= lessonServiceQueryDao.findByCourseFeedback(masterId,vipId,courseName);
		if(!CollectionUtils.isEmpty(list)) {
			Map<String,Object> resultMap = list.get(0);
			FeedbackModelDto dto = new FeedbackModelDto();
			dto.setPlanId((String)resultMap.get("id"));
			//学习进度
			if((Integer)resultMap.get("is_listen_test") == 1) {
				//如果有试听课  0/12
				dto.setStudyPlanCount((Integer)resultMap.get("course_count")-1);
				dto.setStudyCount((Integer)resultMap.get("num")-1);
			}else {
				//如果没有试听课 1/12
				dto.setStudyPlanCount((Integer)resultMap.get("course_count"));
				dto.setStudyCount((Integer)resultMap.get("num"));
			}
			//反馈信息
			Map<String, Object> studyMap = zybService.findTodayOneFinishTask(resultMap.get("vip_id").toString(),resultMap.get("lesson_service_id").toString());
          	if(studyMap.get("child_name") !=null){
          		//掌握程度
           		if(studyMap.get("class_line") != null) {
           			int masterLevel = Integer.valueOf(studyMap.get("class_line").toString());
           			dto.setGraspLevel(masterLevel);
           		}
           		//知识模块
           		dto.setKnowledgeModule("知识精讲板块");
           		//错题数量
           		if(studyMap.get("ztnum") != null) {
           			int errorsCount = Integer.valueOf(studyMap.get("ztnum").toString());
           			dto.setErrorsCount(errorsCount);
           		}
           		//家长评价集合
           		if(studyMap.get("judge_lable") != null) {
           			String[] commentArray = studyMap.get("judge_lable").toString().split(",");
           			List<String> commentList = new ArrayList<String>();
           			Collections.addAll(commentList, commentArray);
           			dto.setCommentList(commentList);
           		}
           	    //家长满意度
           		if(studyMap.get("parent_judge_lever") != null) {
           			int parentJudgeLever = Integer.valueOf(studyMap.get("parent_judge_lever").toString());
           			dto.setPatriarchSatisfaction(parentJudgeLever);
           		}
          	}
          	return dto;
		}
		return null;
	}

	@Override
	public NextClassInfoModelDto findByNextCoursePlan(String masterId, String vipId,String courseName) {
		List<Map<String, Object>> list= lessonServiceQueryDao.findByNextCoursePlan(masterId,vipId,courseName);
		if(!CollectionUtils.isEmpty(list)) {
			NextClassInfoModelDto dto = new NextClassInfoModelDto();
			Map<String,Object> resultMap = list.get(0);
			
			//获取下节授课信息的课程信息
			CourseInfoModelDto courseInfoModelDto = new CourseInfoModelDto();
			courseInfoModelDto.setCourseId((String)resultMap.get("id"));
			courseInfoModelDto.setGrade((String)resultMap.get("grade"));
			courseInfoModelDto.setSubjectName((String)resultMap.get("course_name"));
			courseInfoModelDto.setCourseType((Integer)resultMap.get("course_type"));
			String attendClassTime = resultMap.get("course_time").toString() +" "+resultMap.get("course_start").toString()+"-"+resultMap.get("course_end").toString();
			courseInfoModelDto.setAttendClassTime(attendClassTime);
			dto.setCourseInfoModel(courseInfoModelDto);
			//获取下节授课信息的老师信息
			if(resultMap.get("teacher_id") != null) {
				TeacherInfoModelDto teacherInfoModelDto = new TeacherInfoModelDto();
				//查询我的授课老师
	        	TbLibManager  myTeacher = managerService.findByUserId(resultMap.get("teacher_id").toString(),Constant.KMT_121_TEACHER_TYPE);
	        	teacherInfoModelDto.setTeacherId(myTeacher.getUserId());
	        	teacherInfoModelDto.setTeacherName(StringUtils.isEmpty(myTeacher.getName()) ? "" : myTeacher.getName());
	        	teacherInfoModelDto.setTeacherImg(StringUtils.isEmpty(myTeacher.gettPhoto()) ? "" : myTeacher.gettPhoto());
	        	teacherInfoModelDto.setTeacherType(2);  //授课老师
	            //教龄
	        	teacherInfoModelDto.setSchoolAge(myTeacher.getSchoolAge() == null ? 0 : myTeacher.getSchoolAge().intValue());
	            //授课次数
	        	teacherInfoModelDto.setNumClasses(myTeacher.getCourseCount() == null ? 0 : myTeacher.getCourseCount().intValue());
	            //教的学生
	        	teacherInfoModelDto.setStudentCount(myTeacher.getStudentCount() == null ? 0 : myTeacher.getStudentCount().intValue());
	        	teacherInfoModelDto.setSex(myTeacher.getSex() == null ? 0 : myTeacher.getSex());
	        	teacherInfoModelDto.setSubjectName(StringUtil.formateStr(myTeacher.getCourseName()));
	        	teacherInfoModelDto.setPhone(StringUtil.formateStr(myTeacher.getTelephone()));
	        	teacherInfoModelDto.setParentsPraise(myTeacher.getPraise());
	        	dto.setTeacherInfoModel(teacherInfoModelDto);
			}
			return dto;
		}
		return null;
	}

	@Override
	public int countByVipIdAndMasterId(String vipId, String masterId) {
		return lessonServiceDao.countByVipIdAndMasterId(vipId, masterId);
	}

	@Override
	public List<LessonServicePlanDto> findParentNoPayLessonService(String vipId) {
		//查询学生待支付一对一信息
		List<LessonServicePlanDto> dtoList = new ArrayList<LessonServicePlanDto>();
		List<Map<String, Object>> list= lessonServiceQueryDao.findParentNoPayLessonService(vipId);
		if(!CollectionUtils.isEmpty(list)) {
			LibVip libVip = libVipService.getById(vipId);
			for (Map<String, Object> map : list) {
				LessonServicePlanDto dto = new LessonServicePlanDto();
				dto.setChildName(libVip.getChildName());
				String teacherLever = (String)map.get("teacher_lever");
				if (StringUtils.isEmpty(libVip.getChildName()) || StringUtils.isEmpty(libVip.getGrade())) {
					//待完善孩子信息
					dto.setBizType(1);
					dto.setVipId(vipId);
					dto.setChildImg(libVip.getImgUrl());
					dtoList.add(dto);
					if(Constant.SUPER_TEACHER.equals(teacherLever)) {
						dto.setTeacherType("1");
					}else if(Constant.REGISTER_TEACHER.equals(teacherLever)) {
						dto.setTeacherType("2");
					}else if(Constant.STAR_TEACHER.equals(teacherLever)) {
						dto.setTeacherType("3");
					}else if(Constant.SENIOR_TEACHER.equals(teacherLever)) {
						dto.setTeacherType("4");
					}
				}else if(StringUtils.isNotBlank((String)map.get("apply_teacher_id"))) {
					//家长待确定匹配老师
					LessonServiceApply apply = lessonServiceApplyService.findByKmtCourseIdAndType((String)map.get("lesson_service_id"),2);
					TbLibManager applyTeacher = managerService.findByUserId(apply.getTeacherId(), Constant.KMT_121_TEACHER_TYPE);
					
					dto.setBizType(2);
					dto.setVipId(vipId);
					dto.setLessonServiceId((String)map.get("lesson_service_id"));
					dto.setCourseId((String)map.get("id"));
					dto.setTeacherId(apply.getTeacherId());
					dto.setTeacherName(applyTeacher.getName());
					dto.setTeacherImg(applyTeacher.gettPhoto());
					if(Constant.SUPER_TEACHER.equals(teacherLever)) {
						dto.setTeacherType("1");
					}else if(Constant.REGISTER_TEACHER.equals(teacherLever)) {
						dto.setTeacherType("2");
					}else if(Constant.STAR_TEACHER.equals(teacherLever)) {
						dto.setTeacherType("3");
					}else if(Constant.SENIOR_TEACHER.equals(teacherLever)) {
						dto.setTeacherType("4");
					}
					if(StringUtils.isNotBlank(applyTeacher.getPersonalLabel())){
						dto.setTeacherLabels(Arrays.asList(applyTeacher.getPersonalLabel().split(",")));
					}
					dto.setGrade(applyTeacher.getGrade());
					dto.setTeacherSex(String.valueOf(applyTeacher.getSex()));
					//查询校长信息
					TbLibManager master = managerService.findByUserId((String)map.get("master_id"), Constant.SCHOOL_MASTER_TYPE);
		            String masterName = master.getName();
		            if(StringUtils.isBlank(master.getName())) {
		            	User masterUser = userService.getById(master.getUserId());
		            	masterName = masterUser.getName();
		            }
					dto.setMasterName(masterName);
					dtoList.add(dto);
				}else {
					//待支付
					dto.setBizType(4);
					dto.setVipId(vipId);
					dto.setLessonServiceId((String)map.get("lesson_service_id"));
					dto.setCourseId((String)map.get("id"));
					if(StringUtils.isNotBlank((String)map.get("teacher_id"))) {
						TbLibManager teacher = managerService.findByUserId((String)map.get("teacher_id"), Constant.KMT_121_TEACHER_TYPE);
						dto.setTeacherId(teacher.getUserId());
						dto.setTeacherName(teacher.getName());
						dto.setTeacherImg(teacher.gettPhoto());
						dto.setTeacherLever(String.valueOf(teacher.getPraise()));
						if(Constant.SUPER_TEACHER.equals(teacherLever)) {
							dto.setTeacherType("1");
						}else if(Constant.REGISTER_TEACHER.equals(teacherLever)) {
							dto.setTeacherType("2");
						}else if(Constant.STAR_TEACHER.equals(teacherLever)) {
							dto.setTeacherType("3");
						}else if(Constant.SENIOR_TEACHER.equals(teacherLever)) {
							dto.setTeacherType("4");
						}
					}
					if((int)map.get("status") == 0) {
						dto.setPlanStatus(1);
					}else {
						dto.setPlanStatus((int)map.get("plan_status"));
					}
					dto.setCourseName((String)map.get("course_name"));
					dto.setGrade((String)map.get("grade"));
					if((Integer)map.get("is_listen_test") == 1) {
						//如果有试听课  0/12
						dto.setStudyPlanCount((Integer)map.get("course_count")-1);
					}else {
						//如果没有试听课 1/12
						dto.setStudyPlanCount((Integer)map.get("course_count"));
					}
					dto.setStartTime((String)map.get("start_time"));
					dto.setEndTime((String)map.get("end_time"));
					//通过订单编号查询订单金额
					Order order = orderService.findOrderNo((String)map.get("order_no"));
					dto.setOrderAmount(order.getOrderMoney().toString());
					dtoList.add(dto);
				}
			}
		}
		return dtoList;
	}

	@Override
	public List<LessonServicePlanDto> findParentCoursePlan(String vipId) {
		List<LessonServicePlanDto> dtoList = new ArrayList<LessonServicePlanDto>();
		List<Map<String, Object>> list= lessonServiceQueryDao.findParentCoursePlan(vipId);
		if(!CollectionUtils.isEmpty(list)) {
			LibVip libVip = libVipService.getById(vipId);
			for (Map<String, Object> map : list) {
				String teacherLever = (String)map.get("teacher_lever");
				LessonServicePlanDto dto = new LessonServicePlanDto();
				dto.setChildName(libVip.getChildName());
				Integer isApply = (Integer)map.get("is_apply");
				if(isApply != null && isApply == 1) {
					LessonServiceApply apply = lessonServiceApplyService.findByKmtCourseIdAndType((String)map.get("lesson_service_id"),2);
					if(apply != null) {
						dto.setIsRequestChangeTeacher(1);
						dto.setApplyType(2);
						dto.setApplyStatus(1);
						dto.setApplyReason(apply.getReason());
					}
					if(apply != null && StringUtils.isNotBlank(apply.getTeacherId())) {
						//有校长调老师记录，家长待确定更换老师
						TbLibManager applyTeacher = managerService.findByUserId(apply.getTeacherId(), Constant.KMT_121_TEACHER_TYPE);
						dto.setApplyType(2);
						dto.setApplyStatus(1);
						dto.setApplyReason(apply.getReason());
						dto.setBizType(3);
						dto.setVipId(vipId);
						dto.setLessonServiceId((String)map.get("lesson_service_id"));
						dto.setCourseId((String)map.get("id"));
						dto.setTeacherId(apply.getTeacherId());
						dto.setTeacherName(applyTeacher.getName());
						dto.setTeacherImg(applyTeacher.gettPhoto());
						if(Constant.SUPER_TEACHER.equals(teacherLever)) {
							dto.setTeacherType("1");
						}else if(Constant.REGISTER_TEACHER.equals(teacherLever)) {
							dto.setTeacherType("2");
						}else if(Constant.STAR_TEACHER.equals(teacherLever)) {
							dto.setTeacherType("3");
						}else if(Constant.SENIOR_TEACHER.equals(teacherLever)) {
							dto.setTeacherType("4");
						}
						if(StringUtils.isNotBlank(applyTeacher.getPersonalLabel())){
							dto.setTeacherLabels(Arrays.asList(applyTeacher.getPersonalLabel().split(",")));
						}
						dto.setTeacherSex(String.valueOf(applyTeacher.getSex()));
						//查询校长信息
						TbLibManager master = managerService.findByUserId((String)map.get("master_id"), Constant.SCHOOL_MASTER_TYPE);
			            String masterName = master.getName();
			            if(StringUtils.isBlank(master.getName())) {
			            	User masterUser = userService.getById(master.getUserId());
			            	masterName = masterUser.getName();
			            }
						dto.setMasterName(masterName);
						dto.setCourseName((String)map.get("course_name"));
						dto.setGrade((String)map.get("grade"));
						dto.setCourseType((int)map.get("course_type"));
						String attendClassTime = map.get("course_time").toString() +" "+map.get("course_start").toString()+"-"+map.get("course_end").toString();
						dto.setAttendClassTime(attendClassTime);
						dtoList.add(dto);
						continue;
					}
					
					
					//如果申请老师不在审批中
					if(dto.getApplyStatus() != 1) {
						//查看是否有调课申请
						
						//查询最新的申请
						LessonServiceApply hisApply = lessonServiceApplyService.findHistoryApplyByKmtCourseIdOrLessonServiceIdOrderByCreateTimeDesc((String)map.get("id"), (String)map.get("lesson_service_id"));
						
						//查看是否有调课申请
						apply = lessonServiceApplyService.findFirstByKmtCourseIdAndType((String)map.get("id"),1);
						if(apply != null) {
							if(apply.getStatus() == 0) {
								dto.setApplyType(1);
								dto.setApplyStatus(1);
								dto.setApplyReason(apply.getReason());
								dto.setBizType(4);
								dto.setVipId(vipId);
								dto.setLessonServiceId((String)map.get("lesson_service_id"));
								dto.setCourseId((String)map.get("id"));
								if(StringUtils.isNotBlank((String)map.get("teacher_id"))) {
									TbLibManager teacher = managerService.findByUserId((String)map.get("teacher_id"), Constant.KMT_121_TEACHER_TYPE);
									dto.setTeacherId(teacher.getUserId());
									dto.setTeacherName(teacher.getName());
									dto.setTeacherImg(teacher.gettPhoto());
									dto.setTeacherLever(String.valueOf(teacher.getPraise()));
									if(Constant.SUPER_TEACHER.equals(teacherLever)) {
										dto.setTeacherType("1");
									}else if(Constant.REGISTER_TEACHER.equals(teacherLever)) {
										dto.setTeacherType("2");
									}else if(Constant.STAR_TEACHER.equals(teacherLever)) {
										dto.setTeacherType("3");
									}else if(Constant.SENIOR_TEACHER.equals(teacherLever)) {
										dto.setTeacherType("4");
									}
								}
								dto.setPlanStatus((int)map.get("plan_status"));
								dto.setCourseName((String)map.get("course_name"));
								dto.setGrade((String)map.get("grade"));
								dto.setCourseType((int)map.get("course_type"));
								if((Integer)map.get("is_listen_test") == 1) {
									//如果有试听课  0/12
									dto.setStudyPlanCount((Integer)map.get("course_count")-1);
									dto.setStudyCount((Integer)map.get("current_count")-1);
								}else {
									//如果没有试听课 1/12
									dto.setStudyPlanCount((Integer)map.get("course_count"));
									dto.setStudyCount((Integer)map.get("current_count"));
								}
								dto.setIsRequestChangeClassTime(1);
								
								//计划时间
								String attendTime = DateUtil.format_yyyyMMdd(apply.getOldClassTime());
								String start = DateUtil.format_HHmm(apply.getOldClassTime());
								String end = DateUtil.format_HHmm(DateHelper.getAddHour(apply.getOldClassTime(), 2, 0));
								dto.setAttendClassTime(attendTime+" "+start+"-"+end);
								
								//现申请新调课时间
								String adjustTime = DateUtil.format_yyyyMMdd(apply.getAdjustTime());
								start = DateUtil.format_HHmm(apply.getAdjustTime());
								end = DateUtil.format_HHmm(DateHelper.getAddHour(apply.getAdjustTime(), 2, 0));
								dto.setRequestAttendClassTime(adjustTime+" "+start+"-"+end);
								dtoList.add(dto);
								continue;
							}else if(hisApply.getType() == 1){
								dto.setBizType(4);
								dto.setVipId(vipId);
								dto.setLessonServiceId((String)map.get("lesson_service_id"));
								dto.setCourseId((String)map.get("id"));
								if(StringUtils.isNotBlank((String)map.get("teacher_id"))) {
									TbLibManager teacher = managerService.findByUserId((String)map.get("teacher_id"), Constant.KMT_121_TEACHER_TYPE);
									dto.setTeacherId(teacher.getUserId());
									dto.setTeacherName(teacher.getName());
									dto.setTeacherImg(teacher.gettPhoto());
									dto.setTeacherLever(String.valueOf(teacher.getPraise()));
									if(Constant.SUPER_TEACHER.equals(teacherLever)) {
										dto.setTeacherType("1");
									}else if(Constant.REGISTER_TEACHER.equals(teacherLever)) {
										dto.setTeacherType("2");
									}else if(Constant.STAR_TEACHER.equals(teacherLever)) {
										dto.setTeacherType("3");
									}else if(Constant.SENIOR_TEACHER.equals(teacherLever)) {
										dto.setTeacherType("4");
									}
								}
								dto.setPlanStatus((int)map.get("plan_status"));
								dto.setCourseName((String)map.get("course_name"));
								dto.setGrade((String)map.get("grade"));
								dto.setCourseType((int)map.get("course_type"));
								if((Integer)map.get("is_listen_test") == 1) {
									//如果有试听课  0/12
									dto.setStudyPlanCount((Integer)map.get("course_count")-1);
									dto.setStudyCount((Integer)map.get("current_count")-1);
								}else {
									//如果没有试听课 1/12
									dto.setStudyPlanCount((Integer)map.get("course_count"));
									dto.setStudyCount((Integer)map.get("current_count"));
								}
								dto.setIsRequestChangeClassTime(1);
								
								//计划时间
								String attendTime = DateUtil.format_yyyyMMdd(apply.getOldClassTime());
								String start = DateUtil.format_HHmm(apply.getOldClassTime());
								String end = DateUtil.format_HHmm(DateHelper.getAddHour(apply.getOldClassTime(), 2, 0));
								dto.setAttendClassTime(attendTime+" "+start+"-"+end);
								
								//现申请新调课时间
								String adjustTime = DateUtil.format_yyyyMMdd(apply.getAdjustTime());
								start = DateUtil.format_HHmm(apply.getAdjustTime());
								end = DateUtil.format_HHmm(DateHelper.getAddHour(apply.getAdjustTime(), 2, 0));
								dto.setRequestAttendClassTime(adjustTime+" "+start+"-"+end);
								dtoList.add(dto);
								
								//新增调整理由
								String refuseReason = (String)map.get("refuse_reason");
								if(StringUtils.isBlank(refuseReason)) {
									//同意调整
									dto.setApplyType(hisApply.getType());
									dto.setApplyStatus(2);
								}else {
									//拒绝调整
									dto.setApplyStatus(3);
									//获取最新的申请理由
									dto.setApplyType(hisApply.getType());
									dto.setApplyReason(hisApply.getReason());
									dto.setReason(refuseReason);
								}
								continue;
							}
						}
						
						//新增调整理由
						String refuseReason = (String)map.get("refuse_reason");
						if(StringUtils.isBlank(refuseReason)) {
							//同意调整
							dto.setApplyType(hisApply.getType());
							dto.setApplyStatus(2);
						}else {
							//拒绝调整
							dto.setApplyStatus(3);
							//获取最新的申请理由
							dto.setApplyType(hisApply.getType());
							dto.setApplyReason(hisApply.getReason());
							dto.setReason(refuseReason);
						}
						
					}
				}
				//上课学习计划
				dto.setBizType(4);
				dto.setVipId(vipId);
				dto.setLessonServiceId((String)map.get("lesson_service_id"));
				dto.setCourseId((String)map.get("id"));
				if(StringUtils.isNotBlank((String)map.get("teacher_id"))) {
					TbLibManager teacher = managerService.findByUserId((String)map.get("teacher_id"), Constant.KMT_121_TEACHER_TYPE);
					dto.setTeacherId(teacher.getUserId());
					dto.setTeacherName(teacher.getName());
					dto.setTeacherImg(teacher.gettPhoto());
					dto.setTeacherLever(String.valueOf(teacher.getPraise()));
					if(Constant.SUPER_TEACHER.equals(teacherLever)) {
						dto.setTeacherType("1");
					}else if(Constant.REGISTER_TEACHER.equals(teacherLever)) {
						dto.setTeacherType("2");
					}else if(Constant.STAR_TEACHER.equals(teacherLever)) {
						dto.setTeacherType("3");
					}else if(Constant.SENIOR_TEACHER.equals(teacherLever)) {
						dto.setTeacherType("4");
					}
				}
				dto.setPlanStatus((int)map.get("plan_status"));
				dto.setCourseName((String)map.get("course_name"));
				dto.setGrade((String)map.get("grade"));
				dto.setCourseType((int)map.get("course_type"));
				if((Integer)map.get("is_listen_test") == 1) {
					//如果有试听课  0/12
					dto.setStudyPlanCount((Integer)map.get("course_count")-1);
					dto.setStudyCount((Integer)map.get("current_count")-1);
				}else {
					//如果没有试听课 1/12
					dto.setStudyPlanCount((Integer)map.get("course_count"));
					dto.setStudyCount((Integer)map.get("current_count"));
				}
				String attendClassTime = map.get("course_time").toString() +" "+map.get("course_start").toString()+"-"+map.get("course_end").toString();
				dto.setAttendClassTime(attendClassTime);
				dtoList.add(dto);
			}
		}
		return dtoList;
	}

	@Override
	public List<LessonServicePlanDto> findParentCourseFeedback(String vipId) {
		List<LessonServicePlanDto> dtoList = new ArrayList<LessonServicePlanDto>();
		List<Map<String, Object>> list= lessonServiceQueryDao.findParentCourseFeedback(vipId);
		if(!CollectionUtils.isEmpty(list)) {
			LibVip libVip = libVipService.getById(vipId);
			for (Map<String, Object> map : list) {
				String teacherLever = (String)map.get("teacher_lever");
				LessonServicePlanDto dto = new LessonServicePlanDto();
				dto.setBizType(4);
				dto.setVipId(vipId);
				dto.setLessonServiceId((String)map.get("lesson_service_id"));
				dto.setCourseId((String)map.get("id"));
				dto.setPlanStatus((int)map.get("plan_status"));
				if((Integer)map.get("is_listen_test") == 1) {
					//如果有试听课  0/12
					dto.setStudyPlanCount((Integer)map.get("course_count")-1);
					dto.setStudyCount((Integer)map.get("num")-1);
				}else {
					//如果没有试听课 1/12
					dto.setStudyPlanCount((Integer)map.get("course_count"));
					dto.setStudyCount((Integer)map.get("num"));
				}
				dto.setChildName(libVip.getChildName());
				if(Constant.SUPER_TEACHER.equals(teacherLever)) {
					dto.setTeacherType("1");
				}else if(Constant.REGISTER_TEACHER.equals(teacherLever)) {
					dto.setTeacherType("2");
				}else if(Constant.STAR_TEACHER.equals(teacherLever)) {
					dto.setTeacherType("3");
				}else if(Constant.SENIOR_TEACHER.equals(teacherLever)) {
					dto.setTeacherType("4");
				}
				//反馈信息
				Map<String, Object> studyMap = zybService.findTodayOneFinishTask(map.get("vip_id").toString(),map.get("lesson_service_id").toString());
              	if(studyMap != null && studyMap.get("status") != null){
	           		if(studyMap.get("class_line") != null) {
	           			dto.setLever(studyMap.get("class_line").toString());
	           		}
	           		//学习板块信息
	           		List<String> modelList = new ArrayList<String>();
	           		String zongti = "在总体板块，已记录错题"+studyMap.get("ztnum").toString()+"道";
	           		String kehou = "在课后巩固板块，已记录错题"+studyMap.get("khggnum").toString()+"道";
	           		String niudao = "在小试牛刀板块，已记录错题"+studyMap.get("ndaonum").toString()+"道";
	           		modelList.add(zongti);
	           		modelList.add(kehou);
	           		modelList.add(niudao);
	           		dto.setModelList(modelList);
              	}
              	dtoList.add(dto);
			}
		}
		return dtoList;
	}

	@Override
	public int checkIsLessonOrGroupService(String vipId, int isGroup) {
		int count = lessonServiceDao.checkIsLessonOrGroupService(vipId,isGroup);
		if(count >1) {
			count = 1;
		}
		return count;
	}

	@Override
	public List<LessonGroupServicePlanDto> findParentGroupNoPayLessonService(String vipId) {
		//查询小课未支付订单
		List<LessonGroupServicePlanDto> dtoList = new ArrayList<LessonGroupServicePlanDto>();
		List<Map<String, Object>> list= lessonServiceQueryDao.findParentGroupNoPayLessonService(vipId);
		if(!CollectionUtils.isEmpty(list)) {
			LibVip libVip = libVipService.getById(vipId);
			for (Map<String, Object> map : list) {
				LessonGroupServicePlanDto dto = new LessonGroupServicePlanDto();
				dto.setChildName(libVip.getChildName());
				if (StringUtils.isEmpty(libVip.getChildName()) || StringUtils.isEmpty(libVip.getGrade())) {
					//待完善孩子信息
					dto.setBizType(1);
					dto.setVipId(vipId);
					dto.setChildImg(libVip.getImgUrl());
					dtoList.add(dto);
				}else {
					//待支付
					dto.setBizType(4);
					dto.setVipId(vipId);
					dto.setLessonServiceId((String)map.get("id"));
					dto.setLessonGroupId((String)map.get("lesson_group_id"));
					dto.setCourseName((String)map.get("course_name"));
					dto.setGrade((String)map.get("grade"));
					dto.setStudyPlanCount((Integer)map.get("course_count"));
					if(StringUtils.isNotBlank((String)map.get("teacher_id"))) {
						TbLibManager teacher = managerService.findByUserId((String)map.get("teacher_id"), Constant.KMT_121_TEACHER_TYPE);
						dto.setTeacherId(teacher.getUserId());
						dto.setTeacherName(teacher.getName());
					}
					if((int)map.get("status") == 0) {
						dto.setPlanStatus(1);
					}else {
						dto.setPlanStatus((int)map.get("plan_status"));
					}
					//是否换组下单
					dto.setIsChangeGroup((int)map.get("is_change_group"));
					dto.setStartTime((String)map.get("start_time"));
					dto.setEndTime((String)map.get("end_time"));
					//通过订单编号查询订单金额
					Order order = orderService.findOrderNo((String)map.get("order_no"));
					dto.setOrderAmount(order.getOrderMoney().toString());
					dtoList.add(dto);
				}
			}
		}
		return dtoList;
	}

	@Override
	public List<LessonGroupServicePlanDto> findParentGroupCoursePlan(String vipId) {
		//查询小课学生当前学习计划
		List<LessonGroupServicePlanDto> dtoList = new ArrayList<LessonGroupServicePlanDto>();
		List<Map<String, Object>> list= lessonServiceQueryDao.findParentGroupCoursePlan(vipId);
		if(!CollectionUtils.isEmpty(list)) {
			LibVip libVip = libVipService.getById(vipId);
			for (Map<String, Object> map : list) {
				LessonGroupServicePlanDto dto = new LessonGroupServicePlanDto();
				dto.setChildName(libVip.getChildName());
				//上课学习计划
				dto.setBizType(4);
				dto.setVipId(vipId);
				dto.setLessonServiceId((String)map.get("lesson_service_id"));
				dto.setCourseId((String)map.get("id"));
				dto.setLessonGroupId((String)map.get("lesson_group_id"));
				dto.setGroupName((String)map.get("group_name"));
				if(StringUtils.isNotBlank((String)map.get("teacher_id"))) {
					TbLibManager teacher = managerService.findByUserId((String)map.get("teacher_id"), Constant.KMT_121_TEACHER_TYPE);
					dto.setTeacherId(teacher.getUserId());
					dto.setTeacherName(teacher.getName());
					dto.setTeacherImg(teacher.gettPhoto());
					dto.setTeacherLever(String.valueOf(teacher.getPraise()));
				}
				dto.setPlanStatus((int)map.get("plan_status"));
				dto.setCourseName((String)map.get("course_name"));
				dto.setGrade((String)map.get("grade"));
				dto.setStudyPlanCount((Integer)map.get("course_count"));
				//当前课次为：订单总课次-组总课次+组当前课次
				int currentCount = dto.getStudyPlanCount()-(Integer)map.get("sum_course")+(Integer)map.get("current_count");
				dto.setStudyCount(currentCount);
				String attendClassTime = map.get("course_time").toString() +" "+map.get("course_start").toString()+"-"+map.get("course_end").toString();
				dto.setAttendClassTime(attendClassTime);
				dtoList.add(dto);
			}
		}
		return dtoList;
	}

	@Override
	public List<LessonGroupServicePlanDto> findParentGroupCourseFeedback(String vipId) {
		//查询小课最近一次学习反馈
		List<LessonGroupServicePlanDto> dtoList = new ArrayList<LessonGroupServicePlanDto>();
		List<Map<String, Object>> list= lessonServiceQueryDao.findParentGroupCourseFeedback(vipId);
		if(!CollectionUtils.isEmpty(list)) {
			LibVip libVip = libVipService.getById(vipId);
			for (Map<String, Object> map : list) {
				LessonGroupServicePlanDto dto = new LessonGroupServicePlanDto();
				dto.setBizType(4);
				dto.setVipId(vipId);
				dto.setLessonServiceId((String)map.get("lesson_service_id"));
				dto.setCourseId((String)map.get("id"));
				dto.setLessonGroupId((String)map.get("lesson_group_id"));
				dto.setPlanStatus((int)map.get("plan_status"));
				//课次信息
				dto.setStudyPlanCount((Integer)map.get("course_count"));
				//当前课次为：订单总课次-组总课次+组当前课次
				int currentCount = dto.getStudyPlanCount()-(Integer)map.get("sum_course")+(Integer)map.get("num");
				dto.setStudyCount(currentCount);
				dto.setChildName(libVip.getChildName());
				//反馈信息
				Map<String, Object> studyMap = zybService.findTodayOneFinishTask(map.get("vip_id").toString(),map.get("lesson_service_id").toString());
              	if(studyMap != null && studyMap.get("status") != null){
	           		if(studyMap.get("class_line") != null) {
	           			dto.setLever(studyMap.get("class_line").toString());
	           		}
	           		//学习板块信息
	           		List<String> modelList = new ArrayList<String>();
	           		String zongti = "在总体板块，已记录错题"+studyMap.get("ztnum").toString()+"道";
	           		String kehou = "在课后巩固板块，已记录错题"+studyMap.get("khggnum").toString()+"道";
	           		String niudao = "在小试牛刀板块，已记录错题"+studyMap.get("ndaonum").toString()+"道";
	           		modelList.add(zongti);
	           		modelList.add(kehou);
	           		modelList.add(niudao);
	           		dto.setModelList(modelList);
              	}
              	dtoList.add(dto);
			}
		}
		return dtoList;
	}

    @Override
    public Integer countByLessonGroupIdAndStatus(String lessonGroupId, List<Integer> statusList) {
        return lessonServiceDao.countByLessonGroupIdAndStatusIn(lessonGroupId, statusList);
    }

	@Override
	public List<LessonService> findUnfinishServiceByMasterId(String masterId) {
    	//未完结服务的课程订单，包括0未支付，1已支付待服务
		return lessonServiceDao.findByMasterIdAndStatusLessThan(masterId, 2);
	}

	@Override
	public boolean validateVipLessonGroupOrder(String lessonGroupId, List<String> vipIdList) {
		int count =  lessonServiceDao.countByLessonGroupIdAndVipIdIn(lessonGroupId,vipIdList);
		if(count > 0) {
			return false;
		}
		return true;
	}

	@Override
	public List<LessonService> findNoSignInOffLessonList(String lessonGroupId) {
		return lessonServiceDao.findNoSignInOffLessonList(lessonGroupId);
	}

	@Override
	public Integer countCurrentCourseByLessonGroupIdAndStatus(String lessonGroupId, List<Integer> lessonServiceStatusList) {
		return lessonServiceDao.countCurrentCourseByLessonGroupIdAndStatus(lessonGroupId, lessonServiceStatusList);
	}

    @Override
    public List<LessonService> findByLessonGroupId(String lessonGroupId) {
        return lessonServiceDao.findAllByLessonGroupId(lessonGroupId);
    }
}
