package com.ym.mec.biz.event.listener;

import com.ym.mec.biz.dal.dao.TeacherDao;
import com.ym.mec.biz.dal.dto.SimpleUserDto;
import com.ym.mec.biz.event.SendMessageChangeEvent;
import com.ym.mec.biz.service.SysMessageService;
import com.ym.mec.common.tenant.TenantContextHolder;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Map;

//发送短信，邮件，推送(暂时没用到)
@Component
public class SendMessageListener implements ApplicationListener<SendMessageChangeEvent> {

    @Resource
    private SysMessageService sysMessageService;
    @Resource
    private TeacherDao teacherDao;

    @Async
    @Override
    public void onApplicationEvent(SendMessageChangeEvent event) {
        Map<Integer, String> receivers = event.getReceivers();
        if(receivers.size() > 0){
            Integer userId = receivers.keySet().iterator().next();
            SimpleUserDto simpleUserDto = teacherDao.getSimpleUser(userId);
            TenantContextHolder.setTenantId(simpleUserDto.getTenantId());
            sysMessageService.batchSendMessage(event.getMessageSender()
                    , event.getMsgTemplate(),
                    event.getReceivers(), null, 0,
                    event.getUrl(), event.getPushType(),
                    Arrays.stream(event.getArgs()).toArray(Object[]::new));
            TenantContextHolder.clearTenantId();
        }
    }
}
