package com.hssx.cloudmodel.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hssx.cloudmodel.constant.Constant;
import com.hssx.cloudmodel.entity.*;
import com.hssx.cloudmodel.entity.vo.MouldEquipmentVO;
import com.hssx.cloudmodel.entity.vo.UserVO;
import com.hssx.cloudmodel.mapper.*;
import com.hssx.cloudmodel.service.MouldEquipmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hssx.cloudmodel.util.*;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;
/**
*
* 服务实现类
*
*
* @author 吴涛涛
* @since 2019-08-02
*/
@Service
public class MouldEquipmentServiceImpl extends ServiceImpl implements MouldEquipmentService {
@Resource
MouldEquipmentMapper mouldEquipmentMapper;
@Resource
MouldMapper mouldMapper;
@Resource
UserMapper userMapper;
@Resource
NewsNoticeMapper newsNoticeMapper;
@Resource
NewsNoticeUserMapper newsNoticeUserMapper;
@Resource
PowerMapper powerMapper;
@Resource
ProjectMapper projectMapper;
@Resource
ProjectApproveMapper projectApproveMapper;
@Resource
MouldDownPacketMapper mouldDownPacketMapper;
@Resource
ProjectUserMapper projectUserMapper;
@Resource
ChangeIpCommandMapper changeIpCommandMapper;
@Resource
CompanyMapper companyMapper;
@Override
public HttpRespMsg addAndUpdateMouldEquipment(MouldEquipment mouldEquipment, User user) {
HttpRespMsg msg = new HttpRespMsg();
if (user.getParentId() == 0) {
if (mouldEquipment.getId() == null) {
//添加设备
//查询当前设备编号的模具是否存在
Integer count = mouldEquipmentMapper.selectCount(new QueryWrapper().eq("equipment_no", mouldEquipment.getEquipmentNo()));
if (count > 0) {
msg.setError("当前设备编号已存在,请重新输入其他模具编号");
} else {
mouldEquipmentMapper.insert(mouldEquipment);
}
} else {
//修改设备
MouldEquipment mouldEqu = mouldEquipmentMapper.selectById(mouldEquipment.getId());
MouldEquipment m = mouldEquipmentMapper.selectOne(new QueryWrapper().eq("equipment_no", mouldEquipment.getEquipmentNo()));
if (mouldEqu.getEquipmentNo().equals(mouldEquipment.getEquipmentNo()) || m == null) {
mouldEquipmentMapper.updateById(mouldEquipment);
} else {
msg.setError("当前设备编号已存在,请重新输入其他模具编号");
}
}
} else {
msg.setError("对不起,您不是管理员,不具备设备创建或修改的权限");
}
return msg;
}
@Override
public HttpRespMsg isUse(MouldEquipmentVO mouldEquipment, User user) {
HttpRespMsg msg = new HttpRespMsg();
//16进制的转化
String lowPowerLimitStr = Integer.toHexString(mouldEquipment.getLowPowerLimit());
if (lowPowerLimitStr.length() == 1) {
lowPowerLimitStr = "0" + lowPowerLimitStr;
}
String workInterval = Integer.toHexString(mouldEquipment.getWorkInterval());
if (workInterval.length() == 1) {
workInterval = "0" + workInterval;
}
String freeInterval = Integer.toHexString(mouldEquipment.getFreeInterval());
if (freeInterval.length() == 1) {
freeInterval = "0" + freeInterval;
}
String hotAlarmLimitStr = Integer.toHexString(mouldEquipment.getHotAlarmLimit());
if (hotAlarmLimitStr.length() == 1) {
hotAlarmLimitStr = "0" + hotAlarmLimitStr;
}
String isUseStr = "0" + Integer.toHexString(mouldEquipment.getIsUse());
String threshold = "";
if (null != mouldEquipment.getThreshold()) {
threshold = String.format("%04d", Integer.parseInt(mouldEquipment.getThreshold()));
}
//判断是不是超级管理员,是才可操作
if (user.getParentId() == 0) {
//修改设备
String[] split = mouldEquipment.getEquipmentNo().split(",");
MouldDownPacket packet = null;
String setPacketMessage = "";
for (String str : split) {
packet = mouldDownPacketMapper.selectOne(new QueryWrapper().eq("equipment_no", str));
MouldEquipment equipment = new MouldEquipment();
if (1 == mouldEquipment.getIsUse()) {
//启用中
equipment.setIsUse(2);
} else if (0 == mouldEquipment.getIsUse()) {
//停用中
equipment.setIsUse(3);
}
equipment.setEquipmentNo(mouldEquipment.getEquipmentNo());
equipment.setHillNumber(mouldEquipment.getLowPowerLimit() + "");
equipment.setTemperature(mouldEquipment.getHotAlarmLimit());
mouldEquipmentMapper.update(equipment, new QueryWrapper().eq("equipment_no", str));
MouldDownPacket mouldDownPacket = new MouldDownPacket();
if (!threshold.equals("")) {
mouldDownPacket.setThreshold(threshold);
}
if (0 == mouldEquipment.getIsUse()) {
setPacketMessage = "FAAF0007001e781e50003C";//停用
String crcCode = CRC16Util.getCRC(setPacketMessage);
setPacketMessage = setPacketMessage + crcCode;
} else {
setPacketMessage = downProcessMsg(lowPowerLimitStr, hotAlarmLimitStr, isUseStr, freeInterval, workInterval);
}
mouldDownPacket.setPacketStr(setPacketMessage);
mouldDownPacket.setIsUse(mouldEquipment.getIsUse());
mouldDownPacket.setEquipmentNo(str);
if (packet != null) {
mouldDownPacket.setId(packet.getId());
//已经存在更新下发数据包
mouldDownPacketMapper.updateById(mouldDownPacket);
} else {
mouldDownPacketMapper.insert(mouldDownPacket);
}
}
} else {
msg.setError("对不起,您不是超级管理员,不具备启用设备的权限");
return msg;
}
return msg;
}
@Override
public HttpRespMsg getList(User user, PageUtil page, Integer companyId, String keyName) {
HttpRespMsg msg = new HttpRespMsg();
if (user != null) {
if (Constant.SYS_PARENT_ID.equals(user.getParentId())) {
PageHelper.startPage(page.getPageNum(), page.getPageSize());
List mouldEquipments = mouldEquipmentMapper.getList(companyId, keyName);
PageInfo pageInfo = new PageInfo<>(mouldEquipments);
msg.data = pageInfo;
} else {
msg.setError("对不起,您不含有查看该列表的权利");
}
}
return msg;
}
@Override
public HttpRespMsg getListByCompanyId(MouldEquipmentVO mouldEquipmentVO) {
HttpRespMsg msg = new HttpRespMsg();
List mouldsEquipmentIds = mouldMapper.selectList(new QueryWrapper().eq("company_id", mouldEquipmentVO.getBelongCompanyId()).isNotNull("equipment_id")).stream().map(Mould::getEquipmentId).collect(Collectors.toList());
mouldsEquipmentIds.add(-1);
List equipmentIds = mouldEquipmentMapper.selectList(new QueryWrapper().eq("belong_company_id", mouldEquipmentVO.getBelongCompanyId()).eq("stage", 0)).stream().map(MouldEquipment::getId).collect(Collectors.toList());
equipmentIds.removeAll(mouldsEquipmentIds);//把已经使用的设备剔除
equipmentIds.add(-1);
List list = mouldEquipmentMapper.getListByCompanyId(mouldEquipmentVO.getBelongCompanyId(), equipmentIds);
msg.data = list;
return msg;
}
@Override
public HttpRespMsg MouldEquipmentAlarm() {
HttpRespMsg msg = new HttpRespMsg();
String token = GainTokenUtil.getToken();
List mouldEquipments = mouldEquipmentMapper.selectList(new QueryWrapper().eq("is_use", 1));
for (MouldEquipment mouldEquipment : mouldEquipments) {
Mould mould = mouldMapper.selectOne(new QueryWrapper().eq("equipment_id", mouldEquipment.getId()));
Project project = projectMapper.selectById(mould.getProjectId());
List uids = projectUserMapper.selectList(new QueryWrapper().eq("project_id", project.getId())).stream().map(ProjectUser::getUserId).collect(Collectors.toList());
uids.add(project.getManagerId());
uids.add(project.getCreatorId());
uids.add(-1);
List userList = userMapper.selectList(new QueryWrapper().in("id", uids).isNotNull("openid").eq("is_disable", 0));
if (Constant.ELECTRICITY_THRESHOLD >= Double.parseDouble(mouldEquipment.getHillNumber())) {
if (0 == mouldEquipment.getStage()) {
mouldEquipment.setStage(2);
} else {
mouldEquipment.setStage(3);
}
mouldEquipmentMapper.updateById(mouldEquipment);
//公众号的推送to do
userList.forEach(u -> {
try {
WechatTemplateUtil.sendEmergencyTemplateMessage(u.getOpenid(), mouldEquipment.getEquipmentName(), Constant.ELECTRICITY_TYPE, Constant.ELECTRICITY_CONTENT, token);
} catch (Exception e) {
e.printStackTrace();
}
});
//查询到参与该项目的人
List userIds = new ArrayList<>();
userIds.add(-1);
userIds.add(project.getCreatorId());
userIds.add(project.getManagerId());
List projectUsers = projectUserMapper.selectList(new QueryWrapper().eq("project_id", project.getId()));
for (ProjectUser projectUser : projectUsers) {
userIds.add(projectUser.getUserId());
}
List projectApproves = projectApproveMapper.selectList(new QueryWrapper().eq("project_id", project.getId()));
for (ProjectApprove projectApprove : projectApproves) {
userIds.add(projectApprove.getApproverId());
}
List users = userMapper.selectList(new QueryWrapper().in("id", userIds));
//查询到之前模具保养的消息
NewsNotice oldNews = newsNoticeMapper.selectOne(new QueryWrapper().eq("ref_id", mould.getId()).eq("notice_type", 2));
NewsNotice newsNotice = new NewsNotice();
if (oldNews != null) {
NewsNotice newNews = new NewsNotice();
newNews.setId(oldNews.getId());
oldNews.setIndate(LocalDateTime.now());
newsNoticeMapper.updateById(oldNews);
newsNoticeUserMapper.updateNewsNoticeUserByNewsNoticeId(oldNews.getId());
// for (User u : users) {
// //添加通知的消息
// NewsNoticeUser newsNoticeUser = new NewsNoticeUser();
// newsNoticeUser.setNewsId(oldNews.getId());
// newsNoticeUser.setUserId(u.getId());
// newsNoticeUser.setIsRead(0);
// newsNoticeUserMapper.updateById(newsNoticeUser);
// }
} else {
newsNotice.setNoticeType(Constant.EMERGENCY_TYPE);
newsNotice.setProjectId(project.getId());
newsNotice.setProjectName(project.getProjectName() + "-" + mould.getModelName());
newsNotice.setRefId(mould.getId());
newsNotice.setContent(mouldEquipment.getEquipmentNo() + "-" + Constant.EMERGENCY_ELECTRICITY_NOTICE);
newsNoticeMapper.insert(newsNotice);
for (User u : users) {
//添加通知的消息
NewsNoticeUser newsNoticeUser = new NewsNoticeUser();
newsNoticeUser.setNewsId(newsNotice.getId());
newsNoticeUser.setUserId(u.getId());
newsNoticeUserMapper.insert(newsNoticeUser);
}
}
}
if (Constant.TEMPERATURE_THRESHOLD <= mouldEquipment.getTemperature()) {
if (0 == mouldEquipment.getStage()) {
mouldEquipment.setStage(1);
} else {
mouldEquipment.setStage(3);
}
mouldEquipmentMapper.updateById(mouldEquipment);
//公众号的推送to do
userList.forEach(u -> {
try {
WechatTemplateUtil.sendEmergencyTemplateMessage(u.getOpenid(), mouldEquipment.getEquipmentName(), Constant.TEMPERATURE_TYPE, Constant.TEMPERATURE_CONTENT, token);
} catch (Exception e) {
e.printStackTrace();
}
});
//查询到参与该项目的人
List userIds = new ArrayList<>();
userIds.add(-1);
userIds.add(project.getCreatorId());
userIds.add(project.getManagerId());
List projectUsers = projectUserMapper.selectList(new QueryWrapper().eq("project_id", project.getId()));
for (ProjectUser projectUser : projectUsers) {
userIds.add(projectUser.getUserId());
}
List projectApproves = projectApproveMapper.selectList(new QueryWrapper().eq("project_id", project.getId()));
for (ProjectApprove projectApprove : projectApproves) {
userIds.add(projectApprove.getApproverId());
}
List users = userMapper.selectList(new QueryWrapper().in("id", userIds));
//查询到之前模具保养的消息
NewsNotice oldNews = newsNoticeMapper.selectOne(new QueryWrapper().eq("ref_id", mould.getId()).eq("notice_type", 2));
NewsNotice newsNotice = new NewsNotice();
if (oldNews != null) {
NewsNotice newNews = new NewsNotice();
newNews.setId(oldNews.getId());
oldNews.setIndate(LocalDateTime.now());
newsNoticeMapper.updateById(oldNews);
newsNoticeUserMapper.updateNewsNoticeUserByNewsNoticeId(oldNews.getId());
// for (User u : users) {
// //添加通知的消息
// NewsNoticeUser newsNoticeUser = new NewsNoticeUser();
// newsNoticeUser.setNewsId(oldNews.getId());
// newsNoticeUser.setUserId(u.getId());
// newsNoticeUser.setIsRead(0);
// newsNoticeUserMapper.updateById(newsNoticeUser);
// }
} else {
newsNotice.setNoticeType(Constant.EMERGENCY_TYPE);
newsNotice.setProjectId(project.getId());
newsNotice.setProjectName(project.getProjectName() + "-" + mould.getModelName());
newsNotice.setRefId(mould.getId());
newsNotice.setContent(mouldEquipment.getEquipmentNo() + "-" + Constant.EMERGENCY_TEMPERATURE_NOTICE);
newsNoticeMapper.insert(newsNotice);
for (User u : users) {
//添加通知的消息
NewsNoticeUser newsNoticeUser = new NewsNoticeUser();
newsNoticeUser.setNewsId(newsNotice.getId());
newsNoticeUser.setUserId(u.getId());
newsNoticeUserMapper.insert(newsNoticeUser);
}
}
}
}
return msg;
}
@Override
public HttpRespMsg importMouldEquipmentExcel(MultipartFile file, UserVO userVO) {
HttpRespMsg msg = new HttpRespMsg();
User user = userMapper.selectOne(new QueryWrapper().eq("head_imgurl", userVO.getToken()));
if (user != null) {
List mouldEquipments = mouldEquipmentMapper.selectList(new QueryWrapper());
try {
File f = null;
if ("".equals(file) || file.getSize() <= 0) {
file = null;
} else {
//获取输入流
InputStream ins = file.getInputStream();
//新建一个文件
f = new File(file.getOriginalFilename());
//输入流转file
inputStreamToFile(ins, f);
}
//根据文件创建工作簿
XSSFWorkbook wookbook = new XSSFWorkbook(f);
XSSFSheet sheet = wookbook.getSheetAt(0);
int s = sheet.getLastRowNum();
// 遍历当前sheet中的所有行,第一行是数据对应的字段,不是数据,
// 故从第二行开始遍历拿数据(如果有标题的话,则从第三行开始拿数据)
//有对所属公司的解析,先查出所有公司
List companies = companyMapper.selectList(new QueryWrapper<>());
List allList = new ArrayList<>();
List oldEnoList = new ArrayList<>();
for (int j = 1; j < sheet.getLastRowNum() + 1; j++) {
XSSFRow row = sheet.getRow(j);
//新建云模盒对象
MouldEquipment mouldEquipment = new MouldEquipment();
// 遍历所有的列,下面的10是excle表格里共有10列即对应了10个字段
for (int y = 0; y < 5; y++) {
XSSFCell cell = row.getCell(y);
cell.setCellType(Cell.CELL_TYPE_STRING);
//取出当前列的值
String value = cell.getStringCellValue();
//判断第几列插入数据,后面就是从列中取数据往对象里放,然后插入到数据库里
if (value == null && "".equals(value)) {
log.error("数据不可为空");
msg.setError("数据不可为空");
return msg;
} else if (y == 0) {
//云模编号
for (MouldEquipment p : mouldEquipments) {
if (value.equals(p.getEquipmentNo())) {
// msg.setError("第" + j + "行的云模盒编号:" + value + "已被占用,请修改后重新上传");
msg.setError("云模盒编号("+value+")已被占用,请修改后重新上传");
return msg;
}
}
//检查在本身的excel文件中,是否存在重复的。
if (oldEnoList.contains(value)) {
msg.setError("文档中云模盒编号("+value+")存在重复,请修改后重新上传");
return msg;
}
mouldEquipment.setEquipmentNo(value);
oldEnoList.add(value);
} else if (y == 1) {
//产品编号
mouldEquipment.setEquipmentName(value);
} else if (y == 2) {
//所属公司
if (StringUtils.isNotEmpty(value)) {
Optional comp = companies.stream().filter(c->c.getCompanyName().equals(value)).findFirst();
if (comp.isPresent()) {//设置公司id
mouldEquipment.setBelongCompanyId(comp.get().getId());
} else {
msg.setError("公司名称不存在: " + value);
}
}
} else if (y == 3) {
//使用年限
mouldEquipment.setUseLife(Integer.parseInt(value));
} else if (y == 4) {
//代理商
mouldEquipment.setAgent(value);
}
}
// mouldEquipmentMapper.insert(mouldEquipment);
allList.add(mouldEquipment);
}
//批量插入数据库
mouldEquipmentMapper.batchInsert(allList);
//用完后删除临时文件
if (!f.isDirectory()) {
f.delete();
}
} catch (Exception e) {
log.error(e.getMessage(), e);
msg.setError(e.getMessage());
return msg;
}
} else {
msg.setError("用户不存在或者未登录");
}
return msg;
}
@Override
public HttpRespMsg getEquipmentListByOldMouldAndUser(UserVO userVO) {
HttpRespMsg msg = new HttpRespMsg();
User user = userMapper.selectOne(new QueryWrapper().eq("head_imgurl", userVO.getToken()));
if (user == null) {
msg.setError("用户不存在或者未登录");
} else {
Mould mould = mouldMapper.selectById(userVO.getMouldId());
User admin = userMapper.selectById(projectMapper.selectById(mould.getProjectId()).getCreatorId());
List mouldsEquipmentIds = mouldMapper.selectList(new QueryWrapper().eq("company_id", admin.getCompanyId()).isNotNull("equipment_id")).stream().map(Mould::getEquipmentId).collect(Collectors.toList());
mouldsEquipmentIds.add(-1);
List equipmentIds = mouldEquipmentMapper.selectList(new QueryWrapper().eq("belong_company_id", admin.getCompanyId()).eq("stage", 0)).stream().map(MouldEquipment::getId).collect(Collectors.toList());
equipmentIds.removeAll(mouldsEquipmentIds);//把已经使用的设备剔除
equipmentIds.add(-1);
List list = mouldEquipmentMapper.getListByCompanyId(admin.getCompanyId(), equipmentIds);
msg.data = list;
}
return msg;
}
@Override
public HttpRespMsg changeIp(ChangeIpCommand changeIpCommand) {
HttpRespMsg msg = new HttpRespMsg();
//验证服务器ip是否满足正则表达式
if(!changeIpCommand.getIp().matches(Constant.IP_MATCH_REGULAR)){
msg.setError("服务器ip不合法");
return msg;
}
changeIpCommandMapper.insert(changeIpCommand);
return msg;
}
/**
* 输入流转file
*
* @param ins
* @param file
*/
public static void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 下行配置数据包
private String downProcessMsg(String lowPowerLimit, String hotAlarmLimit, String isUse, String freeInterval, String workInterval) {
//"23"不解析
if ("23".equals(lowPowerLimit)) {
lowPowerLimit = "24";
}
if ("23".equals(hotAlarmLimit)) {
hotAlarmLimit = "24";
}
if ("23".equals(freeInterval)) {
freeInterval = "24";
}
if ("23".equals(workInterval)) {
workInterval = "24";
}
if ("23".equals(isUse)) {
isUse = "24";
}
StringBuilder sb = new StringBuilder();
//FAAF0007021e781e50003C
sb.append("FAAF0007");
sb.append(isUse);
sb.append(workInterval);
sb.append(freeInterval);
sb.append(lowPowerLimit);
sb.append(hotAlarmLimit);
sb.append("003C");
String crcCode = CRC16Util.getCRC(sb.toString());
System.out.println("ret===>" + sb.toString());
String lastPart = (sb.toString() + crcCode).replaceAll("23", "24").replaceAll(" ", "");
System.out.println("lastPart===>" + lastPart);
return lastPart;
}
}