package com.uas.eis.serviceImpl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.uas.eis.core.TokenManager; import com.uas.eis.core.config.SeresConfig; import com.uas.eis.core.config.SpObserver; import com.uas.eis.dao.BaseDao; import com.uas.eis.dao.SqlRowList; import com.uas.eis.entity.InventoryQueryResponse; import com.uas.eis.entity.SeresStock; import com.uas.eis.entity.SeresStockDet; import com.uas.eis.service.SERESService; import com.uas.eis.utils.*; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.*; @Service public class SERESServiceImpl implements SERESService { @Autowired private SeresConfig seresConfig; @Autowired private BaseDao baseDao; private final Logger logger = LoggerFactory.getLogger(this.getClass()); // Token最大有效期 60分钟 毫秒 private static final long MAX_TOKEN_VALID_MS = 60L * 60 * 1000; // 提前1分钟刷新Token(毫秒) private static final long REFRESH_ADVANCE_MS = 60L * 1000; private static final String seresTokenKey = "SERES_TOKEN" ; static final String errLogSql="insert into Seres_Stock_Alert_errlog(ID_,CODE_,DATE_,MESSAGE_,DATA_)values(?,?,sysdate,?,?)"; /** * 获取有效Token,自动判断是否刷新 */ public synchronized String getValidToken() throws IOException { String accessToken = TokenManager.getToken(seresTokenKey,REFRESH_ADVANCE_MS); long nowMs = System.currentTimeMillis(); // 无token 或 距离过期不足1分钟,重新拉取 if (accessToken == null ) { SqlRowList rs = baseDao.queryForRowSet("select access_token,EXP_ from (select * from AW_ZHJK.SERES_TOKEN_LOG where EXP_>"+(nowMs+REFRESH_ADVANCE_MS)+" order by EXP_ desc) where rownum=1"); if(rs.next()){ String token=rs.getString("access_token"); int exp=rs.getInt("exp_"); logger.info("从数据库获取上次有效token {}",token); accessToken=token.toString(); TokenManager.setToken(seresTokenKey,accessToken,exp); }else{ logger.info("token 为空重新获取"); accessToken=refreshToken(); } } return accessToken; } private String refreshToken() throws IOException { String accessToken =""; String tokenUrl = seresConfig.getUrl() + "/aito/DIS/COMM_GET_JWT_TOKEN/1.0.0"; String clientId=seresConfig.getClientId(); String clientSecret=seresConfig.getClientSecret(); long nowMs = System.currentTimeMillis(); long expTs = nowMs + MAX_TOKEN_VALID_MS; // 请求体 JSONObject reqBody = new JSONObject(); reqBody.put("grant_type", "client_credentials"); reqBody.put("client_id", clientId); reqBody.put("client_secret", clientSecret); reqBody.put("exp", expTs); // 发送POST CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(tokenUrl); httpPost.setHeader("Content-Type", "application/json"); StringEntity entity = new StringEntity(reqBody.toString(), "UTF-8"); httpPost.setEntity(entity); logger.info("reqBody {}", JSON.toJSONString(reqBody)); try (CloseableHttpResponse response = httpClient.execute(httpPost)) { String respJson = EntityUtils.toString(response.getEntity(), "UTF-8"); JSONObject respObj = JSON.parseObject(respJson); if (!respObj.containsKey("access_token")) { throw new RuntimeException("获取Token失败,响应:" + respJson); } accessToken = respObj.getString("access_token"); TokenManager.setToken(seresTokenKey,accessToken,expTs); logger.info("token {}",accessToken); baseDao.execute("insert into AW_ZHJK.SERES_TOKEN_LOG(access_token,exp_) VALUES('"+accessToken+"',"+expTs+")"); System.out.println("Token刷新成功,有效期:" + respObj.get("expires_in") + "秒"); } finally { httpClient.close(); } return accessToken; } private Map querySERESInv(String token,String param) throws IOException { logger.info("querySERESInv-token {}" + token); logger.info("querySERESInv-param {}" + param); Map modelMap = new HashMap(); String apiPath="/aito/DIS/INV_STOCK_STS/1.0.0"; String fullUrl = seresConfig.getUrl() + apiPath; logger.info("fullUrl {}",fullUrl); logger.info("Authorization {}","Bearer " + token); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(fullUrl); // 鉴权头 httpPost.setHeader("Authorization", "Bearer " + token); httpPost.setHeader("Content-Type", "application/json"); httpPost.setHeader("SupplierCode", seresConfig.getClientCode()); Map paramMap = BaseUtil.parseFormStoreToMap(param); System.out.println(paramMap.get("page")); System.out.println(paramMap.get("pageSize")); System.out.println(paramMap.get("MaterialCode")); String materialCode=(StringUtil.hasText(paramMap.get("MaterialCode")))?paramMap.get("MaterialCode").toString():""; String factoryCode=(StringUtil.hasText(paramMap.get("FactoryCode")))?paramMap.get("FactoryCode").toString():""; int page= (StringUtil.hasText(paramMap.get("page")))?Integer.parseInt(paramMap.get("page").toString()):1; int pageSize= (StringUtil.hasText(paramMap.get("pageSize")))?Integer.parseInt(paramMap.get("pageSize").toString()):500; if(pageSize>500){ pageSize=500; } JSONObject reqBody = new JSONObject(); //供应商编码 reqBody.put("SupplierCode", seresConfig.getClientCode()); //工厂编码 reqBody.put("FactoryCode",factoryCode); //物料编码 reqBody.put("MaterialCode", materialCode); //页码 reqBody.put("Skip", page); //分页大小 reqBody.put("Take", pageSize); if (reqBody != null) { StringEntity entity = new StringEntity(JSON.toJSONString(reqBody), "UTF-8"); httpPost.setEntity(entity); logger.info("reqBody {}", JSON.toJSONString(reqBody)); } try (CloseableHttpResponse response = httpClient.execute(httpPost)) { String result = EntityUtils.toString(response.getEntity(), "UTF-8"); logger.info("result {}",result); if(StringUtil.hasText(result)){ InventoryQueryResponse queryRes=FlexJsonUtil.fromJson(result, InventoryQueryResponse.class); if(queryRes.getCode().equals("0")){//成功 modelMap.put("message",queryRes.getMessage()); modelMap.put("count",queryRes.getData().getTotalCount()); modelMap.put("data",queryRes.getData().getList()); modelMap.put("success", true); }else{ modelMap.put("message",queryRes.getMessage()); } } } finally { httpClient.close(); return modelMap; } } @Override public Map getStock( String param) throws IOException { logger.info("action : getStock"); String token = getValidToken(); Map modelMap = querySERESInv(token,param); return modelMap; } @Override public Map getERPStock(String param){ Map modelMap = new HashMap(); SpObserver.putSp("AW_ZHJK"); List data=new ArrayList(); String con=""; String MaterialCode_Q=""; if(StringUtil.hasText(param)){ Map map = BaseUtil.parseFormStoreToMap(param); if(StringUtil.hasText(map.get("MaterialCode"))){ MaterialCode_Q=map.get("MaterialCode").toString(); } } if(StringUtil.hasText(MaterialCode_Q)){ con="MaterialCode='"+MaterialCode_Q+"'"; }else{ con="1=1"; } SqlRowList rs = baseDao.queryForRowSet("select MaterialCode,MaterialName from ZHJK_SERES_STOCK_VIEW where "+con+" group by MaterialCode,MaterialName order by MaterialCode"); int n = 1; if(rs.size()>0){ while (rs.next()){ SeresStock seresStock=new SeresStock(); seresStock.setSerialNumber(n); n++; seresStock.setSupplierCode(seresConfig.getClientCode()); seresStock.setSupplierName(seresConfig.getClientName()); seresStock.setMaterialCode(rs.getString("MaterialCode")); seresStock.setMaterialName(rs.getString("MaterialName")); String prcon="MaterialCode='"+rs.getString("MaterialCode")+"'"; List det=new ArrayList(); SqlRowList rs_det = baseDao.queryForRowSet("select StockCode,StockName,StockAddress,FGQualifiedStock,FGNonQualifiedStock from ZHJK_SERES_STOCK_VIEW where "+prcon+" order by StockCode"); while (rs_det.next()){ SeresStockDet detInfo=new SeresStockDet(); detInfo.setStockCode(rs_det.getString("StockCode")); detInfo.setStockName(rs_det.getString("StockName")); detInfo.setStockAddress(rs_det.getString("StockAddress")); detInfo.setFGQualifiedStock(rs_det.getGeneralDouble("FGQualifiedStock")); detInfo.setFGNonQualifiedStock(rs_det.getGeneralDouble("FGNonQualifiedStock")); det.add(detInfo); } seresStock.setStockList(det); data.add(seresStock); } String resp=JSONArray.toJSONString(data); System.out.println(resp); modelMap.put("code",0); modelMap.put("message","成功"); modelMap.put("data",data); } else if (StringUtil.hasText(MaterialCode_Q)) { //物料号不存在 modelMap.put("code",1); modelMap.put("message","物料号不存在"); modelMap.put("data",data); System.out.println("物料号不存在"); }else{ //未配置对照关系 modelMap.put("code",1); modelMap.put("message","未配置对照关系"); modelMap.put("data",data); System.out.println("未配置对照关系"); } return modelMap; } @Override public String getToken() throws IOException { String token=getValidToken(); logger.info("当前token {}",token); return token; } @Override public Map saveAlert(String data) { Map modelMap = new HashMap(); List> dets = BaseUtil.parseGridStoreToMaps(data); Object id = baseDao.getSeqId("SERES_STOCK_ALERT_SEQ"); String code = baseDao.sGetMaxNumber("Seres_Stock_Alert", 2); baseDao.execute("insert into SERES_STOCK_ALERT(Sta_id,sta_code,sta_recorddate) values("+id+",'"+code+"',sysdate)"); for (Map det : dets) { det.put("stad_id",baseDao.getSeqId("SERES_STOCK_ALERT_DET_SEQ")); det.put("stad_staid",id); } try{ List gridSql = SqlUtil.getInsertSqlbyGridStore(dets, "SERES_STOCK_ALERT_DET"); baseDao.execute(gridSql); baseDao.execute("update Seres_Stock_Alert set sta_dockStatus='成功' where Sta_id="+id); modelMap.put("code",0); modelMap.put("message","接收成功"); modelMap.put("data",""); }catch (Exception e){ Object errid = baseDao.getSeqId("SERES_ERRLOG_SEQ"); baseDao.execute("update Seres_Stock_Alert set sta_dockStatus='失败' where Sta_id="+id); baseDao.execute(errLogSql, new Object[]{errid,code,e.getMessage(),data}); modelMap.put("code",1); modelMap.put("message","接收失败"); modelMap.put("data",""); } return modelMap; } @Override public Map test(String token) throws Exception { logger.info("action :testGetStock"); logger.info("token {}",token); Map modelMap = new HashMap(); String apiPath="/aito/DIS/INV_STOCK_STS/1.0.0"; String fullUrl = seresConfig.getUrl() + apiPath; logger.info("fullUrl {}",fullUrl); logger.info("Authorization {}","Bearer " + token); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(fullUrl); // 鉴权头 httpPost.setHeader("Authorization", "Bearer " + token); httpPost.setHeader("Content-Type", "application/json"); httpPost.setHeader("SupplierCode", seresConfig.getClientCode()); logger.info("SupplierCode {}", seresConfig.getClientCode()); JSONObject reqBody = new JSONObject(); //供应商编码 reqBody.put("SupplierCode", seresConfig.getClientCode()); //工厂编码 reqBody.put("FactoryCode", ""); //物料编码 reqBody.put("MaterialCode", ""); //页码 reqBody.put("Skip", 1); //分页大小 reqBody.put("Take", 500); if (reqBody != null) { StringEntity entity = new StringEntity(JSON.toJSONString(reqBody), "UTF-8"); httpPost.setEntity(entity); logger.info("reqBody {}", JSON.toJSONString(reqBody)); } try (CloseableHttpResponse response = httpClient.execute(httpPost)) { String respStr = EntityUtils.toString(response.getEntity(), "UTF-8"); logger.info("test respStr {}", respStr); return JSON.parseObject(respStr); }catch (Exception e){ logger.info("Exception {}",e.getMessage()); e.printStackTrace(); } finally { httpClient.close(); return modelMap; } } @Override public void testToken(String token) throws IOException { logger.info("testToken token {}", token); String fullUrl = "https://dis-api-test.seres.cn/aito/public/API_zsgsw/1.0.0"; logger.info("testToken fullUrl {}", fullUrl); logger.info("testToken Authorization {}", "Bearer " + token); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(fullUrl); // 鉴权头 httpPost.setHeader("Authorization", "Bearer " + token); httpPost.setHeader("Content-Type", "application/json"); try (CloseableHttpResponse response = httpClient.execute(httpPost)) { HttpUtil.Response r= HttpUtil.Response.getResponse(response); //String respStr = EntityUtils.toString(response.getEntity(), "UTF-8"); logger.info("testToken resp-code {}", r.getStatusCode()); logger.info("testToken ResponseText resp {}", r.getResponseText()); } catch (Exception e) { logger.info("Exception {}",e.getMessage()); e.printStackTrace(); } finally { httpClient.close(); } } @Override public Map testGetStock(String token,String param) throws Exception { Map modelMap = querySERESInv(token,param); return modelMap; } @Override public Map testGetStockData(String param) throws Exception { System.out.println(param); Map paramMap = BaseUtil.parseFormStoreToMap(param); System.out.println(paramMap.get("page")); System.out.println(paramMap.get("pageSize")); System.out.println(paramMap.get("MaterialCode")); Map modelMap = new HashMap(); String res="{\"code\":\"0\",\"message\":\"Success\",\"data\":{\"totalCount\":8,\"list\":[{\"SerialNumber\":1,\"FactoryCode\":\"1003\",\"SupplierCode\":\"0000002446\",\"SupplierName\":\"深圳市英唐智慧健康科技有限公司\",\"MaterialCode\":\"8100108-RW01\",\"MaterialName\":\"空调滤芯\",\"RDCLOCQualifiedStock\":0,\"InPlantQualifiedStock\":0,\"LineSideQualifiedStock\":0,\"InPlantNonQualifiedStock\":0,\"VMIQualifiedStock\":0,\"VMINonQualifiedStock\":0,\"PendingInspectionStock\":0,\"FrozenStock\":0,\"ContainerYardStock\":0,\"PRTransitStock\":0,\"POTransitStock\":2792,\"POITransitStock\":0,\"AvailableStock\":0,\"Attribute1\":\"\",\"Attribute2\":\"\",\"Attribute3\":\"\",\"Attribute4\":\"\",\"Attribute5\":\"\"},{\"SerialNumber\":1,\"FactoryCode\":\"1003\",\"SupplierCode\":\"0000002446\",\"SupplierName\":\"深圳市英唐智慧健康科技有限公司\",\"MaterialCode\":\"8100290-RL02\",\"MaterialName\":\"UVC光触媒杀菌模块\",\"RDCLOCQualifiedStock\":0,\"InPlantQualifiedStock\":0,\"LineSideQualifiedStock\":0,\"InPlantNonQualifiedStock\":0,\"VMIQualifiedStock\":1481,\"VMINonQualifiedStock\":0,\"PendingInspectionStock\":0,\"FrozenStock\":0,\"ContainerYardStock\":0,\"PRTransitStock\":0,\"POTransitStock\":0,\"POITransitStock\":0,\"AvailableStock\":1481,\"Attribute1\":\"\",\"Attribute2\":\"\",\"Attribute3\":\"\",\"Attribute4\":\"\",\"Attribute5\":\"\"},{\"SerialNumber\":1,\"FactoryCode\":\"1003\",\"SupplierCode\":\"0000002446\",\"SupplierName\":\"深圳市英唐智慧健康科技有限公司\",\"MaterialCode\":\"8100108-RL03\",\"MaterialName\":\"空调滤芯\",\"RDCLOCQualifiedStock\":0,\"InPlantQualifiedStock\":0,\"LineSideQualifiedStock\":0,\"InPlantNonQualifiedStock\":0,\"VMIQualifiedStock\":1634,\"VMINonQualifiedStock\":0,\"PendingInspectionStock\":0,\"FrozenStock\":0,\"ContainerYardStock\":0,\"PRTransitStock\":0,\"POTransitStock\":0,\"POITransitStock\":0,\"AvailableStock\":1634,\"Attribute1\":\"\",\"Attribute2\":\"\",\"Attribute3\":\"\",\"Attribute4\":\"\",\"Attribute5\":\"\"},{\"SerialNumber\":1,\"FactoryCode\":\"1003\",\"SupplierCode\":\"0000002446\",\"SupplierName\":\"深圳市英唐智慧健康科技有限公��\",\"MaterialCode\":\"8100290-RL01\",\"MaterialName\":\"UVC光触媒杀菌模块\",\"RDCLOCQualifiedStock\":500,\"InPlantQualifiedStock\":0,\"LineSideQualifiedStock\":0,\"InPlantNonQualifiedStock\":0,\"VMIQualifiedStock\":0,\"VMINonQualifiedStock\":0,\"PendingInspectionStock\":0,\"FrozenStock\":0,\"ContainerYardStock\":0,\"PRTransitStock\":0,\"POTransitStock\":1356,\"POITransitStock\":0,\"AvailableStock\":500,\"Attribute1\":\"\",\"Attribute2\":\"\",\"Attribute3\":\"\",\"Attribute4\":\"\",\"Attribute5\":\"\"},{\"SerialNumber\":1,\"FactoryCode\":\"1003\",\"SupplierCode\":\"0000002446\",\"SupplierName\":\"深圳市英唐智慧健康科技有限公司\",\"MaterialCode\":\"8100290-RW01\",\"MaterialName\":\"UVC光触媒杀菌模块\",\"RDCLOCQualifiedStock\":0,\"InPlantQualifiedStock\":0,\"LineSideQualifiedStock\":0,\"InPlantNonQualifiedStock\":0,\"VMIQualifiedStock\":528,\"VMINonQualifiedStock\":0,\"PendingInspectionStock\":0,\"FrozenStock\":0,\"ContainerYardStock\":0,\"PRTransitStock\":0,\"POTransitStock\":2811,\"POITransitStock\":0,\"AvailableStock\":528,\"Attribute1\":\"\",\"Attribute2\":\"\",\"Attribute3\":\"\",\"Attribute4\":\"\",\"Attribute5\":\"\"},{\"SerialNumber\":1,\"FactoryCode\":\"1003\",\"SupplierCode\":\"0000002446\",\"SupplierName\":\"深圳市英唐智慧健康科技有限公司\",\"MaterialCode\":\"8100108-RQ01\",\"MaterialName\":\"空调滤芯\",\"RDCLOCQualifiedStock\":3787,\"InPlantQualifiedStock\":0,\"LineSideQualifiedStock\":0,\"InPlantNonQualifiedStock\":0,\"VMIQualifiedStock\":0,\"VMINonQualifiedStock\":0,\"PendingInspectionStock\":0,\"FrozenStock\":0,\"ContainerYardStock\":0,\"PRTransitStock\":0,\"POTransitStock\":528,\"POITransitStock\":0,\"AvailableStock\":3787,\"Attribute1\":\"\",\"Attribute2\":\"\",\"Attribute3\":\"\",\"Attribute4\":\"\",\"Attribute5\":\"\"},{\"SerialNumber\":1,\"FactoryCode\":\"1003\",\"SupplierCode\":\"0000002446\",\"SupplierName\":\"深圳市英唐智慧健康科技有限公司\",\"MaterialCode\":\"8100108-RV01\",\"MaterialName\":\"空调滤芯\",\"RDCLOCQualifiedStock\":0,\"InPlantQualifiedStock\":0,\"LineSideQualifiedStock\":0,\"InPlantNonQualifiedStock\":0,\"VMIQualifiedStock\":767,\"VMINonQualifiedStock\":0,\"PendingInspectionStock\":0,\"FrozenStock\":0,\"ContainerYardStock\":0,\"PRTransitStock\":0,\"POTransitStock\":0,\"POITransitStock\":0,\"AvailableStock\":767,\"Attribute1\":\"\",\"Attribute2\":\"\",\"Attribute3\":\"\",\"Attribute4\":\"\",\"Attribute5\":\"\"},{\"SerialNumber\":1,\"FactoryCode\":\"2290\",\"SupplierCode\":\"0000002446\",\"SupplierName\":\"深圳市英唐智慧健康科技有限公司\",\"MaterialCode\":\"8100108-RV01\",\"MaterialName\":\"空调滤芯\",\"RDCLOCQualifiedStock\":0,\"InPlantQualifiedStock\":0,\"LineSideQualifiedStock\":0,\"InPlantNonQualifiedStock\":0,\"VMIQualifiedStock\":0,\"VMINonQualifiedStock\":0,\"PendingInspectionStock\":0,\"FrozenStock\":0,\"ContainerYardStock\":0,\"PRTransitStock\":0,\"POTransitStock\":4308,\"POITransitStock\":0,\"AvailableStock\":0,\"Attribute1\":\"\",\"Attribute2\":\"\",\"Attribute3\":\"\",\"Attribute4\":\"\",\"Attribute5\":\"\"}]}}"; InventoryQueryResponse queryRes=FlexJsonUtil.fromJson(res, InventoryQueryResponse.class); System.out.println(queryRes.getCode()); System.out.println(FlexJsonUtil.toJson(queryRes.getData().getList())); modelMap.put("message",queryRes.getMessage()); modelMap.put("count",queryRes.getData().getTotalCount()); modelMap.put("data",queryRes.getData().getList()); return modelMap; } }