package com.ycl.service.message.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ycl.controller.video.common.constant.ChannelCode;
import com.ycl.controller.video.common.util.CommonUtils;
import com.ycl.dto.message.MessageParam;
import com.ycl.entity.message.Message;
import com.ycl.entity.message.SendReq;
import com.ycl.entity.message.SendRes;
import com.ycl.exception.ApiException;
import com.ycl.mapper.message.MessageMapper;
import com.ycl.mapper.user.UmsAdminMapper;
import com.ycl.service.message.IMessageService;
import com.ycl.utils.MD5Util;
import com.ycl.vo.message.MessageVO;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;
/**
*
* 消息 服务实现类
*
*
* @author mg
* @since 2022-10-08
*/
@Service
public class MessageServiceImpl extends ServiceImpl implements IMessageService {
@Value("${e-mail.sendHost}")
private String sendHost;
@Value("${e-mail.username}")
private String userName;
@Value("${e-mail.password}")
private String password;
@Value(value = "${SMS.ecName}")
private String ecName; //集团客户名称
@Value(value = "${SMS.apId}")
private String apId; //用户名
@Value(value = "${SMS.sign}")
private String sign; //网关签名编码,必填,签名编码在中国移动集团开通帐号后分配,可以在云MAS网页端管理子系统-SMS接口管理功能中下载。
@Value(value = "${SMS.url}")
private String url;
@Resource
private UmsAdminMapper umsAdminMapper;
@Resource
private MessageMapper messageMapper;
@Resource
RestTemplate restTemplate;
@Override
@Transactional(rollbackFor = Exception.class)
public String sendMessage(Message message) {
Message savedMessage = messageMapper.selectOne(new LambdaQueryWrapper()
.eq(Message::getTargetTo, message.getTargetTo())
.eq(Message::getTargetFrom, message.getTargetFrom())
.eq(Message::getBody, message.getBody())
.eq(Message::getHead, message.getHead()));
if (savedMessage != null) {
messageMapper.deleteById(savedMessage);
}
ArrayList ids = new ArrayList<>();
message.setTargetFrom(umsAdminMapper.selectById(message.getCreateUser()).getUsername());
for (String receive : message.getTargetTo().split(",")) {
Message sendMessage = new Message();
BeanUtils.copyProperties(message, sendMessage);
sendMessage.setCreateTime(new Date());
sendMessage.setSendTime(new Date());
sendMessage.setTargetTo(receive);
sendMessage.setSendTime(new Date());
this.save(sendMessage);
ids.add(sendMessage.getId());
}
switch (message.getChannelCode()) {
//邮件发送
case ChannelCode.SMS:
sendSMS(message, ids);
break;
//短信发送
case ChannelCode.MAIL:
sendMail(message);
break;
case ChannelCode.INNER:
break;
default:
throw new ApiException("未匹配到该类型");
}
return "send message success!";
}
@SneakyThrows
private void sendSMS(Message message, List mesIds) {
String context = "【" + message.getHead() + "】" + message.getBody();
String addSerial = "";
SendReq sendReq = new SendReq();
sendReq.setEcName(ecName);
sendReq.setApId(apId);
sendReq.setSign(sign);
sendReq.setContext(context);
String[] ids = message.getTargetTo().split(",");
String[] mobiles = new String[ids.length];
for (int i = 0; i < ids.length; i++) {
mobiles[i] = umsAdminMapper.selectById(ids[i]).getMobile();
}
sendReq.setMobiles(StringUtils.join(mobiles, ","));
sendReq.setAddSerial(addSerial);
StringBuffer mac = new StringBuffer();
mac.append(ecName);
mac.append(apId);
mac.append(sendReq.getMobiles());
mac.append(context);
mac.append(sign);
mac.append(addSerial);
sendReq.setMac(MD5Util.md5Encrypt32Lower(mac.toString()));
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
ObjectMapper objectMapper = new ObjectMapper();
HttpEntity stringHttpEntity = new HttpEntity<>(Base64Utils.encodeToString(objectMapper.writeValueAsBytes(mac)), httpHeaders);
SendRes sendRes = objectMapper.readValue(restTemplate.postForEntity(url, stringHttpEntity, String.class).getBody(), SendRes.class);
Message sendedMessage = new Message();
if (sendRes.getRspcod().equals("success")) {
for (Long id : mesIds) {
sendedMessage.setStatus(2);
sendedMessage.setRespondResult("发送成功");
sendedMessage.setId(id);
sendedMessage.setUpdateTime(new Date());
sendedMessage.setSendTime(new Date());
messageMapper.updateById(sendedMessage);
}
} else {
for (Long id : mesIds) {
sendedMessage.setStatus(3);
sendedMessage.setRespondResult("发送失败");
sendedMessage.setSendTime(new Date());
sendedMessage.setId(id);
sendedMessage.setUpdateTime(new Date());
messageMapper.updateById(sendedMessage);
}
}
}
//发送邮件
@SneakyThrows
private void sendMail(Message message) {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost(sendHost);
javaMailSender.setUsername(userName);
javaMailSender.setPassword(password);
javaMailSender.setPort(465);
Properties properties = new Properties();
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.auth", "true");//必须是字符串而不能是boolean否则报错
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.timeout", "1000");
properties.put("mail.smtp.host", sendHost);
javaMailSender.setJavaMailProperties(properties);
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
helper.setText(message.getBody());
helper.setSubject(message.getHead());
helper.setFrom(userName);
String[] ids = message.getTargetTo().split(",");
String[] address = new String[ids.length];
for (int i = 0; i < ids.length; i++) {
address[i] = umsAdminMapper.selectById(ids[i]).getEmail();
}
helper.setTo(address);
javaMailSender.send(mimeMessage);
}
@Override
public Page list(MessageParam messageParam) {
Page page = new Page<>(messageParam.getCurrent(), messageParam.getPageSize());
return messageMapper.selectMessagePage(page, messageParam);
}
@Override
public Boolean deleteMessages(List ids) {
LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.in(Message::getId, ids).or().in(Message::getParentId, ids);
List messages = baseMapper.selectList(queryWrapper);
if (CommonUtils.isNotEmpty(messages)) {
List deleteIds = messages.stream().map(Message::getId).collect(Collectors.toList());
baseMapper.deleteBatchIds(deleteIds);
}
return true;
}
}