package com.szwl.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.szwl.constant.ConfigConsts;
import com.szwl.model.bean.WeChatTemplateMsg;
import com.szwl.model.entity.TAdmin;
import com.szwl.model.entity.TWechat;
import com.szwl.mapper.TWechatMapper;
import com.szwl.service.TAdminService;
import com.szwl.service.TWechatService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
*
* 服务实现类
*
*
* @author wuhs
* @since 2023-05-22
*/
@Slf4j
@Service
public class TWechatServiceImpl extends ServiceImpl implements TWechatService {
@Autowired
TAdminService adminService;
@Resource
private StringRedisTemplate redisTemplate;
private static final String SZ_ACCESS_TOKEN_KEY = "sz_wechat_access_token";
private static final String SC_ACCESS_TOKEN_KEY = "sc_wechat_access_token";
/**
* 缓存1个半小时(90分钟)
*/
private static final long EXPIRATION_TIME = 90 * 60;
@Override
public void sendNoworkMessage(String openId, String clientId, String name, String ifForeign, String companyType) {
// 模板参数
Map sendMag = new HashMap();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String alarmTime = format.format(new Date());
if(name.length() > 20) {
name = name.substring(0, 16) + "...";
}
if (StringUtils.isEmpty(ifForeign) || ifForeign.equals("0")) {
// 国内
sendMag.put("thing11", new WeChatTemplateMsg(name));
sendMag.put("character_string14", new WeChatTemplateMsg(clientId.substring(clientId.length()-6)));
sendMag.put("thing4", new WeChatTemplateMsg("严重"));
sendMag.put("time5", new WeChatTemplateMsg(alarmTime));
sendMag.put("thing6", new WeChatTemplateMsg("机器可能出现断网或突然断电,请及时处理!"));
} else {
// 国外
sendMag.put("thing11", new WeChatTemplateMsg(name));
sendMag.put("character_string14", new WeChatTemplateMsg(clientId.substring(clientId.length()-6)));
sendMag.put("thing4", new WeChatTemplateMsg("Serious"));
sendMag.put("time5", new WeChatTemplateMsg(alarmTime));
sendMag.put("thing6", new WeChatTemplateMsg("Power/Network loss."));
}
sendWechatMessage(openId, sendMag, companyType);
}
@Override
public void sendAlarmMessage(String openId, String clientId, String name, String companyType, String alarmContent, Date occurrenceTime) {
// 模板参数
Map sendMag = new HashMap();
// 转换时间为String类型
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String alarmTime = format.format(occurrenceTime);
// 模版参数
if(name.length() > 20) {
sendMag.put("thing11", new WeChatTemplateMsg(name.substring(0, 16) + "..."));
} else {
sendMag.put("thing11", new WeChatTemplateMsg(name));
}
sendMag.put("character_string14", new WeChatTemplateMsg(clientId.substring(clientId.length()-6)));
sendMag.put("thing4", new WeChatTemplateMsg("高"));
sendMag.put("time5", new WeChatTemplateMsg(alarmTime));
sendMag.put("thing6", new WeChatTemplateMsg(alarmContent));
sendWechatMessage(openId, sendMag, companyType);
}
@Override
public String getAccessToken(String companyType) {
String url= "";
String accessToken = "";
if(StringUtils.isEmpty(companyType) || companyType.equals("0")) {
url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+ ConfigConsts.SZ_WX_SUB_APP_ID + "&secret=" + ConfigConsts.SZ_WX_APP_SECRET;
TAdmin admin = adminService.getById(2738L);
admin.setApiKey(accessToken);
adminService.updateById(admin);
} else {
url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+ ConfigConsts.SC_WX_SUB_APP_ID + "&secret=" + ConfigConsts.SC_WX_APP_SECRET;
TAdmin admin = adminService.getById(2739L);
admin.setApiKey(accessToken);
adminService.updateById(admin);
}
PrintWriter out = null;
BufferedReader in = null;
String line;
StringBuffer stringBuffer = new StringBuffer();
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性 设置请求格式
//设置返回类型
conn.setRequestProperty("contentType", "text/plain");
//设置请求类型
conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
//设置超时时间
conn.setConnectTimeout(1000);
conn.setReadTimeout(1000);
conn.setDoOutput(true);
conn.connect();
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应 设置接收格式
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "UTF-8"));
while ((line = in.readLine()) != null) {
stringBuffer.append(line);
}
JSONObject jsonObject = JSONObject.parseObject(stringBuffer.toString());
log.info("获取token:{}",jsonObject.toString());
accessToken = jsonObject.getString("access_token");
if(StringUtils.isEmpty(companyType) || companyType.equals("0")) {
TAdmin admin = adminService.getById(2738L);
admin.setApiKey(accessToken);
adminService.updateById(admin);
} else {
TAdmin admin = adminService.getById(2739L);
admin.setApiKey(accessToken);
adminService.updateById(admin);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//使用finally块来关闭输出流、输入流
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return accessToken;
}
/**
* 获取accessToken推送消息
* @param openId
* @param sendMag
* @param companyType
* @return
*/
public void sendWechatMessage(String openId, Map sendMag, String companyType) {
String url = "";
String accessToken = "";
try {
if(StringUtils.isEmpty(companyType) || companyType.equals("0")) {
TAdmin admin = adminService.getById(2738L);
accessToken = admin.getApiKey();
} else {
TAdmin admin = adminService.getById(2739L);
accessToken = admin.getApiKey();
}
} catch (Exception e) {
e.printStackTrace();
}
if(StringUtils.isEmpty(accessToken)) {
accessToken = getAccessToken(companyType);
}
// 推送消息
RestTemplate restTemplate = new RestTemplate();
Map sendBody = new HashMap<>();
sendBody.put("touser", openId);
sendBody.put("topcolor", "#FF0000");
sendBody.put("data", sendMag);
if(StringUtils.isEmpty(companyType) || companyType.equals("0")) {
sendBody.put("template_id", ConfigConsts.SZ_TEMPLATE_ID);
sendBody.put("url", "http://szwlh.sunzee.com.cn/shenze/");
} else {
sendBody.put("template_id", ConfigConsts.SC_TEMPLATE_ID);
sendBody.put("url", "http://sevencloud.com.cn/sc/");
}
String sendUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
ResponseEntity forEntity = restTemplate.postForEntity(sendUrl, sendBody, String.class);
JSONObject jsonObject = JSONObject.parseObject(forEntity.getBody());
String messageCode = jsonObject.getString("errcode");
String msgId = jsonObject.getString("msgid");
System.out.println("messageCode : " + messageCode + ", msgId: " +msgId);
log.info("微信推送结果:{}","messageCode : " + messageCode + ", msgId: " +msgId);
}
}