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

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.ImSendGroupMessageDao;
import com.ym.mec.biz.dal.dao.SysConfigDao;
import com.ym.mec.biz.dal.entity.ImSendGroupMessage;
import com.ym.mec.biz.dal.enums.ImSendTypeEnum;
import com.ym.mec.biz.service.ImSendGroupMessageService;
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 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.util.*;
import java.util.stream.Collectors;

@Service
public class ImSendGroupMessageServiceImpl extends BaseServiceImpl<Long, ImSendGroupMessage>  implements ImSendGroupMessageService {
	
	@Autowired
	private ImSendGroupMessageDao imSendGroupMessageDao;
	@Autowired
	private SysMessageService sysMessageService;
	@Autowired
	private SysUserFeignService sysUserFeignService;
	@Autowired
	private SysConfigDao sysConfigDao;

	@Override
	public BaseDAO<Long, ImSendGroupMessage> getDAO() {
		return imSendGroupMessageDao;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void sendTimedMessages() throws Exception {
		List<ImSendGroupMessage> sendGroupMessages = imSendGroupMessageDao.findBySendFlag(false, new Date());
		if(sendGroupMessages.size() > 0){
			for(ImSendGroupMessage messageDto : sendGroupMessages){
				messageDto.setSendFlag(true);
				send(messageDto);
			}
			imSendGroupMessageDao.batchUpdateSendFlag(sendGroupMessages);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void sendGroupMessage(ImSendGroupMessage messageDto) throws Exception {
		SysUser user = Optional.ofNullable(sysUserFeignService.queryUserInfo()).orElseThrow(() -> new BizException("用户不存在"));
		String[] split = messageDto.getTargetIds().split(",");
		if(split.length > 10){
			throw new BizException("单次目标用户(群组)不可超过10");
		}
		messageDto.setSenderId(user.getId().toString());
		messageDto.setOperator(user.getRealName());
		if(Objects.isNull(messageDto.getSendTime())){
			messageDto.setSendType("NOW");
			messageDto.setSendTime(new Date());
			messageDto.setSendFlag(true);
			send(messageDto);
		}
		imSendGroupMessageDao.insert(messageDto);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateGroupMessage(ImSendGroupMessage imSendGroupMessage) {
		ImSendGroupMessage message = imSendGroupMessageDao.get(imSendGroupMessage.getId());
		if(Objects.isNull(message)){
			throw new BizException("消息不存在");
		}
		if(message.getSendFlag()){
			throw new BizException("消息已发送");
		}
		//如果是图片类型，图片地址不能为空
		if((imSendGroupMessage.getMessageType() == ImSendTypeEnum.IMG || imSendGroupMessage.getMessageType() == ImSendTypeEnum.FILE) && StringUtils.isBlank(imSendGroupMessage.getFileUrl())){
			throw new BizException("文件地址不能为空");
		}
		imSendGroupMessageDao.update(imSendGroupMessage);
	}

    @Override
	@Transactional(rollbackFor = Exception.class)
    public void deleteGroupMessage(Long id) {
        ImSendGroupMessage message = imSendGroupMessageDao.get(id);
        if(Objects.isNull(message)){
            throw new BizException("消息不存在");
        }
        if(message.getSendFlag()){
            throw new BizException("消息已发送");
        }
        imSendGroupMessageDao.delete(id);
    }

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteGroupList(Long imSendGroupMessageId, String groupIds) {
		ImSendGroupMessage sendGroupMessage =
				Optional.ofNullable(imSendGroupMessageDao.get(imSendGroupMessageId)).orElseThrow(() -> new BizException("消息不存在"));
		if(sendGroupMessage.getSendFlag()){
			throw new BizException("消息已发送");
		}
		//剔除指定的群列表
		List<String> groupIdList = Arrays.stream(groupIds.split(",")).collect(Collectors.toList());
		List<String> targetIdList = Arrays.stream(sendGroupMessage.getTargetIds().split(",")).collect(Collectors.toList());
		targetIdList.removeAll(groupIdList);
		if (targetIdList.size() == 0) {
			throw new BizException("消息没有指定群组");
		}
		sendGroupMessage.setTargetIds(String.join(",", targetIdList));
		imSendGroupMessageDao.update(sendGroupMessage);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void addGroupList(Long imSendGroupMessageId, String groupIds) {
		ImSendGroupMessage sendGroupMessage =
				Optional.ofNullable(imSendGroupMessageDao.get(imSendGroupMessageId)).orElseThrow(() -> new BizException("消息不存在"));
		if(sendGroupMessage.getSendFlag()){
			throw new BizException("消息已发送");
		}
		//添加指定的群列表
		Set<String> groupIdList = Arrays.stream(groupIds.split(",")).collect(Collectors.toSet());
		Set<String> targetIdList = Arrays.stream(sendGroupMessage.getTargetIds().split(",")).collect(Collectors.toSet());
		targetIdList.addAll(groupIdList);
		sendGroupMessage.setTargetIds(String.join(",", targetIdList));
		imSendGroupMessageDao.update(sendGroupMessage);
	}

	private void send(ImSendGroupMessage messageDto) throws Exception {
		if (Objects.equals(messageDto.getMessageType(), ImSendTypeEnum.IMG)) {
			sysMessageService.batchSendImGroupImgMessage(messageDto);
		} else if (Objects.equals(messageDto.getMessageType(),ImSendTypeEnum.FILE)) {
			sysMessageService.batchSendImGroupFileMessage(messageDto);
		}
		if(StringUtils.isNotEmpty(messageDto.getMessageContent())){
			sysMessageService.batchSendImGroupTxtMessage(messageDto);
		}
	}
}