package com.cdf.service.impl; import cn.hutool.core.io.FileUtil; import cn.hutool.json.JSONUtil; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.cdf.common.ResultCode; import com.cdf.entity.*; import com.cdf.exception.BusinessException; import com.cdf.httpClient.client.CdfClient; import com.cdf.httpClient.client.CdfHKClient; import com.cdf.httpClient.client.FdkkClient; import com.cdf.httpClient.request.FdkkHotData; import com.cdf.httpClient.request.FdkkHotRequest; import com.cdf.httpClient.request.FdkkUploadRequest; import com.cdf.httpClient.request.SceneRequest; import com.cdf.httpClient.response.FdkkResponse; import com.cdf.httpClient.response.cdf.*; import com.cdf.response.BrandApiVo; import com.cdf.service.*; import com.cdf.util.*; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; @Service @Slf4j public class FdkkSceneEditService { @Resource private UploadToFdkkOssUtil uploadToFdkkOssUtil; @Resource private UploadToCdfOssUtil uploadToCdfOssUtil; @Value("${fdkk.hot-path}") private String hotPath; @Value("${fdkk.hot-cdf-path}") private String hotCdfPath; @Value("${fdkk.hot-local-path}") private String hotLocalPath; @Value("${fdkk.qr-code-url}") private String qrCodeUrl; @Resource private FdkkClient fdkkClient; @Resource private CdfHKClient cdfHKClient; @Autowired private IHotRelationService hotRelationService; @Autowired FdkkSceneService fdkkSceneService; @Autowired CdfRolePermService cdfRolePermService; @Autowired IProductHkService productHkService; @Autowired IFdkkUserService fdkkUserService; @Autowired IProductSourceService productSourceService; @Autowired IBrandService brandService; @Autowired IHotRecommendService hotRecommendService; public JSONObject getAuth(String num, String token) { String fdkkToken = fdkkSceneService.getFdkkToken(token); HashMap map = new HashMap<>(); map.put("num",num); JSONObject auth = fdkkClient.getAuth(map, fdkkToken); Integer code = auth.getInteger("code"); if(code == 0){ NumRegion numRegion = fdkkUserService.getRegionByNum(num); JSONObject data = auth.getJSONObject("data"); data.put("cdfRegionData",numRegion); } return auth; } public FdkkResponse saveTag(FdkkHotRequest fdkkHotRequest, String token) { FdkkResponse fdkkResponse = fdkkClient.hotSave(fdkkHotRequest,fdkkSceneService.getFdkkToken(token)); if(fdkkResponse.getCode() != 0){ throw new BusinessException(fdkkResponse.getCode(),fdkkResponse.getMsg()); } List hotDataList = fdkkHotRequest.getHotDataList(); for (FdkkHotData fdkkHotData : hotDataList) { List relationIds = fdkkHotData.getRelationIds(); String sid = fdkkHotData.getSid(); Integer type = fdkkHotData.getHotType(); if(type == null){ continue; } HotRelation hotRelation = hotRelationService.getById(sid); boolean update = true; if(hotRelation == null){ hotRelation = new HotRelation(); update = false; } hotRelation.setHotId(sid); hotRelation.setHotType(type); if(relationIds !=null && relationIds.size() >0){ hotRelation.setRelationIds(JSONArray.toJSONString(relationIds)); }else { hotRelation.setRelationIds(null); } hotRelation.setNum(fdkkHotRequest.getNum()); hotRelation.setContent(fdkkHotData.getHotContent()); hotRelation.setProductSourceId(fdkkHotData.getProductSourceId()); hotRelation.setBrandId(fdkkHotData.getBrandId()); if(update){ hotRelationService.updateById(hotRelation); }else { hotRelationService.save(hotRelation); } } return fdkkResponse; } public void deleteTag(FdkkHotRequest fdkkHotRequest, String token) { FdkkResponse fdkkResponse = fdkkClient.hotDelete(fdkkHotRequest,fdkkSceneService.getFdkkToken(token)); if(fdkkResponse.getCode() !=0){ throw new BusinessException(fdkkResponse.getCode(),fdkkResponse.getMsg()); } hotRelationService.removeByIds(fdkkHotRequest.getSidList()); } public JSONObject getTagList(String num, String token,String language) { FdkkResponse fdkkResponse = fdkkClient.hotList(new SceneRequest(num), fdkkSceneService.getFdkkToken(token)); if(fdkkResponse.getCode() !=0){ throw new BusinessException(fdkkResponse.getCode(),fdkkResponse.getMsg()); } NumRegion numRegion = fdkkUserService.getRegionByNum(num); JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(fdkkResponse.getData())); JSONArray tags =jsonObject.getJSONArray("tags"); jsonObject.put("tags",getProductByJsonObj(tags,numRegion.getRegion(),language)); return jsonObject; } public JSONArray getHotJson(String num,String pType,String language) { String data = uploadToFdkkOssUtil.getObjectContent(String.format(hotPath, num) ); if(StringUtils.isBlank(data)){ throw new BusinessException(ResultCode.NOT_RECORD); } JSONArray tags = JSONObject.parseArray(data); return getProductByJsonObj(tags,pType,language); } public Boolean cdfHasHotJson(String num) { return uploadToCdfOssUtil.existKey(String.format(hotCdfPath, num)); } public JSONArray getCdfHotJson(String num) { String data = uploadToCdfOssUtil.getObjectContent(String.format(hotCdfPath, num)); if(StringUtils.isBlank(data)){ data = uploadToFdkkOssUtil.getObjectContent( String.format(hotPath, num)); } if(StringUtils.isBlank(data)){ throw new BusinessException(ResultCode.NOT_RECORD); } return JSONObject.parseArray(data); } public void publicScene(FdkkHotRequest fdkkHotRequest, String token) throws Exception { FdkkResponse fdkkResponse = fdkkClient.scenePublicScene(new SceneRequest(fdkkHotRequest.getNum()),fdkkSceneService.getFdkkToken(token)); if(fdkkResponse.getCode() !=0){ throw new BusinessException(fdkkResponse.getCode(),fdkkResponse.getMsg()); } NumRegion numRegion = fdkkUserService.getRegionByNum(fdkkHotRequest.getNum()); writeHotJson(fdkkHotRequest.getNum(),numRegion.getRegion()); String res1 = "scene_view_data/%s/images/vision.modeldata"; String res2 = "scene_view_data/%s/images/vision2.modeldata"; updateModelData(fdkkHotRequest.getNum(),res1); updateModelData(fdkkHotRequest.getNum(),res2); String sell1 = "aws s3 sync s3://4dkankan/scene_view_data/"+fdkkHotRequest.getNum()+"/user " + " s3://4dage-moderate2/scene_view_data/"+fdkkHotRequest.getNum()+"/user --profile user1"; log.info("执行脚本:{}",sell1); ReadCmdLine.callShellByExec(sell1); } private void updateModelData(String num,String res) { String localPath = "/home/cdf/"+String.format(res, num); String s3PathKey = String.format(res, num); uploadToFdkkOssUtil.downFromS3(s3PathKey,localPath); uploadToCdfOssUtil.upload(localPath,s3PathKey); } public void writeHotJson(String num,String pType) { try { if(pType.equals("HK")){ writeHotJsonHk(num,"eshop_en"); writeHotJsonHk(num,"eshop_zh"); writeHotJsonHk(num,"eshop_cn"); return; } JSONArray hotJson = getHotJson(num,pType,"all"); String path = String.format(hotLocalPath,num)+"/"+"hot.json"; String json = JSONUtil.toJsonStr(hotJson); FileUtils.writeFile(path,json ); uploadToCdfOssUtil.upload(path,String.format(hotCdfPath, num)); }catch (Exception e){ log.error("writeHotJson",e); } } public void writeHotJsonHk(String num,String lang){ try { JSONArray hotJson = getHotJson(num,"HK",lang); String name = "hot_" +lang +".json"; String path = String.format(hotLocalPath,num)+"/"+name; String json = JSONUtil.toJsonStr(hotJson); FileUtils.writeFile(path,json ); uploadToCdfOssUtil.upload(path,String.format(hotCdfPath, num).replace("hot.json",name)); if("eshop_zh".equals(lang)){ uploadToCdfOssUtil.upload(path,String.format(hotCdfPath, num)); } }catch (Exception e){ e.printStackTrace(); } } public FdkkResponse uploadFiles(FdkkUploadRequest fdkkUploadRequest, MultipartFile[] files, String token) throws IOException { List multipartFiles = new ArrayList<>(); if(StringUtils.isNotBlank(fdkkUploadRequest.getBase64())){ MultipartFile file = BASE64DecodedMultipartFile.base64ToMultipart(fdkkUploadRequest.getBase64()); multipartFiles.add(file); } if(files.length >0){ multipartFiles.addAll(Arrays.asList(files)); } List paths = new ArrayList<>(); for (MultipartFile file : multipartFiles) { if(file !=null && file.getSize() >0){ String fileName = file.getOriginalFilename(); assert fileName != null; String newFilePath = String.format(hotLocalPath,fdkkUploadRequest.getNum()) + "/"+fileName; File newFiles = new File(newFilePath ); if (!newFiles.getParentFile().exists()) { newFiles.getParentFile().mkdirs(); } if (!newFiles.exists()) { newFiles.createNewFile(); } file.transferTo(newFiles); String path = newFiles.getPath(); paths.add(path); } } fdkkUploadRequest.setBase64(null); FdkkResponse fdkkResponse = fdkkClient.uploadFiles(fdkkUploadRequest,paths,fdkkSceneService.getFdkkToken(token)); if(fdkkResponse.getCode() !=0){ throw new BusinessException(fdkkResponse.getCode(),fdkkResponse.getMsg()); } return fdkkResponse; } private JSONArray getProductByJsonObj(JSONArray tags,String pType,String language){ HashMap resultMap = new HashMap<>(); //sid, productId array HashMap productMap = new HashMap<>(); //productId cdf JSONArray requestArray = new JSONArray(); //productId all array List sidsList = new ArrayList<>(); HashMap hotRelationMap = new HashMap<>(); HashMap hotRecommendHashMap = new HashMap<>(); HashMap productSourceMap = new HashMap<>(); HashMap brandMap = new HashMap<>(); for (Object obj : tags) { JSONObject tag = (JSONObject) obj; String sid = tag.getString("sid"); sidsList.add(sid); } List productSources = new ArrayList<>(); if(sidsList.size() >0){ List hotRelations = hotRelationService.listByIds(sidsList); //批量查询熱點 for (HotRelation hotRelation : hotRelations) { hotRelationMap.put(hotRelation.getHotId(),hotRelation); } hotRecommendHashMap = hotRecommendService.getMapBySids(sidsList); Set productSourceIds = hotRelations.stream().map(HotRelation::getProductSourceId).collect(Collectors.toSet()); if(productSourceIds.size() >0){ productSources = productSourceService.listByIds(productSourceIds); for (ProductSource productSource : productSources) { productSourceMap.put(productSource.getId(),productSource); } } Set brandIds = new HashSet<>(); for (HotRelation hotRelation : hotRelations) { if(StringUtils.isNotBlank(hotRelation.getBrandId())){ brandIds.add(hotRelation.getBrandId()); } } brandMap = brandService.getMapByIds(brandIds); } for (Object obj : tags) { JSONObject tag = (JSONObject) obj; String sid = tag.getString("sid"); HotRecommend recommend = hotRecommendHashMap.get(sid); if(recommend != null){ tag.put("recommendSelection",recommend.getRecommendSelection()); tag.put("recommendBrand",recommend.getRecommendBrand()); } HotRelation hotRelation = hotRelationMap.get(sid); if(hotRelation == null){ continue; } if(hotRelation.getBrandId() != null){ tag.put("brand",brandMap.get(hotRelation.getBrandId())); } tag.put("hotType",hotRelation.getHotType()); //0商品,1优惠劵,2第三方跳转,3瀑布流 ,場景关联 if(hotRelation.getHotType() == null){ continue; } if(hotRelation.getHotType() == 1 || hotRelation.getHotType() == 2){ tag.put("hotContent", hotRelation.getContent()); continue; } String relationIds = hotRelation.getRelationIds(); if(StringUtils.isBlank(relationIds)){ continue; } JSONArray jsonArray = JSONObject.parseArray(relationIds); if(jsonArray == null || jsonArray.size() <=0){ continue; } if(hotRelation.getProductSourceId() != null){ tag.put("productSource",productSourceMap.get(hotRelation.getProductSourceId())); } resultMap.put(sid,jsonArray); requestArray.addAll(jsonArray); } if(requestArray.size() <=0){ return tags; } for (ProductSource productSource : productSources) { if(productSource.getMchType() == 1){ List list = productHkService.getListByIds(requestArray); List convert = productHkService.convert(list, language); for (CdfProduct cdfProduct : convert) { productMap.put(productSource.getId() + "_"+ cdfProduct.getId(),cdfProduct); } } if(productSource.getMchType() == 0){ CdfProductListByIdsRequest param = new CdfProductListByIdsRequest(requestArray); CdfProductListByIdsVo vos = cdfHKClient.getProductListByIds(productSource.getCdfHost(),productSource.getCdfMchId(),param); if(vos.getProductCardList()!=null && vos.getProductCardList().size() >0){ for (CdfProduct cdfProduct : vos.getProductCardList()) { productMap.put(productSource.getId() + "_"+ cdfProduct.getId(),cdfProduct); } } } } for (Object obj : tags) { JSONObject tag = (JSONObject) obj; String sid = tag.getString("sid"); JSONObject productSource = tag.getJSONObject("productSource"); String keyPre = ""; if(productSource != null){ Integer id = productSource.getInteger("id"); keyPre = id +"_"; } JSONArray jsonArray = resultMap.get(sid); if(jsonArray==null || jsonArray.size()<=0){ continue; } List cdfProductList = new ArrayList<>(); for (Object o : jsonArray) { String key = keyPre + o.toString(); if(productMap.get( key)!=null){ cdfProductList.add(productMap.get( key)); } } if(cdfProductList.size() >0){ tag.put("products",cdfProductList); } } return tags; } public void downQrCode(HttpServletRequest request, HttpServletResponse response, String num) { String longUrl; try { longUrl = qrCodeUrl +num; // 生成二维码 BitMatrix qRcodeImg = QRCodeUtil.generateQRCodeStream(longUrl, response); // 将二维码输出到页面中 MatrixToImageWriter.writeToStream(qRcodeImg, "png", response.getOutputStream()); } catch (Exception e) { e.printStackTrace(); } } public String getHotTitle(List hotDataList) { try { StringBuilder title = new StringBuilder(); for (FdkkHotData fdkkHotData : hotDataList) { String hotData = fdkkHotData.getHotData(); String s1 = StringEscapeUtils.unescapeJava(hotData); JSONObject jsonObject = JSONObject.parseObject(s1); title.append(jsonObject.getString("title")); title.append(","); } if(title.length()>0 && title.toString().contains(",")){ title.delete(title.lastIndexOf(",") ,title.length() ); } return title.toString(); }catch (Exception e){ e.printStackTrace(); } return ""; } public String getSceneName(String num) { try { HashMap map = new HashMap<>(); map.put("num",num); JSONObject info = fdkkClient.getInfo(map); return info.getJSONObject("data").getString("title"); }catch (Exception e){ e.printStackTrace(); } return num; } }