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

import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.CourseScheduleDao;
import com.ym.mec.biz.dal.dao.StudentCourseHomeworkReplyDao;
import com.ym.mec.biz.dal.dao.SysConfigDao;
import com.ym.mec.biz.dal.dao.TeacherDao;
import com.ym.mec.biz.dal.dto.StudentCourseHomeworkCommentDto;
import com.ym.mec.biz.dal.entity.CourseSchedule;
import com.ym.mec.biz.dal.entity.StudentCourseHomework;
import com.ym.mec.biz.dal.entity.StudentCourseHomeworkReply;
import com.ym.mec.biz.dal.enums.ImSendTypeEnum;
import com.ym.mec.biz.dal.enums.MessageTypeEnum;
import com.ym.mec.biz.dal.page.StudentCourseHomeworkReplyQueryInfo;
import com.ym.mec.biz.service.*;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.common.page.QueryInfo;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.thirdparty.message.MessageSenderPluginContext;
import com.ym.mec.util.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class StudentCourseHomeworkReplyServiceImpl extends BaseServiceImpl<Long, StudentCourseHomeworkReply> implements StudentCourseHomeworkReplyService {
	
	@Autowired
	private StudentCourseHomeworkReplyDao studentCourseHomeworkReplyDao;
	@Autowired
	private StudentCourseHomeworkService studentCourseHomeworkService;
	@Autowired
	private CourseScheduleDao courseScheduleDao;
	@Autowired
	private TeacherDao teacherDao;
	@Autowired
	private SysConfigDao sysConfigDao;
	@Autowired
	private SysMessageService sysMessageService;
	@Autowired
	private StudentServeService studentServeService;

	@Override
	public BaseDAO<Long, StudentCourseHomeworkReply> getDAO() {
		return studentCourseHomeworkReplyDao;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public long insert(StudentCourseHomeworkReply bean) {
		StudentCourseHomework studentCourseHomework = studentCourseHomeworkService.get(bean.getStudentCourseHomeworkId());
		if(Objects.isNull(studentCourseHomework)){
			throw new BizException("请指定需要回复的作业");
		}
		CourseSchedule courseSchedule = courseScheduleDao.get(studentCourseHomework.getCourseScheduleId());
		Map<Integer, String> userMap = new HashMap<>();
		userMap.put(courseSchedule.getActualTeacherId(), courseSchedule.getActualTeacherId().toString());
		SysUser user = teacherDao.getUser(studentCourseHomework.getUserId());

		String notifyUrl = "9?courseScheduleID=" + studentCourseHomework.getId() + "&userId=" + studentCourseHomework.getUserId() + "&studentCourseHomeworkId=" + studentCourseHomework.getId() + "&extra=0";
		String extra = "dayaedu?courseScheduleID=" + courseSchedule.getId() + "&userId=" + studentCourseHomework.getUserId() + "&studentCourseHomeworkId=" + studentCourseHomework.getId() + "&extra=0";
		String courseDate = DateUtil.dateToString(courseSchedule.getClassDate(), "yyyy年MM月dd日");
		if (bean.getMsgType() != ImSendTypeEnum.TXT){
			sysMessageService.batchSendImMessage(MessageTypeEnum.IM_HOMEWORK_STUDENT_REPLY_PUSH,studentCourseHomework.getUserId().toString(),extra,
					new String[]{courseSchedule.getActualTeacherId().toString()},
					null,courseDate,courseSchedule.getName(),SysConfigService.NEW_MSG_PUSH);
		}else {
			sysMessageService.batchSendImMessage(MessageTypeEnum.IM_HOMEWORK_STUDENT_REPLY_PUSH,studentCourseHomework.getUserId().toString(),extra,
					new String[]{courseSchedule.getActualTeacherId().toString()},
					null,courseDate,courseSchedule.getName(),bean.getContent());
		}
		sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.HOMEWORK_STUDENT_REPLY_PUSH,
				userMap, null, 0, notifyUrl, "TEACHER", courseDate,courseSchedule.getName(), user.getUsername());
		return super.insert(bean);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void insertTeacherReply(StudentCourseHomeworkReply bean) {
		StudentCourseHomework studentCourseHomework = studentCourseHomeworkService.get(bean.getStudentCourseHomeworkId());
		if(Objects.isNull(studentCourseHomework)){
			throw new BizException("请指定需要回复的作业");
		}
		if(Objects.nonNull(studentCourseHomework.getAttachments())){
			studentCourseHomeworkService.updateReplyStatus(bean.getUserId(),
					studentCourseHomework.getCourseHomeworkId(),
					studentCourseHomework.getUserId());
		}

		CourseSchedule courseSchedule = courseScheduleDao.get(studentCourseHomework.getCourseScheduleId());
		Map<Integer, String> userMap = new HashMap<>();
		userMap.put(studentCourseHomework.getUserId(),studentCourseHomework.getUserId().toString());
		SysUser user = teacherDao.get(courseSchedule.getActualTeacherId());
		String notifyUrl = "?courseScheduleID=" + courseSchedule.getId() + "&studentCourseHomeworkId=" + studentCourseHomework.getId() + "&extra=0";
		String courseDate = DateUtil.dateToString(courseSchedule.getClassDate(), "yyyy年MM月dd日");
		String extra = "dayaedu" + notifyUrl + "&userId=" + studentCourseHomework.getUserId();
		if (bean.getMsgType() != ImSendTypeEnum.TXT){
			sysMessageService.batchSendImMessage(MessageTypeEnum.IM_HOMEWORK_TEACHER_REPLY_PUSH,courseSchedule.getActualTeacherId().toString(),extra,
					new String[]{studentCourseHomework.getUserId().toString()},
					null, courseDate,courseSchedule.getName(),SysConfigService.NEW_MSG_PUSH);
		}else {
			sysMessageService.batchSendImMessage(MessageTypeEnum.IM_HOMEWORK_TEACHER_REPLY_PUSH,courseSchedule.getActualTeacherId().toString(),extra,
					new String[]{studentCourseHomework.getUserId().toString()},
					null, courseDate,courseSchedule.getName(),bean.getContent());
		}

		sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.HOMEWORK_TEACHER_REPLY_PUSH,
				userMap, null, 0, 3+notifyUrl, "STUDENT", user.getRealName(), courseSchedule.getName());

		studentServeService.updateExercisesSituation(courseSchedule.getClassDate(), Arrays.asList(studentCourseHomework.getUserId()), courseSchedule.getActualTeacherId());
		super.insert(bean);
	}

	@Override
	public PageInfo queryPage(QueryInfo queryInfo) {
		StudentCourseHomeworkReplyQueryInfo studentCourseHomeworkReplyQueryInfo= (StudentCourseHomeworkReplyQueryInfo) queryInfo;
		studentCourseHomeworkReplyQueryInfo.setParentID(null);
		PageInfo studentCourseHomeworkReplyPageInfo = super.queryPage(studentCourseHomeworkReplyQueryInfo);
		for(Object temp:studentCourseHomeworkReplyPageInfo.getRows()){
			studentCourseHomeworkReplyQueryInfo.setParentID(((StudentCourseHomeworkCommentDto)temp).getReplyId());
			getTree((StudentCourseHomeworkCommentDto) temp,studentCourseHomeworkReplyQueryInfo);
		}
		return studentCourseHomeworkReplyPageInfo;
	}

	@Override
	public int delete(Long id) {
		StudentCourseHomeworkReply studentCourseHomeworkReply = super.get(id);
		List<Long> ids=new ArrayList<>();
		ids.add(id);
		List<StudentCourseHomeworkReply> allReplyByStudentCourseHomeworkID = studentCourseHomeworkReplyDao.findAllReplyByStudentCourseHomeworkID(studentCourseHomeworkReply.getStudentCourseHomeworkId());
		findAllChildID(id,allReplyByStudentCourseHomeworkID,ids);
		return studentCourseHomeworkReplyDao.batchDeleteReplys(ids);
	}

	private void findAllChildID(Long parentID,List<StudentCourseHomeworkReply> datas,List<Long> results){
		for(StudentCourseHomeworkReply data:datas){
			if(parentID.equals(data.getParentId())){
				results.add(data.getId());
				findAllChildID(data.getId(),datas,results);
			}
		}
	}

	private StudentCourseHomeworkCommentDto getTree(StudentCourseHomeworkCommentDto studentCourseHomeworkCommentDto, StudentCourseHomeworkReplyQueryInfo queryInfo){
		PageInfo pageInfo = super.queryPage(queryInfo);
		if(pageInfo != null && pageInfo.getRows().size() > 0) {
			studentCourseHomeworkCommentDto.setReplys(pageInfo.getRows());
			for (Object  object: pageInfo.getRows()) {
				queryInfo.setParentID(((StudentCourseHomeworkCommentDto)object).getReplyId());
				getTree((StudentCourseHomeworkCommentDto) object,queryInfo);
			}
		}
		return studentCourseHomeworkCommentDto;
	}

}
