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

import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.*;
import com.ym.mec.biz.dal.dto.StudentCourseHomeworkCommentDto;
import com.ym.mec.biz.dal.entity.ExtracurricularExercises;
import com.ym.mec.biz.dal.entity.ExtracurricularExercisesMessage;
import com.ym.mec.biz.dal.entity.ExtracurricularExercisesReply;
import com.ym.mec.biz.dal.entity.StudentExtracurricularExercisesSituation;
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.ExtracurricularExercisesMessageService;
import com.ym.mec.biz.service.StudentServeService;
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.page.PageInfo;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.thirdparty.message.MessageSenderPluginContext;
import com.ym.mec.util.collection.MapUtil;
import com.ym.mec.util.date.DateUtil;
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 java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class ExtracurricularExercisesMessageServiceImpl extends BaseServiceImpl<Long, ExtracurricularExercisesMessage> implements ExtracurricularExercisesMessageService {

	@Autowired
	private StudentExtracurricularExercisesSituationDao studentExtracurricularExercisesSituationDao;
	@Autowired
	private ExtracurricularExercisesMessageDao extracurricularExercisesMessageDao;
	@Autowired
	private ExtracurricularExercisesReplyDao extracurricularExercisesReplyDao;
	@Autowired
	private ExtracurricularExercisesDao extracurricularExercisesDao;
	@Autowired
	private SysMessageService sysMessageService;
	@Autowired
	private TeacherDao teacherDao;
	@Autowired
	private StudentServeService studentServeService;

	@Override
	public BaseDAO<Long, ExtracurricularExercisesMessage> getDAO() {
		return extracurricularExercisesMessageDao;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void addStudentExtraExerciseComment(ExtracurricularExercisesMessage extracurricularExercisesMessage) {
		if(Objects.isNull(extracurricularExercisesMessage.getExtracurricularExercisesReplyId())){
			throw new BizException("请指定学生课外训练");
		}
		if(StringUtils.isBlank(extracurricularExercisesMessage.getContent())){
			throw new BizException("请填写回复内容");
		}
		extracurricularExercisesMessageDao.insert(extracurricularExercisesMessage);
		ExtracurricularExercisesReply extracurricularExercisesReply = extracurricularExercisesReplyDao.get(extracurricularExercisesMessage.getExtracurricularExercisesReplyId());
		if(Objects.isNull(extracurricularExercisesReply)){
			throw new BizException("课外训练不存在");
		}
		ExtracurricularExercises extracurricularExercises = extracurricularExercisesDao.get(extracurricularExercisesReply.getExtracurricularExercisesId());
		if("TEACHER".equals(extracurricularExercisesMessage.getRole())){
			if(Objects.nonNull(extracurricularExercisesReply.getAttachments())){
				boolean change=false;
				if(!Integer.valueOf(1).equals(extracurricularExercisesReply.getIsRepliedTimely())&&Objects.nonNull(extracurricularExercisesReply.getSubmitTime())){
					int hours = DateUtil.hoursBetween(extracurricularExercisesReply.getSubmitTime(), new Date());
					if(hours>=0&&hours<=12){
						extracurricularExercisesReply.setIsRepliedTimely(1);
						change=true;
					}
				}
				if(extracurricularExercisesReply.getIsReplied()==0){
					extracurricularExercisesReply.setIsReplied(1);
					change=true;
				}
				if(change){
					extracurricularExercisesReplyDao.update(extracurricularExercisesReply);
					LocalDate nowDate = LocalDateTime.now(DateUtil.zoneId).toLocalDate();
					LocalDate monDayDate = nowDate.with(DateUtil.weekFields.dayOfWeek(), DayOfWeek.MONDAY.getValue());
					LocalDate createDateTime = LocalDateTime.ofInstant(extracurricularExercisesReply.getCreateTime().toInstant(), DateUtil.zoneId).toLocalDate();
					LocalDate createMonday = createDateTime.with(DateUtil.weekFields.dayOfWeek(), DayOfWeek.MONDAY.getValue());
					if(createDateTime.isBefore(monDayDate)){
						StudentExtracurricularExercisesSituation studentExercisesSituation = studentExtracurricularExercisesSituationDao.findStudentExercisesSituationsWithMonDay(createMonday.toString(), extracurricularExercisesReply.getUserId());
						if(Objects.nonNull(studentExercisesSituation)){
							if(new Integer(1).equals(extracurricularExercisesReply.getIsReplied())){
								studentExercisesSituation.setExercisesMessageNum(1);
							}
							if(new Integer(1).equals(extracurricularExercisesReply.getIsRepliedTimely())){
								studentExercisesSituation.setExercisesMessageTimelyNum(1);
							}
							studentExtracurricularExercisesSituationDao.update(studentExercisesSituation);
						}
					}
				}
			}

			Map<Integer, String> userMap = new HashMap<>();
			userMap.put(extracurricularExercisesReply.getUserId(),extracurricularExercisesReply.getUserId().toString());
			String notifyUrl = "?courseScheduleID=" + extracurricularExercisesReply.getId() + "&studentCourseHomeworkId=" + extracurricularExercisesReply.getId()+ "&extra=1";
			String extra = "dayaedu" + notifyUrl + "&userId=" + extracurricularExercisesReply.getUserId();
			if (extracurricularExercisesMessage.getMsgType() != ImSendTypeEnum.TXT){
				sysMessageService.batchSendImMessage(MessageTypeEnum.EXTRA_TEACHER_REPLY_IM,extracurricularExercises.getTeacherId().toString(),extra,
						new String[]{extracurricularExercisesReply.getUserId().toString()},
						null, extracurricularExercises.getTitle(), SysConfigService.NEW_MSG_PUSH);
			}else {
				sysMessageService.batchSendImMessage(MessageTypeEnum.EXTRA_TEACHER_REPLY_IM,extracurricularExercises.getTeacherId().toString(),extra,
						new String[]{extracurricularExercisesReply.getUserId().toString()},
						null, extracurricularExercises.getTitle(), extracurricularExercisesMessage.getContent());
			}
			sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.EXTRA_TEACHER_REPLY_PUSH,
					userMap, null, 0, 3+notifyUrl, "STUDENT", extracurricularExercises.getTitle());
		}else if("STUDENT".equals(extracurricularExercisesMessage.getRole())&&Objects.nonNull(extracurricularExercisesReply.getAttachments())){
			Map<Integer, String> userMap = new HashMap<>();
			userMap.put(extracurricularExercises.getTeacherId(), extracurricularExercises.getTeacherId().toString());
			SysUser user = teacherDao.getUser(extracurricularExercisesReply.getUserId());

			String notifyUrl = "?courseScheduleID=" + extracurricularExercisesReply.getId() +
					"&userId=" + extracurricularExercisesReply.getUserId() + "&studentCourseHomeworkId=" + extracurricularExercisesReply.getId()+ "&extra=1";
			if (extracurricularExercisesMessage.getMsgType() != ImSendTypeEnum.TXT){
				sysMessageService.batchSendImMessage(MessageTypeEnum.EXTRA_STUDENT_REPLY_IM,extracurricularExercisesReply.getUserId().toString(),"dayaedu"+notifyUrl,
						new String[]{extracurricularExercises.getTeacherId().toString()},
						null,extracurricularExercises.getTitle(), SysConfigService.NEW_MSG_PUSH);
			}else {
				sysMessageService.batchSendImMessage(MessageTypeEnum.EXTRA_STUDENT_REPLY_IM,extracurricularExercisesReply.getUserId().toString(),"dayaedu"+notifyUrl,
						new String[]{extracurricularExercises.getTeacherId().toString()},
						null,extracurricularExercises.getTitle(), extracurricularExercisesMessage.getContent());
			}
			sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.EXTRA_STUDENT_REPLY_PUSH,
					userMap, null, 0, 9+notifyUrl, "TEACHER", extracurricularExercises.getTitle(), user.getUsername());
		}
		studentServeService.updateExercisesSituation(extracurricularExercises.getCreateTime(), new ArrayList<>(Arrays.asList(extracurricularExercisesReply.getUserId())), extracurricularExercises.getTeacherId());
	}

	@Override
	public PageInfo findStudentExtraExerciseComments(StudentCourseHomeworkReplyQueryInfo queryInfo) {
		PageInfo<StudentCourseHomeworkCommentDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
		Map<String, Object> params = new HashMap<>();
		MapUtil.populateMap(params, queryInfo);

		List<StudentCourseHomeworkCommentDto> dataList = null;
		int count = extracurricularExercisesMessageDao.countStudentExtraComments(params);
		if (count > 0) {
			pageInfo.setTotal(count);
			params.put("offset", pageInfo.getOffset());
			dataList = extracurricularExercisesMessageDao.findStudentExtraComments(params);
		}
		if (count == 0) {
			dataList = new ArrayList<>();
		}
		pageInfo.setRows(dataList);
		return pageInfo;
	}
}
