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

import com.ym.mec.biz.dal.dao.MusicEnlightenmentQuestionnaireDao;
import com.ym.mec.biz.dal.dao.MusicGroupDao;
import com.ym.mec.biz.dal.dto.MusicEnlightenmentQuestionnaireStatDto;
import com.ym.mec.biz.dal.entity.MusicEnlightenmentQuestionnaire;
import com.ym.mec.biz.dal.entity.MusicGroup;
import com.ym.mec.biz.dal.enums.MessageTypeEnum;
import com.ym.mec.biz.dal.enums.MusicGroupStatusEnum;
import com.ym.mec.biz.dal.page.MusicEnlightenmentQuestionnaireQueryInfo;
import com.ym.mec.biz.service.MusicEnlightenmentQuestionnaireService;
import com.ym.mec.biz.service.StudentService;
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.common.tenant.TenantContextHolder;
import com.ym.mec.thirdparty.message.MessageSenderPluginContext;
import com.ym.mec.util.collection.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MusicEnlightenmentQuestionnaireServiceImpl extends BaseServiceImpl<Long, MusicEnlightenmentQuestionnaire>  implements MusicEnlightenmentQuestionnaireService {
	
	@Autowired
	private MusicEnlightenmentQuestionnaireDao musicEnlightenmentQuestionnaireDao;
	@Autowired
	private MusicGroupDao musicGroupDao;
	@Autowired
	private StudentService studentService;
	@Autowired
	private SysMessageService sysMessageService;

	private SimpleDateFormat sdf_ymdhm = new SimpleDateFormat("yyyy-MM-dd HH:mm");

	@Override
	public BaseDAO<Long, MusicEnlightenmentQuestionnaire> getDAO() {
		return musicEnlightenmentQuestionnaireDao;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void addEnlightenmentQuestionnaire(MusicEnlightenmentQuestionnaire enlightenmentQuestionnaire) {
		String musicGroupId = enlightenmentQuestionnaire.getMusicGroupId();
		String userPhone = enlightenmentQuestionnaire.getPhone();
		if(Objects.isNull(musicGroupId) || Objects.isNull(userPhone)){
			throw new BizException("问卷信息错误");
		}
		// 查询乐团状态
		MusicGroup musicGroup = musicGroupDao.get(musicGroupId);
		if (musicGroup == null) {
			throw new BizException("乐团信息错误");
		}
		if (musicGroup.getStatus() != MusicGroupStatusEnum.PRE_APPLY) {
			throw new BizException("乐团当前状态不能预报名");
		}
		TenantContextHolder.setTenantId(musicGroup.getTenantId());
		enlightenmentQuestionnaire.setTenantId(musicGroup.getTenantId());
		enlightenmentQuestionnaire.setOrganId(musicGroup.getOrganId());
		// 根据手机号检测学员是否存在，存在就更新，不存在插入
		studentService.upSetStudent(enlightenmentQuestionnaire);

		MusicEnlightenmentQuestionnaire musicEnlightenmentQuestionnaire = musicEnlightenmentQuestionnaireDao.lockUserMusicEnlightenmentQuestionnaire(musicGroupId, userPhone);
		if(Objects.isNull(musicEnlightenmentQuestionnaire)){
			musicEnlightenmentQuestionnaireDao.insert(enlightenmentQuestionnaire);
		}else{
			enlightenmentQuestionnaire.setId(musicEnlightenmentQuestionnaire.getId());
			musicEnlightenmentQuestionnaireDao.update(enlightenmentQuestionnaire);
		}
		TenantContextHolder.clearTenantId();
	}

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

		List<MusicEnlightenmentQuestionnaire> dataList = new ArrayList<>();
		int count = this.findCount(params);
		if (count > 0) {
			pageInfo.setTotal(count);
			params.put("offset", pageInfo.getOffset());
			dataList = this.getDAO().queryPage(params);
		}
		pageInfo.setRows(dataList);
		return pageInfo;
	}

	@Override
	public MusicEnlightenmentQuestionnaire getUserMusicEnlightenmentQuestionnaire(String musicGroupId, String phone) {
		return musicEnlightenmentQuestionnaireDao.lockUserMusicEnlightenmentQuestionnaire(musicGroupId, phone);
	}

	@Override
	public List<MusicEnlightenmentQuestionnaireStatDto> musicEnlightenmentQuestionnaireStat(String musicGroupId) {
		return musicEnlightenmentQuestionnaireDao.musicEnlightenmentQuestionnaireStat(musicGroupId);
	}

	@Override
	public boolean sendParentMeetingNotice(Integer userId, String musicGroupId, Date meetingDate, String address) {
		MusicGroup musicGroup = musicGroupDao.get(musicGroupId);
		if (musicGroup == null) {
			throw new BizException("乐团信息查询失败");
		}
		if (musicGroup.getStatus() != MusicGroupStatusEnum.PRE_APPLY) {
			throw new BizException("操作失败：只有乐团在[{}]状态才能操作", MusicGroupStatusEnum.PRE_APPLY.getMsg());
		}

		List<MusicEnlightenmentQuestionnaire> enlightenmentQuestionnaires = musicEnlightenmentQuestionnaireDao.findByMusicGroupId(musicGroupId);
		Map<Integer, String> receiverList = enlightenmentQuestionnaires.stream().filter(e->e.getJoinParentMeeting()).collect(Collectors.toMap(MusicEnlightenmentQuestionnaire::getUserId, MusicEnlightenmentQuestionnaire::getPhone));

		String meetingDateStr = sdf_ymdhm.format(meetingDate);
		sysMessageService.batchSendImGroupMessage(MessageTypeEnum.STUDENT_SMS_IM_MUSIC_GROUP_PARENT_MEETING_NOTICE, userId + "", null, new String[]{musicGroupId}, null, meetingDateStr, address);
		sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.AWSMS, MessageTypeEnum.STUDENT_SMS_IM_MUSIC_GROUP_PARENT_MEETING_NOTICE, receiverList, null, 1, null, null, meetingDateStr, address);
		return true;
	}
}
