diff --git a/src/main/java/com/ai/da/common/utils/RedisUtil.java b/src/main/java/com/ai/da/common/utils/RedisUtil.java index 40f8ac09..e65366ee 100644 --- a/src/main/java/com/ai/da/common/utils/RedisUtil.java +++ b/src/main/java/com/ai/da/common/utils/RedisUtil.java @@ -494,6 +494,7 @@ public class RedisUtil { return maxLikeCount != null ? Integer.parseInt(maxLikeCount) : 0; } + public final static String IMAGE_SEGMENTATION = "ImageSegmentation:"; public final static String STRIPE_EXCEPTION_LOG = "StripeException:"; diff --git a/src/main/java/com/ai/da/controller/ConvenientInquiryController.java b/src/main/java/com/ai/da/controller/ConvenientInquiryController.java index 95014eec..9925474f 100644 --- a/src/main/java/com/ai/da/controller/ConvenientInquiryController.java +++ b/src/main/java/com/ai/da/controller/ConvenientInquiryController.java @@ -7,9 +7,7 @@ import com.ai.da.common.response.Response; import com.ai.da.mapper.primary.DesignMapper; import com.ai.da.mapper.primary.entity.Account; import com.ai.da.mapper.primary.entity.TrialOrder; -import com.ai.da.model.dto.AccountAddDTO; -import com.ai.da.model.dto.QueryPaymentInfoDTO; -import com.ai.da.model.dto.UserDesignStatisticDTO; +import com.ai.da.model.dto.*; import com.ai.da.model.vo.PaymentInfoVO; import com.ai.da.model.vo.QuestionnaireFeedbackVO; import com.ai.da.model.vo.QuestionnaireVO; @@ -17,7 +15,6 @@ import com.ai.da.model.vo.QueryUserConditionsVO; import com.ai.da.service.AccountService; import com.ai.da.service.ConvenientInquiryService; import com.baomidou.mybatisplus.core.metadata.IPage; -import io.netty.util.internal.StringUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @@ -63,26 +60,7 @@ public class ConvenientInquiryController { @GetMapping("/getDesignStatistic") public Response> getDesignStatistic(@RequestParam(required = false) String startTime, @RequestParam(required = false) String endTime, @RequestParam(required = false) List ids, @RequestParam(required = false) String email) { - Long accountId = UserContext.getUserHolder().getId(); - String userEmail = accountService.getById(accountId).getUserEmail(); - if (accountId.equals(31L) || accountId.equals(87L) || accountId.equals(83L) - || accountId.equals(6L) || accountId.equals(4L) || accountId.equals(73L) - || userEmail.equals("joho8228@hotmail.com") || userEmail.equals("wanninghua160@gmail.com") - ) { - if (StringUtil.isNullOrEmpty(startTime)) startTime = "2024-02-01 00:00:00"; - if (StringUtil.isNullOrEmpty(endTime)) { - SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); - Date date = new Date(); - endTime = simpleDateFormat.format(date); - } - if (!StringUtil.isNullOrEmpty(email)){ - email = email.trim(); - } - List designStatistic = designMapper.getDesignStatistic(startTime, endTime, ids, email); - return Response.success(designStatistic); - } else { - return Response.fail("Sorry, you don't have permission"); - } + return Response.success(convenientInquiryService.getDesignStatistic(startTime, endTime, ids, email)); } @@ -215,4 +193,10 @@ public class ConvenientInquiryController { public Response exportTransactionRecords(@Valid @RequestBody QueryPaymentInfoDTO queryPaymentInfoDTO, HttpServletResponse response){ return Response.success(convenientInquiryService.exportTransactionRecords(queryPaymentInfoDTO, response)); } + + @ApiOperation("获取生成功能使用频次") + @PostMapping("/getGenerateFrequency") + public Response> getGenerateFrequency(@Valid @RequestBody AccountCreditsUsageQueryDTO queryDTO){ + return Response.success(convenientInquiryService.getGenerateFrequency(queryDTO)); + } } diff --git a/src/main/java/com/ai/da/controller/ElementController.java b/src/main/java/com/ai/da/controller/ElementController.java index 8065c6dc..ee0b65f6 100644 --- a/src/main/java/com/ai/da/controller/ElementController.java +++ b/src/main/java/com/ai/da/controller/ElementController.java @@ -18,7 +18,10 @@ import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import javax.validation.Valid; +import javax.validation.constraints.Pattern; +import java.util.Arrays; import java.util.List; +import java.util.stream.Collectors; @Api(tags = "collection模块") @@ -106,4 +109,25 @@ public class ElementController { return Response.success(); } + @ApiOperation(value = "图片分割") + @PostMapping("/imageSegmentation") + public Response> selectedImageSeg( + @RequestPart(value = "files", required = false) MultipartFile[] files, + @RequestParam(value = "type", required = false) @Pattern(regexp = "sketch|product", message = "类型必须是sketch或product") String type, + @RequestParam(value = "id", required = false) Long id) { + // 过滤空文件 + List nonEmptyFiles = Arrays.stream(files) + .filter(file -> !file.isEmpty()) + .collect(Collectors.toList()); + // 参数校验 + if ((nonEmptyFiles.isEmpty()) && id == null) { + throw new BusinessException("必须提供文件上传或ID"); + } + if (!nonEmptyFiles.isEmpty() && id != null) { + throw new BusinessException("不能同时提供文件上传和ID"); + } + + return Response.success(collectionElementService.selectedImageSeg(nonEmptyFiles, id, type)); + } + } diff --git a/src/main/java/com/ai/da/mapper/primary/AccountMapper.java b/src/main/java/com/ai/da/mapper/primary/AccountMapper.java index 8826eb71..65d6e8fe 100644 --- a/src/main/java/com/ai/da/mapper/primary/AccountMapper.java +++ b/src/main/java/com/ai/da/mapper/primary/AccountMapper.java @@ -2,8 +2,8 @@ package com.ai.da.mapper.primary; import com.ai.da.common.config.mybatis.plus.CommonMapper; import com.ai.da.mapper.primary.entity.Account; +import com.ai.da.model.dto.AccountCreditsUsageDTO; -import java.util.Date; import java.util.List; /** @@ -32,4 +32,8 @@ public interface AccountMapper extends CommonMapper { void toVisitor(Long id); + List selectCreditUsage(boolean groupByEvent, String changeEvent, String role, String userEmail, Long id, String startTime, String endTime, Integer size, Integer offset); + + int countCreditUsage(boolean groupByEvent, String changeEvent, String role, String userEmail, Long id, String startTime, String endTime); + } diff --git a/src/main/java/com/ai/da/mapper/primary/DesignMapper.java b/src/main/java/com/ai/da/mapper/primary/DesignMapper.java index 425b5a2c..85c69f70 100644 --- a/src/main/java/com/ai/da/mapper/primary/DesignMapper.java +++ b/src/main/java/com/ai/da/mapper/primary/DesignMapper.java @@ -18,7 +18,7 @@ public interface DesignMapper extends CommonMapper { //返回插入数据后生成的主键 Long insertDesign(Design design); - List getDesignStatistic(String startTime, String endTime, List ids, String email); + List getDesignStatistic(String startTime, String endTime, List ids, String email, String role); List selectDeleteList(); } diff --git a/src/main/java/com/ai/da/mapper/primary/entity/Library.java b/src/main/java/com/ai/da/mapper/primary/entity/Library.java index cc5250a4..fcc8fb8f 100644 --- a/src/main/java/com/ai/da/mapper/primary/entity/Library.java +++ b/src/main/java/com/ai/da/mapper/primary/entity/Library.java @@ -69,6 +69,8 @@ public class Library implements Serializable { */ private Integer width; + private String segmentedData; + /** * 创建时间 */ diff --git a/src/main/java/com/ai/da/model/vo/CollectionElementVO.java b/src/main/java/com/ai/da/model/vo/CollectionElementVO.java index 53a1888a..5662f16a 100644 --- a/src/main/java/com/ai/da/model/vo/CollectionElementVO.java +++ b/src/main/java/com/ai/da/model/vo/CollectionElementVO.java @@ -4,6 +4,8 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; +import java.util.List; + @Data @ApiModel("element-响应") public class CollectionElementVO { @@ -42,4 +44,6 @@ public class CollectionElementVO { private String originalUrl; + private List segmentedImages; + } diff --git a/src/main/java/com/ai/da/python/PythonService.java b/src/main/java/com/ai/da/python/PythonService.java index 1d30445d..fc64629d 100644 --- a/src/main/java/com/ai/da/python/PythonService.java +++ b/src/main/java/com/ai/da/python/PythonService.java @@ -21,10 +21,7 @@ import com.ai.da.python.vo.*; import com.ai.da.service.DesignHistoryService; import com.ai.da.service.PythonTAllInfoService; import com.ai.da.service.SysFileService; -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.*; import com.alibaba.fastjson.serializer.SerializerFeature; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.google.common.collect.Lists; @@ -4199,4 +4196,58 @@ public class PythonService { //生成失败 throw new BusinessException("brandDNAGenerate.interface.exception"); } + + public List imageSegmentation(ImageSegmentation imageSegmentation) { + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + + MediaType mediaType = MediaType.parse("application/json"); + RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(imageSegmentation)); + + log.info("modifyModelProportion 请求地址: {},\n 参数:{}", accessPythonIp + ":" + accessPythonPort + "/api/clothing_seg", JSON.toJSONString(imageSegmentation)); + Request request = new Request.Builder() + .url(accessPythonIp + ":" + accessPythonPort + "/api/clothing_seg") + .method("POST", body) + .addHeader("Content-Type", "application/json") + .build(); + Response response = null; + try { + response = client.newCall(request).execute(); + } catch (IOException ioException) { + log.error("PythonService##imageSegmentation异常###{}", ExceptionUtil.getThrowableList(ioException)); + throw new BusinessException("generate.interface.error"); + } + int responseCode = response.code(); + String bodyString; + try { + bodyString = response.body().string(); + if (responseCode != HttpURLConnection.HTTP_OK) { + // 基本不会有除200以外的code + log.info("imageSegmentation 失败。 Response code {}", responseCode); + throw new BusinessException("imageSegmentation 失败。 Response code " + responseCode); + } + JSONObject jsonObject = JSON.parseObject(bodyString); + if (response.isSuccessful() && jsonObject.get("msg").equals("OK!")) { + log.info("imageSegmentation 结果 : {}", jsonObject.get("data").toString()); + List seg = JSONObject.parseObject( + jsonObject.get("data").toString(), + new TypeReference>() {} + ); + return seg; + }else { + log.info("imageSegmentation 失败。 Response code {}", responseCode); + throw new BusinessException("imageSegmentation 失败。 Response code " + responseCode); + } + } catch (IOException e) { + log.error("imageSegmentation 失败; error message => {}", e.getMessage()); + response.close(); + throw new BusinessException("generate.interface.error"); + } finally { + response.close(); + } + } } diff --git a/src/main/java/com/ai/da/python/vo/ImageSegmentation.java b/src/main/java/com/ai/da/python/vo/ImageSegmentation.java new file mode 100644 index 00000000..673741a3 --- /dev/null +++ b/src/main/java/com/ai/da/python/vo/ImageSegmentation.java @@ -0,0 +1,20 @@ +package com.ai.da.python.vo; + +import lombok.Data; + +import java.util.List; + +@Data +public class ImageSegmentation { + + private Long user_id; + private List image_data; + + @Data + public class ImageDate{ + public String image_url; + public String image_type; + // 作为入参时一起传入会怎样? + public List clothing_url; + } +} diff --git a/src/main/java/com/ai/da/service/CollectionElementService.java b/src/main/java/com/ai/da/service/CollectionElementService.java index ef9c6646..3090b504 100644 --- a/src/main/java/com/ai/da/service/CollectionElementService.java +++ b/src/main/java/com/ai/da/service/CollectionElementService.java @@ -5,6 +5,7 @@ import com.ai.da.mapper.primary.entity.LibraryModelPoint; import com.ai.da.model.dto.*; import com.ai.da.model.vo.*; import com.baomidou.mybatisplus.extension.service.IService; +import org.springframework.web.multipart.MultipartFile; import java.util.List; @@ -137,4 +138,7 @@ public interface CollectionElementService extends IService { CollectionElement editLevel2Type(Long elementId, String level2Type, String designType); List getByProjectId(Long projectId); + + List selectedImageSeg(List files, Long id, String type); + } diff --git a/src/main/java/com/ai/da/service/ConvenientInquiryService.java b/src/main/java/com/ai/da/service/ConvenientInquiryService.java index fa279d0d..8cd4eb6b 100644 --- a/src/main/java/com/ai/da/service/ConvenientInquiryService.java +++ b/src/main/java/com/ai/da/service/ConvenientInquiryService.java @@ -4,8 +4,7 @@ import com.ai.da.common.response.PageBaseResponse; import com.ai.da.mapper.primary.entity.Account; import com.ai.da.mapper.primary.entity.Questionnaire; import com.ai.da.mapper.primary.entity.TrialOrder; -import com.ai.da.model.dto.AccountAddDTO; -import com.ai.da.model.dto.QueryPaymentInfoDTO; +import com.ai.da.model.dto.*; import com.ai.da.model.vo.PaymentInfoVO; import com.ai.da.model.vo.QuestionnaireFeedbackVO; import com.ai.da.model.vo.QuestionnaireVO; @@ -21,6 +20,8 @@ public interface ConvenientInquiryService extends IService { IPage getTrial(QueryUserConditionsVO queryUserConditionsVO); + List getDesignStatistic(String startTime, String endTime, List ids, String email); + QuestionnaireFeedbackVO getQuestionnaireInfo(); List getAllQuestionnaire(); @@ -53,4 +54,6 @@ public interface ConvenientInquiryService extends IService { Map> getCities(); String exportTransactionRecords(QueryPaymentInfoDTO queryPaymentInfoDTO, HttpServletResponse response); + + PageBaseResponse getGenerateFrequency(AccountCreditsUsageQueryDTO queryDTO); } diff --git a/src/main/java/com/ai/da/service/impl/CollectionElementServiceImpl.java b/src/main/java/com/ai/da/service/impl/CollectionElementServiceImpl.java index 4b3016ea..c297c457 100644 --- a/src/main/java/com/ai/da/service/impl/CollectionElementServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/CollectionElementServiceImpl.java @@ -1,962 +1,1060 @@ -package com.ai.da.service.impl; - -import cn.hutool.core.collection.CollectionUtil; -import com.ai.da.common.config.FileProperties; -import com.ai.da.common.config.exception.BusinessException; -import com.ai.da.common.context.UserContext; -import com.ai.da.common.enums.*; -import com.ai.da.common.response.ResultEnum; -import com.ai.da.common.utils.*; -import com.ai.da.mapper.primary.CollectionElementMapper; -import com.ai.da.mapper.primary.GenerateDetailMapper; -import com.ai.da.mapper.primary.entity.*; -import com.ai.da.model.dto.*; -import com.ai.da.model.enums.ModelType; -import com.ai.da.model.enums.Sex; -import com.ai.da.model.enums.StyleEnum; -import com.ai.da.model.vo.*; -import com.ai.da.python.PythonService; -import com.ai.da.python.vo.DesignPythonItem; -import com.ai.da.service.*; -import com.alibaba.fastjson.JSON; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.core.metadata.IPage; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.google.common.collect.Lists; -import io.netty.util.internal.StringUtil; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.BeanUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.CollectionUtils; -import org.springframework.util.StringUtils; - -import javax.annotation.Resource; -import java.io.File; -import java.math.BigDecimal; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.*; -import java.util.stream.Collectors; - -/** - * 服务实现类 - * - * @author yanglei - * @since 2022-09-30 - */ -@Slf4j -@Service -public class CollectionElementServiceImpl extends ServiceImpl implements CollectionElementService { - @Resource - private CollectionElementMapper collectionElementMapper; - @Resource - private FileProperties fileProperties; - @Resource - private PanToneService panToneService; - @Resource - private PythonService pythonService; - @Resource - private LibraryService libraryService; - @Resource - private SysFileService sysFileService; - @Resource - private GenerateService generateService; - @Resource - private GenerateDetailMapper generateDetailMapper; - @Resource - private LibraryModelPointService libraryModelPointService; - @Resource - private TCollectionElementRelationService tCollectionElementRelationService; - @Resource - private MinioUtil minioUtil; - - @Value("${minio.bucketName.collectionElement}") - private String collectionElement; - @Value("${minio.bucketName.gradient}") - private String gradientBucketName; - @Resource - private RedisUtil redisUtil; - -// @Resource -// private RedisUtil redisUtil; - - @Transactional(rollbackFor = Exception.class) - @Override - public CollectionElementVO upload(CollectionElementUploadDTO uploadDTO) { - long start = System.currentTimeMillis(); - //用户信息 - AuthPrincipalVo userInfo = UserContext.getUserHolder(); - CollectionLevel1TypeEnum level1TypeEnum = CollectionLevel1TypeEnum.uploadOf(uploadDTO.getLevel1Type()); - if (Objects.isNull(level1TypeEnum)) { - throw new BusinessException("unknown.parameter.level1Type"); - } - String objectName = userInfo.getId() + "/" + level1TypeEnum.getRealName(); - String path = minioUtil.upload(collectionElement, objectName, uploadDTO.getFile()); - - String level2Type = null; - if (uploadDTO.getLevel1Type().equals(CollectionLevel1TypeEnum.SKETCH_BOARD.getRealName())){ - if (StringUtil.isNullOrEmpty(uploadDTO.getGender())) { - throw new BusinessException("gender.cannot.be.empty"); - } - level2Type = pythonService.getClothCategory(path,uploadDTO.getGender()); - } - - //保存element元素 - CollectionElement collectionElement = resolveData(uploadDTO, userInfo, path, level2Type); - saveOne(collectionElement); -// if (!StringUtils.isEmpty(uploadDTO.getMoodboardPosition())) { -// redisUtil.saveMoodboardPosition(collectionElement.getId(), uploadDTO.getMoodboardPosition()); -// } - CollectionElementVO collectionElementVO = CopyUtil.copyObject(collectionElement, CollectionElementVO.class); - collectionElementVO.setMinIOPath(collectionElementVO.getUrl()); - collectionElementVO.setUrl(minioUtil.getPreSignedUrl(collectionElementVO.getUrl(), 24 * 60)); - collectionElementVO.setDesignType(DesignTypeEnum.COLLECTION.getRealName()); - - long end = System.currentTimeMillis(); - double floor = Math.floor((double) (end - start) / 1000); - log.info("本次图片上传耗时:{} 毫秒", end - start); - Long incrementCount = redisUtil.getIncrementCount(RedisUtil.UPLOAD_TIMEOUT_REMINDER_COUNTER); - if (floor > 5 && incrementCount < 3) { - // 邮件通知 一天最多通知3次 - log.info("上传超过5秒,发送邮件通知"); - SendEmailUtil.uploadTimeoutReminder(userInfo.getUsername(), String.valueOf(((end - start) / 1000))); - redisUtil.increaseCount(RedisUtil.UPLOAD_TIMEOUT_REMINDER_COUNTER); - } - return collectionElementVO; - } - - private String calculateFileUrl(CollectionLevel1TypeEnum level1TypeEnum, Long userId) { - String rootPath = fileProperties.getSys().getPath(); - String day = DateUtil.dateToStr(new Date(), DateUtil.YYYYMM); - return rootPath + day + "/" + "userFile" + "/collection" - + "/" + level1TypeEnum.getRealName() + "/" + userId + "/" + UUID.randomUUID().toString(); - } - - private CollectionElement resolveData(CollectionElementUploadDTO uploadDTO, AuthPrincipalVo userInfo, File file) { - CollectionElement element = CopyUtil.copyObject(uploadDTO, CollectionElement.class); - element.setAccountId(userInfo.getId()); - element.setCollectionId(0L); - element.setHasPin((byte) 0); - String pictureCollectonName = file.getName(); - //获取图片后缀 - String suffix = pictureCollectonName.substring(pictureCollectonName.lastIndexOf(".")); - //获取图片前缀 - String prefix = pictureCollectonName.substring(0, pictureCollectonName.lastIndexOf(".")); - element.setName(DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD)); - element.setUrl(file.getAbsolutePath()); - //按时区计算 - element.setCreateDate(DateUtil.getByTimeZone(uploadDTO.getTimeZone())); - String linuxDomain = fileProperties.getLinuxDomain(); - if (!StringUtils.isEmpty(linuxDomain)) { - //linux 系统 - String oldPath = fileProperties.getSys().getPath(); - element.setUrl(file.getAbsolutePath().replace(oldPath, linuxDomain)); - } - return element; - } - - private CollectionElement resolveData(CollectionElementUploadDTO uploadDTO, AuthPrincipalVo userInfo, String path, String level2Type) { - CollectionElement element = CopyUtil.copyObject(uploadDTO, CollectionElement.class); - element.setAccountId(userInfo.getId()); - element.setCollectionId(0L); - element.setHasPin((byte) 0); -// String pictureCollectonName = fileName; -// //获取图片后缀 -// String suffix = pictureCollectonName.substring(pictureCollectonName.lastIndexOf(".")); -// //获取图片前缀 -// String prefix = pictureCollectonName.substring(0,pictureCollectonName.lastIndexOf(".")); - String originalFilename = uploadDTO.getFile().getOriginalFilename(); - if (originalFilename != null && originalFilename.contains(".")) { - // 如果文件名包含点号,则去除最后一个点及其后面的内容 - int lastDotIndex = originalFilename.lastIndexOf("."); - if (lastDotIndex != -1) { - originalFilename = originalFilename.substring(0, lastDotIndex); - } - } - element.setName(originalFilename); - element.setUrl(path); - //按时区计算 - element.setCreateDate(DateUtil.getByTimeZone(uploadDTO.getTimeZone())); - element.setLevel2Type(level2Type); -// String linuxDomain = fileProperties.getLinuxDomain(); -// if (!StringUtils.isEmpty(linuxDomain)) { -// //linux 系统 -// String oldPath = fileProperties.getSys().getPath(); -// element.setUrl(file.getAbsolutePath().replace(oldPath, linuxDomain)); -// } - return element; - } - - @Override - public void delete(Long id) { - CollectionElement collectionElement = selectById(id); - if (Objects.isNull(collectionElement)) { - throw new BusinessException("collectionElement.not.found"); - } - minioUtil.deleteObject(collectionElement.getUrl()); - collectionElementMapper.deleteById(id); -// if (!FileUtil.delete(collectionElement.getUrl())) { -// throw new BusinessException("file deletion failed! "); -// } - } - - @Override - public void batchDelete(List ids) { - if (CollectionUtils.isEmpty(ids)) { - return; - } -// QueryWrapper queryWrapper = new QueryWrapper<>(); -// queryWrapper.in("id", ids); -// CollectionElement collectionElement = new CollectionElement(); -// collectionElement.setCollectionId(0L); - collectionElementMapper.deleteBatchIds(ids); - } - - /** 该方法已不再使用 */ - @Deprecated - @Override - public GenerateCollectionItemVO generatePrint(CollectionGeneratePrintDTO generatePrintDTO) { - Long userId = UserContext.getUserHolder().getId(); - String url1 = null; - String url2 = null; - CollectionElement element1 = selectById(generatePrintDTO.getSelect1Id()); - if (Objects.isNull(element1)) { - Library library1 = libraryService.getById(generatePrintDTO.getSelect1Id()); - if (Objects.isNull(library1)) { - throw new BusinessException("select1.file.does.not.exist"); - } - url1 = library1.getUrl(); - } else { - url1 = element1.getUrl(); - } - CollectionElement element2 = selectById(generatePrintDTO.getSelect2Id()); - if (Objects.isNull(element2)) { - Library library2 = libraryService.getById(generatePrintDTO.getSelect2Id()); - if (Objects.isNull(library2)) { - throw new BusinessException("select2.file.does.not.exist"); - } - url2 = library2.getUrl(); - } else { - url2 = element2.getUrl(); - } - List printPath = Arrays.asList(url1, url2); - //调取python 接口 - String generateUrl = pythonService.generatePrint(printPath,userId); - if (StringUtils.isEmpty(generateUrl)) { - throw new BusinessException("generate.interface.exception"); - } - - // 保存合成信息到generate表 - Generate generate = setGenerate(userId, generatePrintDTO.getTimeZone()); - generateService.save(generate); - - // 保存合成后的信息到generateDetail - GenerateDetail generateDetail = setGenerateDetail(generate.getId(), generateUrl, generatePrintDTO.getTimeZone()); - generateDetailMapper.insert(generateDetail); - -// CollectionElement element = resolveData(generateUrl, generatePrintDTO.getTimeZone(), userId); -// if (!this.save(element)) { -// throw new BusinessException("save.collectionElement.failed"); -// } -// CollectionGeneratePrintVO collectionGeneratePrint = CopyUtil.copyObject(element, CollectionGeneratePrintVO.class); -// collectionGeneratePrint.setUrl(minioUtil.getPresignedUrl(generateUrl, 24 * 60)); -// collectionGeneratePrint.setDesignType(DesignTypeEnum.COLLECTION.getRealName()); -// return collectionGeneratePrint; - return new GenerateCollectionItemVO(generateDetail.getId(), - minioUtil.getPreSignedUrl(generateUrl, 24 * 60), - generateDetail.getIsLike().equals((byte) 0) ? Boolean.FALSE : Boolean.TRUE); - } - - @Override - public Boolean savePrint(CollectionSavePrintDTO savePrintDTO) { - //用户信息 - List elements = listByIds(savePrintDTO.getPrintId()); - if (CollectionUtils.isEmpty(elements)) { - throw new BusinessException("collectionElements.not.found"); - } - return saveLibraryByCollectionElement(elements, savePrintDTO.getTimeZone()); - } - - @Override - public Boolean saveLibraryByCollectionElement(List elements, String timeZone) { - if (CollectionUtils.isEmpty(elements)) { - return Boolean.TRUE; - } - //获取已存在相同的library - List md5List = elements.stream().map(CollectionElement::getMd5).collect(Collectors.toList()); - List existsLibrarys = libraryService.getByMD5List(md5List); - if (!CollectionUtils.isEmpty(existsLibrarys)) { - //去重 - List existsMd5Lists = existsLibrarys.stream().map(Library::getMd5).collect(Collectors.toList()); - elements = elements.stream().filter(element -> !existsMd5Lists.contains(element.getMd5())).collect(Collectors.toList()); - } - if (CollectionUtils.isEmpty(elements)) { - //都是重复的 - return Boolean.TRUE; - } - String name = DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD); - List libraryList = CopyUtil.copyList(elements, Library.class, (o, d) -> { - d.setCreateDate(DateUtil.getByTimeZone(timeZone)); - d.setName(name); - d.setId(null); - }); - if (!libraryService.saveBatch(libraryList)) { - throw new BusinessException("batch.save.libraryList.failed"); - } - return Boolean.TRUE; - } - - @Override - public Boolean saveLibraryByCollectionElement(List elements, String timeZone, String modelSex) { - if (CollectionUtils.isEmpty(elements)) { - return Boolean.TRUE; - } - //获取已存在相同的library - List md5List = elements.stream().map(CollectionElement::getMd5).collect(Collectors.toList()); - List existsLibrarys = libraryService.getByMD5List(md5List); - if (!CollectionUtils.isEmpty(existsLibrarys)) { - //去重 - List existsMd5Lists = existsLibrarys.stream().map(Library::getMd5).collect(Collectors.toList()); - elements = elements.stream().filter(element -> !existsMd5Lists.contains(element.getMd5())).collect(Collectors.toList()); - } - if (CollectionUtils.isEmpty(elements)) { - //都是重复的 - return Boolean.TRUE; - } - String name = DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD); - List libraryList = CopyUtil.copyList(elements, Library.class, (o, d) -> { - if (d.getLevel1Type().equals(LibraryLevel1TypeEnum.SKETCH_BOARD.getRealName())) { - d.setLevel3Type(modelSex); -// try { -// libraryService.processSketchBoards(d.getUrl(), d.getLevel2Type()); -// }catch (Exception e) { -// // TODO:暂不处理 -// } - } - d.setCreateDate(DateUtil.getByTimeZone(timeZone)); - d.setName(name); - d.setId(null); - }); - if (!libraryService.saveBatch(libraryList)) { - throw new BusinessException("batch.save.libraryList.failed"); - } - return Boolean.TRUE; - } - - private CollectionElement resolveData(String path, String timeZone, Long userId){ -// File file = new File(path); - - String name = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf(".")); - CollectionElement element = new CollectionElement(); - element.setAccountId(userId); - element.setCollectionId(0L); - element.setName(name); - element.setLevel1Type(CollectionLevel1TypeEnum.PRINT_BOARD.getRealName()); - element.setUrl(path); - element.setHasPin((byte) 0); - try { - element.setMd5(MD5Utils.encryptFile(minioUtil.download(path))); - }catch (Exception e){ - throw new RuntimeException(e); - } - /* catch (MinioException | IOException e) { - throw new RuntimeException(e); - }*/ - - //按时区计算 - element.setCreateDate(DateUtil.getByTimeZone(timeZone)); - return element; - } - - @Override - public ValidateElementVO validateElement(DesignCollectionDTO designDTO) { - ValidateElementVO elementVO = CopyUtil.copyObject(designDTO, ValidateElementVO.class); - List colorBoards = elementVO.getColorBoards(); - for (CollectionColorDTO colorBoard : colorBoards) { - if (Objects.nonNull(colorBoard.getGradient())) { - String colorImg = colorBoard.getGradient().getColorImg(); - String[] parts = colorImg.split(","); - String imageType = parts[0].split("/")[1].split(";")[0]; - String base64Data = parts[1]; - String gradientMinioUrl = minioUtil.uploadImageFromBase64(gradientBucketName, base64Data, imageType); - colorBoard.setGradientMinioUrl(gradientMinioUrl); - colorBoard.getGradient().setColorImg(null); - colorBoard.setGradientString(JSON.toJSONString(colorBoard.getGradient())); - } - } - elementVO.setColorBoards(colorBoards); - List usedElementIds = elementVO.getUsedElementIds(); - List libraryCollectionElements = elementVO.getLibraryCollectionElements(); - List generateCollectionElements = elementVO.getGenerateCollectionElements(); - //校验moodboard - if (CollectionUtil.isNotEmpty(designDTO.getMoodBoards())) { - //校验designType - validateDesignType(designDTO.getMoodBoards(), "moodBoards"); - List moodBoardIds = designDTO.getMoodBoards().stream() - .filter(f -> f.getDesignType().equals(DesignTypeEnum.COLLECTION.getRealName())) - .map(DesignCollectionElementDTO::getId) - .collect(Collectors.toList()); - if (!CollectionUtils.isEmpty(moodBoardIds)) { - List MoodBoardElements = collectionElementMapper.selectBatchIds(moodBoardIds); - if (CollectionUtil.isEmpty(MoodBoardElements) || MoodBoardElements.size() != moodBoardIds.size()) { - throw new BusinessException("get.moodBoards.data.is.mismatch"); - } - elementVO.setMoodBoardElements(MoodBoardElements); - usedElementIds.addAll(moodBoardIds); - } - //library - List libraryIds = designDTO.getMoodBoards().stream() - .filter(f -> f.getDesignType().equals(DesignTypeEnum.LIBRARY.getRealName())) - .map(DesignCollectionElementDTO::getId) - .collect(Collectors.toList()); - if (!CollectionUtils.isEmpty(libraryIds)) { - List librarys = libraryService.getByIds(libraryIds); - //不校验了防止用户在library删除 对应不上 - if (CollectionUtil.isNotEmpty(librarys)) { - libraryCollectionElements.addAll(covertLibrarysToCollections(librarys, null)); - } - } - // generate - List generateIds = designDTO.getMoodBoards().stream() - .filter(o -> o.getDesignType().equals((DesignTypeEnum.GENERATE.getRealName()))) - .map(DesignCollectionElementDTO::getId) - .collect((Collectors.toList())); - if (CollectionUtil.isNotEmpty(generateIds)) { - List generateDetailList = generateDetailMapper.selectBatchIds(generateIds); - if (CollectionUtil.isNotEmpty(generateDetailList)) { - generateCollectionElements.addAll(covertGeneratesToCollections(generateDetailList, null)); - } - } - } - if (CollectionUtil.isNotEmpty(designDTO.getPrintBoards())) { - //校验designType - validateDesignType(CopyUtil.copyList(designDTO.getPrintBoards(), DesignCollectionElementDTO.class), "printBoards"); - List printBoardIds = designDTO.getPrintBoards().stream() - .filter(f -> f.getDesignType().equals(DesignTypeEnum.COLLECTION.getRealName())) - .map(DesignCollectionPrintElementDTO::getId) - .collect(Collectors.toList()); - if (!CollectionUtils.isEmpty(printBoardIds)) { - //校验printboard - List printBoardElements = collectionElementMapper.selectBatchIds(printBoardIds); - if (CollectionUtil.isEmpty(printBoardElements) || printBoardElements.size() != printBoardIds.size()) { - throw new BusinessException("get.printBoards.data.is.mismatch"); - } - elementVO.setPrintBoardElements(printBoardElements); - usedElementIds.addAll(printBoardIds); - } - //library - List libraryIds = designDTO.getPrintBoards().stream() - .filter(f -> f.getDesignType().equals(DesignTypeEnum.LIBRARY.getRealName())) - .map(DesignCollectionPrintElementDTO::getId) - .collect(Collectors.toList()); - if (!CollectionUtils.isEmpty(libraryIds)) { - List librarys = libraryService.getByIds(libraryIds); - //不校验了防止用户在library删除 对应不上 - if (CollectionUtil.isNotEmpty(librarys)) { - Map idToMap = designDTO.getPrintBoards() - .stream() - .collect(Collectors.toMap(DesignCollectionPrintElementDTO::getId, v -> v)); - libraryCollectionElements.addAll(covertLibrarysToPrintCollections(librarys, idToMap)); - } - } - // generate - List generateIds = designDTO.getPrintBoards().stream() - .filter(o -> o.getDesignType().equals((DesignTypeEnum.GENERATE.getRealName()))) - .map(DesignCollectionPrintElementDTO::getId) - .collect((Collectors.toList())); - if (CollectionUtil.isNotEmpty(generateIds)) { - List generateDetailList = generateDetailMapper.selectBatchIds(generateIds); - if (CollectionUtil.isNotEmpty(generateDetailList)) { - Map idToMap = designDTO.getPrintBoards() - .stream() - .collect(Collectors.toMap(DesignCollectionPrintElementDTO::getId, v -> v)); - generateCollectionElements.addAll(covertGeneratesToPrintCollections(generateDetailList, idToMap)); - } - } - } - if (CollectionUtil.isNotEmpty(designDTO.getSketchBoards())) { - //校验PIN是否满足 上衣或者下衣必须不超过8 - long topNum = 0; - long bottomNum = 0; - long outerwearNum = 0; - if (designDTO.getModelSex().equals(Sex.FEMALE.getValue())) { - topNum= designDTO.getSketchBoards().stream() - .filter(skecth -> skecth.getIsPin() == 1 - && DesignPythonItem.DRESS_BLOUSE.contains(skecth.getLevel2Type())).count(); - bottomNum = designDTO.getSketchBoards().stream() - .filter(skecth -> skecth.getIsPin() == 1 - && DesignPythonItem.SKIRT_TROUSERS.contains(skecth.getLevel2Type())).count(); - }else if (designDTO.getModelSex().equals(Sex.MALE.getValue())) { - topNum= designDTO.getSketchBoards().stream() - .filter(skecth -> skecth.getIsPin() == 1 - && DesignPythonItem.TOPS.contains(skecth.getLevel2Type())).count(); - bottomNum = designDTO.getSketchBoards().stream() - .filter(skecth -> skecth.getIsPin() == 1 - && DesignPythonItem.BOTTOMS.contains(skecth.getLevel2Type())).count(); - } - outerwearNum = designDTO.getSketchBoards().stream() - .filter(skecth -> skecth.getIsPin() == 1 - && DesignPythonItem.OUTWEAR.contains(skecth.getLevel2Type())).count(); - if (topNum > 8 || bottomNum > 8 || outerwearNum > 8) { - throw new BusinessException("the.number.of.PIN.top.or.bottom.or.outerwear.sketchBoard.cannot.be.more.than.8", ResultEnum.PROMPT.getCode()); - } - //校验designType - Boolean result = designDTO.getSketchBoards().stream() - .filter(mood -> StringUtils.isEmpty(mood.getDesignType())) - .findFirst().isPresent(); - if (result) { - throw new BusinessException("sketchBoards.designType.cannot.be.empty"); - } - - List sketchBoardIds = designDTO.getSketchBoards().stream() - .filter(f -> f.getDesignType().equals(DesignTypeEnum.COLLECTION.getRealName())) - .map(CollectionSketchDTO::getSketchBoardId) - .collect(Collectors.toList()); - if (!CollectionUtils.isEmpty(sketchBoardIds)) { - //校验sketchBoard - List sketchBoardElements = collectionElementMapper.selectBatchIds(sketchBoardIds); - if (CollectionUtil.isEmpty(sketchBoardElements) || sketchBoardElements.size() != sketchBoardIds.size()) { - throw new BusinessException("get.sketchBoards.data.is.mismatch"); - } - elementVO.setSketchBoardElements(sketchBoardElements); - usedElementIds.addAll(sketchBoardIds); - } - //library - List libraryIds = designDTO.getSketchBoards().stream() - .filter(f -> f.getDesignType().equals(DesignTypeEnum.LIBRARY.getRealName())) - .map(CollectionSketchDTO::getSketchBoardId) - .collect(Collectors.toList()); - if (!CollectionUtils.isEmpty(libraryIds)) { - List librarys = libraryService.getByIds(libraryIds); - //不校验了防止用户在library删除 对应不上 - if (CollectionUtil.isNotEmpty(librarys)) { - Map idToMap = designDTO.getSketchBoards() - .stream() - .collect(Collectors.toMap(CollectionSketchDTO::getSketchBoardId, v -> v)); - libraryCollectionElements.addAll(covertLibrarysToCollections(librarys, idToMap)); - } - } - // generate - List generateIds = designDTO.getSketchBoards().stream() - .filter(o -> o.getDesignType().equals((DesignTypeEnum.GENERATE.getRealName()))) - .map(CollectionSketchDTO::getSketchBoardId) - .collect((Collectors.toList())); - if (CollectionUtil.isNotEmpty(generateIds)) { - List generateDetailList = generateDetailMapper.selectBatchIds(generateIds); - if (CollectionUtil.isNotEmpty(generateDetailList)) { - Map idToMap = designDTO.getSketchBoards() - .stream() - .collect(Collectors.toMap(CollectionSketchDTO::getSketchBoardId, v -> v)); - generateCollectionElements.addAll(covertGeneratesToCollections(generateDetailList, idToMap)); - } - } - } - //校验marketingSketch - // 2023.12版本去掉了这个入参 -// if (CollectionUtil.isNotEmpty(designDTO.getMarketingSketchs())) { -// //校验designType -// validateDesignType(designDTO.getMarketingSketchs(),"marketingSketchs"); -// List printBoardIds = designDTO.getMarketingSketchs().stream() -// .filter(f ->f.getDesignType().equals(DesignTypeEnum.COLLECTION.getRealName())) -// .map(DesignCollectionElementDTO::getId) -// .collect(Collectors.toList()); -// if(!CollectionUtils.isEmpty(printBoardIds)){ -// List marketingSketchElements = collectionElementMapper.selectBatchIds(printBoardIds); -// Assert.isTrue(CollectionUtil.isNotEmpty(marketingSketchElements) -// && marketingSketchElements.size() == printBoardIds.size(), "get marketingSketch data is mismatch"); -// elementVO.setMarketingSketchElements(marketingSketchElements); -// usedElementIds.addAll(printBoardIds); -// } -// //library -// List libraryIds = designDTO.getMarketingSketchs().stream() -// .filter(f ->f.getDesignType().equals(DesignTypeEnum.LIBRARY.getRealName())) -// .map(DesignCollectionElementDTO::getId) -// .collect(Collectors.toList()); -// if(!CollectionUtils.isEmpty(libraryIds)){ -// List librarys = libraryService.getByIds(libraryIds); -// //不校验了防止用户在library删除 对应不上 -// if(CollectionUtil.isNotEmpty(librarys)){ -// libraryCollectionElements.addAll(covertLibrarysToCollections(librarys,null)); -// } -// } -// } - //校验控制生成类型 - SingleOverallEnum singleOverall = SingleOverallEnum.of(designDTO.getSingleOverall()); - if (Objects.isNull(singleOverall)) { - throw new BusinessException("unknown.parameter.singleOverall"); - } - if (SingleOverallEnum.SINGLE.equals(singleOverall)) { - SwitchCategoryEnum switchCategory = SwitchCategoryEnum.of(designDTO.getSwitchCategory()); - if (Objects.isNull(switchCategory)) { - throw new BusinessException("unknown.parameter.switchCategory"); - } - } - // 校验模特 - if (!StringUtils.isEmpty(designDTO.getModelType())) { - if (designDTO.getModelType().equals(ModelType.LIBRARY.getValue())) { - Library byId = libraryService.getById(designDTO.getTemplateId()); - LibraryModelPoint modelPoint = libraryModelPointService.getByRelationId(byId.getId(), designDTO.getModelType()); - elementVO.setDesignLibraryModelPoint(calculateTemplatePointTemplate(modelPoint, byId.getHigh(), byId.getWidth(), byId.getUrl())); - } else if (designDTO.getModelType().equals(ModelType.SYSTEM.getValue())) { - SysFileVO byId = sysFileService.getById(designDTO.getTemplateId()); - if (!StringUtils.isEmpty(byId.getLevel3Type()) && byId.getLevel2Type().equals("Female")) { - elementVO.setStyle(byId.getLevel3Type()); - } - LibraryModelPoint modelPoint = libraryModelPointService.getByRelationId(byId.getId(), designDTO.getModelType()); - elementVO.setDesignLibraryModelPoint(calculateTemplatePointTemplate(modelPoint, 700, 320, byId.getUrl())); - } - } - elementVO.setModelSex(designDTO.getModelSex()); - elementVO.setRequestIdList(designDTO.getRequestIdList()); - if (null != designDTO.getDesignNum()) { - elementVO.setDesignNum(designDTO.getDesignNum()); - }else { - elementVO.setDesignNum(8); - } - return elementVO; - } - - @Override - public DesignLibraryModelPointVO calculateTemplatePoint(LibraryModelPoint modelPoint, Integer high, Integer width, String templateUrl) { - DesignLibraryModelPointVO libraryModelPoint = new DesignLibraryModelPointVO(); - libraryModelPoint.setHandLeft(calculateTemplatePointOne(modelPoint.getHandLeft(), high, width)); - libraryModelPoint.setHandRight(calculateTemplatePointOne(modelPoint.getHandRight(), high, width)); - libraryModelPoint.setShoulderLeft(calculateTemplatePointOne(modelPoint.getShoulderLeft(), high, width)); - libraryModelPoint.setShoulderRight(calculateTemplatePointOne(modelPoint.getShoulderRight(), high, width)); - libraryModelPoint.setWaistbandLeft(calculateTemplatePointOne(modelPoint.getWaistbandLeft(), high, width)); - libraryModelPoint.setWaistbandRight(calculateTemplatePointOne(modelPoint.getWaistbandRight(), high, width)); - libraryModelPoint.setTemplateUrl(templateUrl); - return libraryModelPoint; - } - - @Override - public DesignLibraryModelPointVO calculateTemplatePointTemplate(LibraryModelPoint modelPoint, Integer high, Integer width, String templateUrl) { - DesignLibraryModelPointVO libraryModelPoint = new DesignLibraryModelPointVO(); -// LibraryModelPoint template = libraryModelPointService.getById(96L); -// libraryModelPoint.setHandLeft(calculateTemplatePointOne(template.getHandLeft(),752,564)); -// libraryModelPoint.setHandRight(calculateTemplatePointOne(template.getHandRight(),752,564)); -// libraryModelPoint.setShoulderLeft(calculateTemplatePointOne(template.getShoulderLeft(),752,564)); -// libraryModelPoint.setShoulderRight(calculateTemplatePointOne(template.getShoulderRight(),752,564)); -// libraryModelPoint.setWaistbandLeft(calculateTemplatePointOne(template.getWaistbandLeft(),752,564)); -// libraryModelPoint.setWaistbandRight(calculateTemplatePointOne(template.getWaistbandRight(),752,564)); -// libraryModelPoint.setTemplateUrl("aida-mannequins/model_1693218345.2714432.png"); - libraryModelPoint.setHandLeft(calculateTemplatePointOne(modelPoint.getHandLeft(), high, width)); - libraryModelPoint.setHandRight(calculateTemplatePointOne(modelPoint.getHandRight(), high, width)); - libraryModelPoint.setShoulderLeft(calculateTemplatePointOne(modelPoint.getShoulderLeft(), high, width)); - libraryModelPoint.setShoulderRight(calculateTemplatePointOne(modelPoint.getShoulderRight(), high, width)); - libraryModelPoint.setWaistbandLeft(calculateTemplatePointOne(modelPoint.getWaistbandLeft(), high, width)); - libraryModelPoint.setWaistbandRight(calculateTemplatePointOne(modelPoint.getWaistbandRight(), high, width)); - libraryModelPoint.setTemplateUrl(templateUrl); - return libraryModelPoint; - } - - private List calculateTemplatePointOne(String template, Integer high, Integer width) { - List originRatioList = JSON.parseObject(template, List.class); - originRatioList.set(0, originRatioList.get(0).multiply(BigDecimal.valueOf(width))); - originRatioList.set(1, originRatioList.get(1).multiply(BigDecimal.valueOf(high))); - return originRatioList; - } - - private List covertLibrarysToCollections(List libraries, Map idToMap) { - return CopyUtil.copyList(libraries, CollectionElement.class, (o, d) -> { - if (null != idToMap) { - CollectionSketchDTO sketchDTO = idToMap.get(o.getId()); - d.setLevel2Type(sketchDTO.getLevel2Type()); - d.setHasPin(sketchDTO.getIsPin()); - } - }); - } - - private List covertGeneratesToCollections(List generateDetailList, Map idToMap) { - return CopyUtil.copyList(generateDetailList, CollectionElement.class, (o, d) -> { - Generate byId = generateService.getById(o.getGenerateId()); - d.setAccountId(byId.getAccountId()); - d.setLevel1Type(byId.getLevel1Type()); - d.setCreateDate(Date.from(o.getCreateDate().atZone(ZoneId.systemDefault()).toInstant())); - if (null != idToMap) { - CollectionSketchDTO sketchDTO = idToMap.get(o.getId()); - d.setLevel2Type(sketchDTO.getLevel2Type()); - d.setHasPin(sketchDTO.getIsPin()); - } - }); - } - - private List covertLibrarysToPrintCollections(List libraries, Map idToMap) { - return CopyUtil.copyList(libraries, CollectionElement.class, (o, d) -> { - if (null != idToMap) { - DesignCollectionPrintElementDTO printDTO = idToMap.get(o.getId()); - d.setHasPin(printDTO.getIsPin()); - } - }); - } - - private List covertGeneratesToPrintCollections(List generateDetailList, Map idToMap) { - return CopyUtil.copyList(generateDetailList, CollectionElement.class, (o, d) -> { - Generate byId = generateService.getById(o.getGenerateId()); - d.setAccountId(byId.getAccountId()); - d.setLevel1Type(byId.getLevel1Type()); - if (!StringUtils.isEmpty(byId.getLevel2Type())) { - d.setLevel2Type(byId.getLevel2Type()); - } - d.setCreateDate(Date.from(o.getCreateDate().atZone(ZoneId.systemDefault()).toInstant())); - if (null != idToMap) { - DesignCollectionPrintElementDTO printDTO = idToMap.get(o.getId()); - d.setHasPin(printDTO.getIsPin()); - } - }); - } - - private void validateDesignType(List collectionElements, String msg) { - Boolean result = collectionElements.stream().filter(mood -> StringUtils.isEmpty(mood.getDesignType())).findFirst().isPresent(); - if (result) { - throw new BusinessException(msg + ".designType.cannot.be.empty"); - } - } - - @Override - public void editSketchBoardsElement(ValidateElementVO elementVO, List sketchBoards) { - if (CollectionUtil.isNotEmpty(sketchBoards)) { - List collect = sketchBoards.stream().filter(o -> o.getDesignType().equals(DesignTypeEnum.COLLECTION.getRealName())).collect(Collectors.toList()); - collect.forEach(sketchBoard -> { - CollectionElement collectionElement = CopyUtil.copyObject(sketchBoard, CollectionElement.class); - collectionElement.setHasPin(sketchBoard.getIsPin()); - collectionElement.setId(sketchBoard.getSketchBoardId()); - collectionElementMapper.updateById(collectionElement); - }); - List sketchBoardIds = collect.stream().map(CollectionSketchDTO::getSketchBoardId).collect(Collectors.toList()); - if (!CollectionUtils.isEmpty(sketchBoardIds)) { - List sketchBoardElements = collectionElementMapper.selectBatchIds(sketchBoardIds); - elementVO.setSketchBoardElements(sketchBoardElements); - }else { - elementVO.setSketchBoardElements(new ArrayList<>()); - } - } - } - - @Override - public void editPrintBoardsElement(ValidateElementVO elementVO, List printBoards) { - if (CollectionUtil.isNotEmpty(printBoards)) { - List collect = printBoards.stream().filter(o -> o.getDesignType().equals(DesignTypeEnum.COLLECTION.getRealName())).collect(Collectors.toList()); - collect.forEach(printBoard -> { - CollectionElement collectionElement = CopyUtil.copyObject(printBoard, CollectionElement.class); - collectionElement.setHasPin(Objects.isNull(printBoard.getIsPin()) ? 0 : printBoard.getIsPin()); - collectionElement.setId(printBoard.getId()); - collectionElementMapper.updateById(collectionElement); - }); - List printBoardIds = collect.stream().map(DesignCollectionPrintElementDTO::getId).collect(Collectors.toList()); - if (!CollectionUtils.isEmpty(printBoardIds)) { - List printBoardElements = collectionElementMapper.selectBatchIds(printBoardIds); - elementVO.setPrintBoardElements(printBoardElements); - }else { - elementVO.setPrintBoardElements(new ArrayList<>()); - } - } - } - - @Transactional(rollbackFor = Exception.class) - @Override - public void relationCollection(List elementIds, Long collectionId) { - if (CollectionUtils.isEmpty(elementIds) || null == collectionId) { - return; - } - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.lambda().in(CollectionElement::getId, elementIds); - CollectionElement element = new CollectionElement(); - element.setCollectionId(collectionId); - //批量关联 - collectionElementMapper.update(element, queryWrapper); - } - - @Transactional(rollbackFor = Exception.class) - @Override - public List saveColorBoard(List colorBoards, Long collectionId, String timeZone) { - //用户信息 - AuthPrincipalVo userInfo = UserContext.getUserHolder(); - List colorElements = resolveColorData(colorBoards, userInfo, collectionId, timeZone); - if (!this.saveBatch(colorElements)) { - throw new BusinessException("batch.save.colorElements.failed"); - } - return CopyUtil.copyList(colorElements, CollectionElementVO.class); - } - - @Override - public void refreshHistoryData() { - //幂等 - if (!CollectionUtils.isEmpty(tCollectionElementRelationService.getByCollectionId(1083L))) { - return; - } - // 分页数据 - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.orderByAsc("id"); - PageQueryBaseVo pageQuery = new PageQueryBaseVo(); - pageQuery.setPage(1); - pageQuery.setSize(200); - while (true) { - IPage page = getBaseMapper().selectPage( - new Page<>(pageQuery.getPage(), pageQuery.getSize()), queryWrapper); - List list = page.getRecords(); - if (CollectionUtils.isEmpty(list)) { - break; - } - - //保存 - List relations = list.stream().map(element -> - TCollectionElementRelation.builder().elementId(element.getId()) - .collectionId(element.getCollectionId()).createDate(new Date()).build()) - .collect(Collectors.toList()); - tCollectionElementRelationService.saveBatch(relations); - pageQuery.setPage(pageQuery.getPage() + 1); - log.info("refreshHistoryData###process###page###" + pageQuery.getPage()); - } - } - - private List resolveColorData(List colorBoards, AuthPrincipalVo userInfo, Long collectionId, String timeZone) { - List elements = Lists.newArrayList(); - colorBoards.forEach(color -> { - CollectionElement element = new CollectionElement(); - element.setAccountId(userInfo.getId()); - element.setCollectionId(collectionId); - if (StringUtils.isEmpty(color.getName())) { - element.setName(null); - } else { - element.setName(color.getId() + "_" + color.getName() + "_" + color.getTcx()); - } - element.setLevel1Type(CollectionLevel1TypeEnum.COLOR_BOARD.getRealName()); - element.setHasPin((byte) 0); - element.setMd5("0"); - element.setColorRgb(color.getRgbValue()); - //按时区计算 - element.setCreateDate(DateUtil.getByTimeZone(timeZone)); - if (Objects.nonNull(color.getGradient())) { - color.getGradient().setColorImg(null); - } - element.setGradientString(JSON.toJSONString(color.getGradient())); - elements.add(element); - }); - return elements; - } - - @Override - public List getByCollectionId(Long collectionId) { -// List elementIds = tCollectionElementRelationService.getByCollectionId(collectionId); -// if (CollectionUtils.isEmpty(elementIds)) { -// return null; -// } - QueryWrapper queryWrapper = new QueryWrapper<>(); -// queryWrapper.in("id", elementIds); - queryWrapper.lambda().eq(CollectionElement::getCollectionId, collectionId); - return collectionElementMapper.selectList(queryWrapper); - } - - @Override - public List getByOnlyCollectionId(Long collectionId) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("collection_id", collectionId); - return collectionElementMapper.selectList(queryWrapper); - } - - private CollectionElement selectById(Long id) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("id", id); - return collectionElementMapper.selectOne(queryWrapper); - } - - private Boolean exists(Long id) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("id", id); - return collectionElementMapper.exists(queryWrapper); - } - - private boolean saveOne(CollectionElement collectionElement) { - if (collectionElementMapper.insert(collectionElement) <= 0) { - throw new BusinessException("save.collectionElement.failed"); - } - return Boolean.TRUE; - } - - @Override - public CollectionElement editLevel2Type(Long elementId, String level2Type, String designType) { - CollectionElement collectionElement = new CollectionElement(); - - if (!Objects.isNull(elementId)) { - if (!StringUtil.isNullOrEmpty(designType)){ - switch (designType){ - case "collection": - collectionElement = collectionElementMapper.selectById(elementId); - if (StringUtil.isNullOrEmpty(collectionElement.getLevel2Type()) || !(collectionElement.getLevel2Type()).equals(level2Type)) { - collectionElement.setLevel2Type(level2Type); - updateById(collectionElement); - } - break; - case "library": - Library libraryElement = libraryService.getById(elementId); - if (!Objects.isNull(libraryElement)) { - if (StringUtil.isNullOrEmpty(libraryElement.getLevel2Type()) || !(libraryElement.getLevel2Type()).equals(level2Type)){ - libraryElement.setLevel2Type(level2Type); - libraryService.updateById(libraryElement); - } - BeanUtils.copyProperties(libraryElement,collectionElement); - } - break; - } - } else { - log.error("designType cannot be empty"); - throw new BusinessException("element source type cannot be empty!"); - } - }else { - return null; - } - return collectionElement; - } - - @Override - public List getByProjectId(Long projectId) { - QueryWrapper qw = new QueryWrapper<>(); - qw.lambda().eq(CollectionElement::getProjectId, projectId); - List collectionElementList = collectionElementMapper.selectList(qw); - if (CollectionUtils.isEmpty(collectionElementList)) { - return new ArrayList<>(); - } - return collectionElementList; - } - - private Generate setGenerate(Long userId,String timeZone){ - Generate generate = new Generate(); - generate.setAccountId(userId); - generate.setLevel1Type(CollectionLevel1TypeEnum.PRINT_BOARD.getRealName()); - generate.setGenerateType("synthesis"); -// generate.setModelName("Image Synthesis Model"); - generate.setCreateDate(DateUtil.getByTimeZone(timeZone)); - return generate; - } - - private GenerateDetail setGenerateDetail(Long generateId, String url, String timeZone){ - GenerateDetail generateDetail = new GenerateDetail(); - generateDetail.setGenerateId(generateId); - generateDetail.setUrl(url); - String md5; - try { - md5 = MD5Utils.encryptFile(minioUtil.download(url)); - } catch (Exception e){ - throw new RuntimeException(e); - }/*catch (MinioException | IOException e) { - throw new RuntimeException(e); - }*/ - // 通过MD5来确认当前图片是否有被like过,避免重复like - List> libraryIds = generateDetailMapper.getLibraryIdThroughMD5(md5, CollectionLevel1TypeEnum.PRINT_BOARD.getRealName()); - if (libraryIds.isEmpty()){ - generateDetail.setIsLike((byte) 0); - }else { - generateDetail.setIsLike((byte) 1); - generateDetail.setLibraryId(libraryIds.get(0).get("library_id")); - } - generateDetail.setMd5(md5); - generateDetail.setCreateDate(LocalDateTime.now()); - - return generateDetail; - } -} +package com.ai.da.service.impl; + +import cn.hutool.core.collection.CollectionUtil; +import com.ai.da.common.config.FileProperties; +import com.ai.da.common.config.exception.BusinessException; +import com.ai.da.common.constant.CommonConstant; +import com.ai.da.common.context.UserContext; +import com.ai.da.common.enums.*; +import com.ai.da.common.response.ResultEnum; +import com.ai.da.common.utils.*; +import com.ai.da.mapper.primary.CollectionElementMapper; +import com.ai.da.mapper.primary.GenerateDetailMapper; +import com.ai.da.mapper.primary.entity.*; +import com.ai.da.model.dto.*; +import com.ai.da.model.enums.ModelType; +import com.ai.da.model.enums.Sex; +import com.ai.da.model.enums.StyleEnum; +import com.ai.da.model.vo.*; +import com.ai.da.python.PythonService; +import com.ai.da.python.vo.DesignPythonItem; +import com.ai.da.python.vo.ImageSegmentation; +import com.ai.da.service.*; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.google.common.collect.Lists; +import com.google.gson.Gson; +import io.netty.util.internal.StringUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; +import org.springframework.web.multipart.MultipartFile; + +import javax.annotation.Resource; +import java.io.File; +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.*; +import java.util.stream.Collectors; + +/** + * 服务实现类 + * + * @author yanglei + * @since 2022-09-30 + */ +@Slf4j +@Service +public class CollectionElementServiceImpl extends ServiceImpl implements CollectionElementService { + @Resource + private CollectionElementMapper collectionElementMapper; + @Resource + private FileProperties fileProperties; + @Resource + private PanToneService panToneService; + @Resource + private PythonService pythonService; + @Resource + private LibraryService libraryService; + @Resource + private SysFileService sysFileService; + @Resource + private GenerateService generateService; + @Resource + private GenerateDetailMapper generateDetailMapper; + @Resource + private LibraryModelPointService libraryModelPointService; + @Resource + private TCollectionElementRelationService tCollectionElementRelationService; + @Resource + private MinioUtil minioUtil; + + @Value("${minio.bucketName.collectionElement}") + private String collectionElement; + @Value("${minio.bucketName.gradient}") + private String gradientBucketName; + @Value("${minio.bucketName.users}") + private String userBucketName; + @Resource + private RedisUtil redisUtil; + +// @Resource +// private RedisUtil redisUtil; + + @Transactional(rollbackFor = Exception.class) + @Override + public CollectionElementVO upload(CollectionElementUploadDTO uploadDTO) { + long start = System.currentTimeMillis(); + //用户信息 + AuthPrincipalVo userInfo = UserContext.getUserHolder(); + CollectionLevel1TypeEnum level1TypeEnum = CollectionLevel1TypeEnum.uploadOf(uploadDTO.getLevel1Type()); + if (Objects.isNull(level1TypeEnum)) { + throw new BusinessException("unknown.parameter.level1Type"); + } + String objectName = userInfo.getId() + "/" + level1TypeEnum.getRealName(); + String path = minioUtil.upload(collectionElement, objectName, uploadDTO.getFile()); + + String level2Type = null; + if (uploadDTO.getLevel1Type().equals(CollectionLevel1TypeEnum.SKETCH_BOARD.getRealName())){ + if (StringUtil.isNullOrEmpty(uploadDTO.getGender())) { + throw new BusinessException("gender.cannot.be.empty"); + } + level2Type = pythonService.getClothCategory(path,uploadDTO.getGender()); + } + + //保存element元素 + CollectionElement collectionElement = resolveData(uploadDTO, userInfo, path, level2Type); + saveOne(collectionElement); +// if (!StringUtils.isEmpty(uploadDTO.getMoodboardPosition())) { +// redisUtil.saveMoodboardPosition(collectionElement.getId(), uploadDTO.getMoodboardPosition()); +// } + CollectionElementVO collectionElementVO = CopyUtil.copyObject(collectionElement, CollectionElementVO.class); + collectionElementVO.setMinIOPath(collectionElementVO.getUrl()); + collectionElementVO.setUrl(minioUtil.getPreSignedUrl(collectionElementVO.getUrl(), 24 * 60)); + collectionElementVO.setDesignType(DesignTypeEnum.COLLECTION.getRealName()); + + long end = System.currentTimeMillis(); + double floor = Math.floor((double) (end - start) / 1000); + log.info("本次图片上传耗时:{} 毫秒", end - start); + Long incrementCount = redisUtil.getIncrementCount(RedisUtil.UPLOAD_TIMEOUT_REMINDER_COUNTER); + if (floor > 5 && incrementCount < 3) { + // 邮件通知 一天最多通知3次 + log.info("上传超过5秒,发送邮件通知"); + SendEmailUtil.uploadTimeoutReminder(userInfo.getUsername(), String.valueOf(((end - start) / 1000))); + redisUtil.increaseCount(RedisUtil.UPLOAD_TIMEOUT_REMINDER_COUNTER); + } + return collectionElementVO; + } + + private String calculateFileUrl(CollectionLevel1TypeEnum level1TypeEnum, Long userId) { + String rootPath = fileProperties.getSys().getPath(); + String day = DateUtil.dateToStr(new Date(), DateUtil.YYYYMM); + return rootPath + day + "/" + "userFile" + "/collection" + + "/" + level1TypeEnum.getRealName() + "/" + userId + "/" + UUID.randomUUID().toString(); + } + + private CollectionElement resolveData(CollectionElementUploadDTO uploadDTO, AuthPrincipalVo userInfo, File file) { + CollectionElement element = CopyUtil.copyObject(uploadDTO, CollectionElement.class); + element.setAccountId(userInfo.getId()); + element.setCollectionId(0L); + element.setHasPin((byte) 0); + String pictureCollectonName = file.getName(); + //获取图片后缀 + String suffix = pictureCollectonName.substring(pictureCollectonName.lastIndexOf(".")); + //获取图片前缀 + String prefix = pictureCollectonName.substring(0, pictureCollectonName.lastIndexOf(".")); + element.setName(DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD)); + element.setUrl(file.getAbsolutePath()); + //按时区计算 + element.setCreateDate(DateUtil.getByTimeZone(uploadDTO.getTimeZone())); + String linuxDomain = fileProperties.getLinuxDomain(); + if (!StringUtils.isEmpty(linuxDomain)) { + //linux 系统 + String oldPath = fileProperties.getSys().getPath(); + element.setUrl(file.getAbsolutePath().replace(oldPath, linuxDomain)); + } + return element; + } + + private CollectionElement resolveData(CollectionElementUploadDTO uploadDTO, AuthPrincipalVo userInfo, String path, String level2Type) { + CollectionElement element = CopyUtil.copyObject(uploadDTO, CollectionElement.class); + element.setAccountId(userInfo.getId()); + element.setCollectionId(0L); + element.setHasPin((byte) 0); +// String pictureCollectonName = fileName; +// //获取图片后缀 +// String suffix = pictureCollectonName.substring(pictureCollectonName.lastIndexOf(".")); +// //获取图片前缀 +// String prefix = pictureCollectonName.substring(0,pictureCollectonName.lastIndexOf(".")); + String originalFilename = uploadDTO.getFile().getOriginalFilename(); + if (originalFilename != null && originalFilename.contains(".")) { + // 如果文件名包含点号,则去除最后一个点及其后面的内容 + int lastDotIndex = originalFilename.lastIndexOf("."); + if (lastDotIndex != -1) { + originalFilename = originalFilename.substring(0, lastDotIndex); + } + } + element.setName(originalFilename); + element.setUrl(path); + //按时区计算 + element.setCreateDate(DateUtil.getByTimeZone(uploadDTO.getTimeZone())); + element.setLevel2Type(level2Type); +// String linuxDomain = fileProperties.getLinuxDomain(); +// if (!StringUtils.isEmpty(linuxDomain)) { +// //linux 系统 +// String oldPath = fileProperties.getSys().getPath(); +// element.setUrl(file.getAbsolutePath().replace(oldPath, linuxDomain)); +// } + return element; + } + + @Override + public void delete(Long id) { + CollectionElement collectionElement = selectById(id); + if (Objects.isNull(collectionElement)) { + throw new BusinessException("collectionElement.not.found"); + } + minioUtil.deleteObject(collectionElement.getUrl()); + collectionElementMapper.deleteById(id); +// if (!FileUtil.delete(collectionElement.getUrl())) { +// throw new BusinessException("file deletion failed! "); +// } + } + + @Override + public void batchDelete(List ids) { + if (CollectionUtils.isEmpty(ids)) { + return; + } +// QueryWrapper queryWrapper = new QueryWrapper<>(); +// queryWrapper.in("id", ids); +// CollectionElement collectionElement = new CollectionElement(); +// collectionElement.setCollectionId(0L); + collectionElementMapper.deleteBatchIds(ids); + } + + /** 该方法已不再使用 */ + @Deprecated + @Override + public GenerateCollectionItemVO generatePrint(CollectionGeneratePrintDTO generatePrintDTO) { + Long userId = UserContext.getUserHolder().getId(); + String url1 = null; + String url2 = null; + CollectionElement element1 = selectById(generatePrintDTO.getSelect1Id()); + if (Objects.isNull(element1)) { + Library library1 = libraryService.getById(generatePrintDTO.getSelect1Id()); + if (Objects.isNull(library1)) { + throw new BusinessException("select1.file.does.not.exist"); + } + url1 = library1.getUrl(); + } else { + url1 = element1.getUrl(); + } + CollectionElement element2 = selectById(generatePrintDTO.getSelect2Id()); + if (Objects.isNull(element2)) { + Library library2 = libraryService.getById(generatePrintDTO.getSelect2Id()); + if (Objects.isNull(library2)) { + throw new BusinessException("select2.file.does.not.exist"); + } + url2 = library2.getUrl(); + } else { + url2 = element2.getUrl(); + } + List printPath = Arrays.asList(url1, url2); + //调取python 接口 + String generateUrl = pythonService.generatePrint(printPath,userId); + if (StringUtils.isEmpty(generateUrl)) { + throw new BusinessException("generate.interface.exception"); + } + + // 保存合成信息到generate表 + Generate generate = setGenerate(userId, generatePrintDTO.getTimeZone()); + generateService.save(generate); + + // 保存合成后的信息到generateDetail + GenerateDetail generateDetail = setGenerateDetail(generate.getId(), generateUrl, generatePrintDTO.getTimeZone()); + generateDetailMapper.insert(generateDetail); + +// CollectionElement element = resolveData(generateUrl, generatePrintDTO.getTimeZone(), userId); +// if (!this.save(element)) { +// throw new BusinessException("save.collectionElement.failed"); +// } +// CollectionGeneratePrintVO collectionGeneratePrint = CopyUtil.copyObject(element, CollectionGeneratePrintVO.class); +// collectionGeneratePrint.setUrl(minioUtil.getPresignedUrl(generateUrl, 24 * 60)); +// collectionGeneratePrint.setDesignType(DesignTypeEnum.COLLECTION.getRealName()); +// return collectionGeneratePrint; + return new GenerateCollectionItemVO(generateDetail.getId(), + minioUtil.getPreSignedUrl(generateUrl, 24 * 60), + generateDetail.getIsLike().equals((byte) 0) ? Boolean.FALSE : Boolean.TRUE); + } + + @Override + public Boolean savePrint(CollectionSavePrintDTO savePrintDTO) { + //用户信息 + List elements = listByIds(savePrintDTO.getPrintId()); + if (CollectionUtils.isEmpty(elements)) { + throw new BusinessException("collectionElements.not.found"); + } + return saveLibraryByCollectionElement(elements, savePrintDTO.getTimeZone()); + } + + @Override + public Boolean saveLibraryByCollectionElement(List elements, String timeZone) { + if (CollectionUtils.isEmpty(elements)) { + return Boolean.TRUE; + } + //获取已存在相同的library + List md5List = elements.stream().map(CollectionElement::getMd5).collect(Collectors.toList()); + List existsLibrarys = libraryService.getByMD5List(md5List); + if (!CollectionUtils.isEmpty(existsLibrarys)) { + //去重 + List existsMd5Lists = existsLibrarys.stream().map(Library::getMd5).collect(Collectors.toList()); + elements = elements.stream().filter(element -> !existsMd5Lists.contains(element.getMd5())).collect(Collectors.toList()); + } + if (CollectionUtils.isEmpty(elements)) { + //都是重复的 + return Boolean.TRUE; + } + String name = DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD); + List libraryList = CopyUtil.copyList(elements, Library.class, (o, d) -> { + d.setCreateDate(DateUtil.getByTimeZone(timeZone)); + d.setName(name); + d.setId(null); + }); + if (!libraryService.saveBatch(libraryList)) { + throw new BusinessException("batch.save.libraryList.failed"); + } + return Boolean.TRUE; + } + + @Override + public Boolean saveLibraryByCollectionElement(List elements, String timeZone, String modelSex) { + if (CollectionUtils.isEmpty(elements)) { + return Boolean.TRUE; + } + //获取已存在相同的library + List md5List = elements.stream().map(CollectionElement::getMd5).collect(Collectors.toList()); + List existsLibrarys = libraryService.getByMD5List(md5List); + if (!CollectionUtils.isEmpty(existsLibrarys)) { + //去重 + List existsMd5Lists = existsLibrarys.stream().map(Library::getMd5).collect(Collectors.toList()); + elements = elements.stream().filter(element -> !existsMd5Lists.contains(element.getMd5())).collect(Collectors.toList()); + } + if (CollectionUtils.isEmpty(elements)) { + //都是重复的 + return Boolean.TRUE; + } + String name = DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD); + List libraryList = CopyUtil.copyList(elements, Library.class, (o, d) -> { + if (d.getLevel1Type().equals(LibraryLevel1TypeEnum.SKETCH_BOARD.getRealName())) { + d.setLevel3Type(modelSex); +// try { +// libraryService.processSketchBoards(d.getUrl(), d.getLevel2Type()); +// }catch (Exception e) { +// // TODO:暂不处理 +// } + } + d.setCreateDate(DateUtil.getByTimeZone(timeZone)); + d.setName(name); + d.setId(null); + }); + if (!libraryService.saveBatch(libraryList)) { + throw new BusinessException("batch.save.libraryList.failed"); + } + return Boolean.TRUE; + } + + private CollectionElement resolveData(String path, String timeZone, Long userId){ +// File file = new File(path); + + String name = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf(".")); + CollectionElement element = new CollectionElement(); + element.setAccountId(userId); + element.setCollectionId(0L); + element.setName(name); + element.setLevel1Type(CollectionLevel1TypeEnum.PRINT_BOARD.getRealName()); + element.setUrl(path); + element.setHasPin((byte) 0); + try { + element.setMd5(MD5Utils.encryptFile(minioUtil.download(path))); + }catch (Exception e){ + throw new RuntimeException(e); + } + /* catch (MinioException | IOException e) { + throw new RuntimeException(e); + }*/ + + //按时区计算 + element.setCreateDate(DateUtil.getByTimeZone(timeZone)); + return element; + } + + @Override + public ValidateElementVO validateElement(DesignCollectionDTO designDTO) { + ValidateElementVO elementVO = CopyUtil.copyObject(designDTO, ValidateElementVO.class); + List colorBoards = elementVO.getColorBoards(); + for (CollectionColorDTO colorBoard : colorBoards) { + if (Objects.nonNull(colorBoard.getGradient())) { + String colorImg = colorBoard.getGradient().getColorImg(); + String[] parts = colorImg.split(","); + String imageType = parts[0].split("/")[1].split(";")[0]; + String base64Data = parts[1]; + String gradientMinioUrl = minioUtil.uploadImageFromBase64(gradientBucketName, base64Data, imageType); + colorBoard.setGradientMinioUrl(gradientMinioUrl); + colorBoard.getGradient().setColorImg(null); + colorBoard.setGradientString(JSON.toJSONString(colorBoard.getGradient())); + } + } + elementVO.setColorBoards(colorBoards); + List usedElementIds = elementVO.getUsedElementIds(); + List libraryCollectionElements = elementVO.getLibraryCollectionElements(); + List generateCollectionElements = elementVO.getGenerateCollectionElements(); + //校验moodboard + if (CollectionUtil.isNotEmpty(designDTO.getMoodBoards())) { + //校验designType + validateDesignType(designDTO.getMoodBoards(), "moodBoards"); + List moodBoardIds = designDTO.getMoodBoards().stream() + .filter(f -> f.getDesignType().equals(DesignTypeEnum.COLLECTION.getRealName())) + .map(DesignCollectionElementDTO::getId) + .collect(Collectors.toList()); + if (!CollectionUtils.isEmpty(moodBoardIds)) { + List MoodBoardElements = collectionElementMapper.selectBatchIds(moodBoardIds); + if (CollectionUtil.isEmpty(MoodBoardElements) || MoodBoardElements.size() != moodBoardIds.size()) { + throw new BusinessException("get.moodBoards.data.is.mismatch"); + } + elementVO.setMoodBoardElements(MoodBoardElements); + usedElementIds.addAll(moodBoardIds); + } + //library + List libraryIds = designDTO.getMoodBoards().stream() + .filter(f -> f.getDesignType().equals(DesignTypeEnum.LIBRARY.getRealName())) + .map(DesignCollectionElementDTO::getId) + .collect(Collectors.toList()); + if (!CollectionUtils.isEmpty(libraryIds)) { + List librarys = libraryService.getByIds(libraryIds); + //不校验了防止用户在library删除 对应不上 + if (CollectionUtil.isNotEmpty(librarys)) { + libraryCollectionElements.addAll(covertLibrarysToCollections(librarys, null)); + } + } + // generate + List generateIds = designDTO.getMoodBoards().stream() + .filter(o -> o.getDesignType().equals((DesignTypeEnum.GENERATE.getRealName()))) + .map(DesignCollectionElementDTO::getId) + .collect((Collectors.toList())); + if (CollectionUtil.isNotEmpty(generateIds)) { + List generateDetailList = generateDetailMapper.selectBatchIds(generateIds); + if (CollectionUtil.isNotEmpty(generateDetailList)) { + generateCollectionElements.addAll(covertGeneratesToCollections(generateDetailList, null)); + } + } + } + if (CollectionUtil.isNotEmpty(designDTO.getPrintBoards())) { + //校验designType + validateDesignType(CopyUtil.copyList(designDTO.getPrintBoards(), DesignCollectionElementDTO.class), "printBoards"); + List printBoardIds = designDTO.getPrintBoards().stream() + .filter(f -> f.getDesignType().equals(DesignTypeEnum.COLLECTION.getRealName())) + .map(DesignCollectionPrintElementDTO::getId) + .collect(Collectors.toList()); + if (!CollectionUtils.isEmpty(printBoardIds)) { + //校验printboard + List printBoardElements = collectionElementMapper.selectBatchIds(printBoardIds); + if (CollectionUtil.isEmpty(printBoardElements) || printBoardElements.size() != printBoardIds.size()) { + throw new BusinessException("get.printBoards.data.is.mismatch"); + } + elementVO.setPrintBoardElements(printBoardElements); + usedElementIds.addAll(printBoardIds); + } + //library + List libraryIds = designDTO.getPrintBoards().stream() + .filter(f -> f.getDesignType().equals(DesignTypeEnum.LIBRARY.getRealName())) + .map(DesignCollectionPrintElementDTO::getId) + .collect(Collectors.toList()); + if (!CollectionUtils.isEmpty(libraryIds)) { + List librarys = libraryService.getByIds(libraryIds); + //不校验了防止用户在library删除 对应不上 + if (CollectionUtil.isNotEmpty(librarys)) { + Map idToMap = designDTO.getPrintBoards() + .stream() + .collect(Collectors.toMap(DesignCollectionPrintElementDTO::getId, v -> v)); + libraryCollectionElements.addAll(covertLibrarysToPrintCollections(librarys, idToMap)); + } + } + // generate + List generateIds = designDTO.getPrintBoards().stream() + .filter(o -> o.getDesignType().equals((DesignTypeEnum.GENERATE.getRealName()))) + .map(DesignCollectionPrintElementDTO::getId) + .collect((Collectors.toList())); + if (CollectionUtil.isNotEmpty(generateIds)) { + List generateDetailList = generateDetailMapper.selectBatchIds(generateIds); + if (CollectionUtil.isNotEmpty(generateDetailList)) { + Map idToMap = designDTO.getPrintBoards() + .stream() + .collect(Collectors.toMap(DesignCollectionPrintElementDTO::getId, v -> v)); + generateCollectionElements.addAll(covertGeneratesToPrintCollections(generateDetailList, idToMap)); + } + } + } + if (CollectionUtil.isNotEmpty(designDTO.getSketchBoards())) { + //校验PIN是否满足 上衣或者下衣必须不超过8 + long topNum = 0; + long bottomNum = 0; + long outerwearNum = 0; + if (designDTO.getModelSex().equals(Sex.FEMALE.getValue())) { + topNum= designDTO.getSketchBoards().stream() + .filter(skecth -> skecth.getIsPin() == 1 + && DesignPythonItem.DRESS_BLOUSE.contains(skecth.getLevel2Type())).count(); + bottomNum = designDTO.getSketchBoards().stream() + .filter(skecth -> skecth.getIsPin() == 1 + && DesignPythonItem.SKIRT_TROUSERS.contains(skecth.getLevel2Type())).count(); + }else if (designDTO.getModelSex().equals(Sex.MALE.getValue())) { + topNum= designDTO.getSketchBoards().stream() + .filter(skecth -> skecth.getIsPin() == 1 + && DesignPythonItem.TOPS.contains(skecth.getLevel2Type())).count(); + bottomNum = designDTO.getSketchBoards().stream() + .filter(skecth -> skecth.getIsPin() == 1 + && DesignPythonItem.BOTTOMS.contains(skecth.getLevel2Type())).count(); + } + outerwearNum = designDTO.getSketchBoards().stream() + .filter(skecth -> skecth.getIsPin() == 1 + && DesignPythonItem.OUTWEAR.contains(skecth.getLevel2Type())).count(); + if (topNum > 8 || bottomNum > 8 || outerwearNum > 8) { + throw new BusinessException("the.number.of.PIN.top.or.bottom.or.outerwear.sketchBoard.cannot.be.more.than.8", ResultEnum.PROMPT.getCode()); + } + //校验designType + Boolean result = designDTO.getSketchBoards().stream() + .filter(mood -> StringUtils.isEmpty(mood.getDesignType())) + .findFirst().isPresent(); + if (result) { + throw new BusinessException("sketchBoards.designType.cannot.be.empty"); + } + + List sketchBoardIds = designDTO.getSketchBoards().stream() + .filter(f -> f.getDesignType().equals(DesignTypeEnum.COLLECTION.getRealName())) + .map(CollectionSketchDTO::getSketchBoardId) + .collect(Collectors.toList()); + if (!CollectionUtils.isEmpty(sketchBoardIds)) { + //校验sketchBoard + List sketchBoardElements = collectionElementMapper.selectBatchIds(sketchBoardIds); + if (CollectionUtil.isEmpty(sketchBoardElements) || sketchBoardElements.size() != sketchBoardIds.size()) { + throw new BusinessException("get.sketchBoards.data.is.mismatch"); + } + elementVO.setSketchBoardElements(sketchBoardElements); + usedElementIds.addAll(sketchBoardIds); + } + //library + List libraryIds = designDTO.getSketchBoards().stream() + .filter(f -> f.getDesignType().equals(DesignTypeEnum.LIBRARY.getRealName())) + .map(CollectionSketchDTO::getSketchBoardId) + .collect(Collectors.toList()); + if (!CollectionUtils.isEmpty(libraryIds)) { + List librarys = libraryService.getByIds(libraryIds); + //不校验了防止用户在library删除 对应不上 + if (CollectionUtil.isNotEmpty(librarys)) { + Map idToMap = designDTO.getSketchBoards() + .stream() + .collect(Collectors.toMap(CollectionSketchDTO::getSketchBoardId, v -> v)); + libraryCollectionElements.addAll(covertLibrarysToCollections(librarys, idToMap)); + } + } + // generate + List generateIds = designDTO.getSketchBoards().stream() + .filter(o -> o.getDesignType().equals((DesignTypeEnum.GENERATE.getRealName()))) + .map(CollectionSketchDTO::getSketchBoardId) + .collect((Collectors.toList())); + if (CollectionUtil.isNotEmpty(generateIds)) { + List generateDetailList = generateDetailMapper.selectBatchIds(generateIds); + if (CollectionUtil.isNotEmpty(generateDetailList)) { + Map idToMap = designDTO.getSketchBoards() + .stream() + .collect(Collectors.toMap(CollectionSketchDTO::getSketchBoardId, v -> v)); + generateCollectionElements.addAll(covertGeneratesToCollections(generateDetailList, idToMap)); + } + } + } + //校验marketingSketch + // 2023.12版本去掉了这个入参 +// if (CollectionUtil.isNotEmpty(designDTO.getMarketingSketchs())) { +// //校验designType +// validateDesignType(designDTO.getMarketingSketchs(),"marketingSketchs"); +// List printBoardIds = designDTO.getMarketingSketchs().stream() +// .filter(f ->f.getDesignType().equals(DesignTypeEnum.COLLECTION.getRealName())) +// .map(DesignCollectionElementDTO::getId) +// .collect(Collectors.toList()); +// if(!CollectionUtils.isEmpty(printBoardIds)){ +// List marketingSketchElements = collectionElementMapper.selectBatchIds(printBoardIds); +// Assert.isTrue(CollectionUtil.isNotEmpty(marketingSketchElements) +// && marketingSketchElements.size() == printBoardIds.size(), "get marketingSketch data is mismatch"); +// elementVO.setMarketingSketchElements(marketingSketchElements); +// usedElementIds.addAll(printBoardIds); +// } +// //library +// List libraryIds = designDTO.getMarketingSketchs().stream() +// .filter(f ->f.getDesignType().equals(DesignTypeEnum.LIBRARY.getRealName())) +// .map(DesignCollectionElementDTO::getId) +// .collect(Collectors.toList()); +// if(!CollectionUtils.isEmpty(libraryIds)){ +// List librarys = libraryService.getByIds(libraryIds); +// //不校验了防止用户在library删除 对应不上 +// if(CollectionUtil.isNotEmpty(librarys)){ +// libraryCollectionElements.addAll(covertLibrarysToCollections(librarys,null)); +// } +// } +// } + //校验控制生成类型 + SingleOverallEnum singleOverall = SingleOverallEnum.of(designDTO.getSingleOverall()); + if (Objects.isNull(singleOverall)) { + throw new BusinessException("unknown.parameter.singleOverall"); + } + if (SingleOverallEnum.SINGLE.equals(singleOverall)) { + SwitchCategoryEnum switchCategory = SwitchCategoryEnum.of(designDTO.getSwitchCategory()); + if (Objects.isNull(switchCategory)) { + throw new BusinessException("unknown.parameter.switchCategory"); + } + } + // 校验模特 + if (!StringUtils.isEmpty(designDTO.getModelType())) { + if (designDTO.getModelType().equals(ModelType.LIBRARY.getValue())) { + Library byId = libraryService.getById(designDTO.getTemplateId()); + LibraryModelPoint modelPoint = libraryModelPointService.getByRelationId(byId.getId(), designDTO.getModelType()); + elementVO.setDesignLibraryModelPoint(calculateTemplatePointTemplate(modelPoint, byId.getHigh(), byId.getWidth(), byId.getUrl())); + } else if (designDTO.getModelType().equals(ModelType.SYSTEM.getValue())) { + SysFileVO byId = sysFileService.getById(designDTO.getTemplateId()); + if (!StringUtils.isEmpty(byId.getLevel3Type()) && byId.getLevel2Type().equals("Female")) { + elementVO.setStyle(byId.getLevel3Type()); + } + LibraryModelPoint modelPoint = libraryModelPointService.getByRelationId(byId.getId(), designDTO.getModelType()); + elementVO.setDesignLibraryModelPoint(calculateTemplatePointTemplate(modelPoint, 700, 320, byId.getUrl())); + } + } + elementVO.setModelSex(designDTO.getModelSex()); + elementVO.setRequestIdList(designDTO.getRequestIdList()); + if (null != designDTO.getDesignNum()) { + elementVO.setDesignNum(designDTO.getDesignNum()); + }else { + elementVO.setDesignNum(8); + } + return elementVO; + } + + @Override + public DesignLibraryModelPointVO calculateTemplatePoint(LibraryModelPoint modelPoint, Integer high, Integer width, String templateUrl) { + DesignLibraryModelPointVO libraryModelPoint = new DesignLibraryModelPointVO(); + libraryModelPoint.setHandLeft(calculateTemplatePointOne(modelPoint.getHandLeft(), high, width)); + libraryModelPoint.setHandRight(calculateTemplatePointOne(modelPoint.getHandRight(), high, width)); + libraryModelPoint.setShoulderLeft(calculateTemplatePointOne(modelPoint.getShoulderLeft(), high, width)); + libraryModelPoint.setShoulderRight(calculateTemplatePointOne(modelPoint.getShoulderRight(), high, width)); + libraryModelPoint.setWaistbandLeft(calculateTemplatePointOne(modelPoint.getWaistbandLeft(), high, width)); + libraryModelPoint.setWaistbandRight(calculateTemplatePointOne(modelPoint.getWaistbandRight(), high, width)); + libraryModelPoint.setTemplateUrl(templateUrl); + return libraryModelPoint; + } + + @Override + public DesignLibraryModelPointVO calculateTemplatePointTemplate(LibraryModelPoint modelPoint, Integer high, Integer width, String templateUrl) { + DesignLibraryModelPointVO libraryModelPoint = new DesignLibraryModelPointVO(); +// LibraryModelPoint template = libraryModelPointService.getById(96L); +// libraryModelPoint.setHandLeft(calculateTemplatePointOne(template.getHandLeft(),752,564)); +// libraryModelPoint.setHandRight(calculateTemplatePointOne(template.getHandRight(),752,564)); +// libraryModelPoint.setShoulderLeft(calculateTemplatePointOne(template.getShoulderLeft(),752,564)); +// libraryModelPoint.setShoulderRight(calculateTemplatePointOne(template.getShoulderRight(),752,564)); +// libraryModelPoint.setWaistbandLeft(calculateTemplatePointOne(template.getWaistbandLeft(),752,564)); +// libraryModelPoint.setWaistbandRight(calculateTemplatePointOne(template.getWaistbandRight(),752,564)); +// libraryModelPoint.setTemplateUrl("aida-mannequins/model_1693218345.2714432.png"); + libraryModelPoint.setHandLeft(calculateTemplatePointOne(modelPoint.getHandLeft(), high, width)); + libraryModelPoint.setHandRight(calculateTemplatePointOne(modelPoint.getHandRight(), high, width)); + libraryModelPoint.setShoulderLeft(calculateTemplatePointOne(modelPoint.getShoulderLeft(), high, width)); + libraryModelPoint.setShoulderRight(calculateTemplatePointOne(modelPoint.getShoulderRight(), high, width)); + libraryModelPoint.setWaistbandLeft(calculateTemplatePointOne(modelPoint.getWaistbandLeft(), high, width)); + libraryModelPoint.setWaistbandRight(calculateTemplatePointOne(modelPoint.getWaistbandRight(), high, width)); + libraryModelPoint.setTemplateUrl(templateUrl); + return libraryModelPoint; + } + + private List calculateTemplatePointOne(String template, Integer high, Integer width) { + List originRatioList = JSON.parseObject(template, List.class); + originRatioList.set(0, originRatioList.get(0).multiply(BigDecimal.valueOf(width))); + originRatioList.set(1, originRatioList.get(1).multiply(BigDecimal.valueOf(high))); + return originRatioList; + } + + private List covertLibrarysToCollections(List libraries, Map idToMap) { + return CopyUtil.copyList(libraries, CollectionElement.class, (o, d) -> { + if (null != idToMap) { + CollectionSketchDTO sketchDTO = idToMap.get(o.getId()); + d.setLevel2Type(sketchDTO.getLevel2Type()); + d.setHasPin(sketchDTO.getIsPin()); + } + }); + } + + private List covertGeneratesToCollections(List generateDetailList, Map idToMap) { + return CopyUtil.copyList(generateDetailList, CollectionElement.class, (o, d) -> { + Generate byId = generateService.getById(o.getGenerateId()); + d.setAccountId(byId.getAccountId()); + d.setLevel1Type(byId.getLevel1Type()); + d.setCreateDate(Date.from(o.getCreateDate().atZone(ZoneId.systemDefault()).toInstant())); + if (null != idToMap) { + CollectionSketchDTO sketchDTO = idToMap.get(o.getId()); + d.setLevel2Type(sketchDTO.getLevel2Type()); + d.setHasPin(sketchDTO.getIsPin()); + } + }); + } + + private List covertLibrarysToPrintCollections(List libraries, Map idToMap) { + return CopyUtil.copyList(libraries, CollectionElement.class, (o, d) -> { + if (null != idToMap) { + DesignCollectionPrintElementDTO printDTO = idToMap.get(o.getId()); + d.setHasPin(printDTO.getIsPin()); + } + }); + } + + private List covertGeneratesToPrintCollections(List generateDetailList, Map idToMap) { + return CopyUtil.copyList(generateDetailList, CollectionElement.class, (o, d) -> { + Generate byId = generateService.getById(o.getGenerateId()); + d.setAccountId(byId.getAccountId()); + d.setLevel1Type(byId.getLevel1Type()); + if (!StringUtils.isEmpty(byId.getLevel2Type())) { + d.setLevel2Type(byId.getLevel2Type()); + } + d.setCreateDate(Date.from(o.getCreateDate().atZone(ZoneId.systemDefault()).toInstant())); + if (null != idToMap) { + DesignCollectionPrintElementDTO printDTO = idToMap.get(o.getId()); + d.setHasPin(printDTO.getIsPin()); + } + }); + } + + private void validateDesignType(List collectionElements, String msg) { + Boolean result = collectionElements.stream().filter(mood -> StringUtils.isEmpty(mood.getDesignType())).findFirst().isPresent(); + if (result) { + throw new BusinessException(msg + ".designType.cannot.be.empty"); + } + } + + @Override + public void editSketchBoardsElement(ValidateElementVO elementVO, List sketchBoards) { + if (CollectionUtil.isNotEmpty(sketchBoards)) { + List collect = sketchBoards.stream().filter(o -> o.getDesignType().equals(DesignTypeEnum.COLLECTION.getRealName())).collect(Collectors.toList()); + collect.forEach(sketchBoard -> { + CollectionElement collectionElement = CopyUtil.copyObject(sketchBoard, CollectionElement.class); + collectionElement.setHasPin(sketchBoard.getIsPin()); + collectionElement.setId(sketchBoard.getSketchBoardId()); + collectionElementMapper.updateById(collectionElement); + }); + List sketchBoardIds = collect.stream().map(CollectionSketchDTO::getSketchBoardId).collect(Collectors.toList()); + if (!CollectionUtils.isEmpty(sketchBoardIds)) { + List sketchBoardElements = collectionElementMapper.selectBatchIds(sketchBoardIds); + elementVO.setSketchBoardElements(sketchBoardElements); + }else { + elementVO.setSketchBoardElements(new ArrayList<>()); + } + } + } + + @Override + public void editPrintBoardsElement(ValidateElementVO elementVO, List printBoards) { + if (CollectionUtil.isNotEmpty(printBoards)) { + List collect = printBoards.stream().filter(o -> o.getDesignType().equals(DesignTypeEnum.COLLECTION.getRealName())).collect(Collectors.toList()); + collect.forEach(printBoard -> { + CollectionElement collectionElement = CopyUtil.copyObject(printBoard, CollectionElement.class); + collectionElement.setHasPin(Objects.isNull(printBoard.getIsPin()) ? 0 : printBoard.getIsPin()); + collectionElement.setId(printBoard.getId()); + collectionElementMapper.updateById(collectionElement); + }); + List printBoardIds = collect.stream().map(DesignCollectionPrintElementDTO::getId).collect(Collectors.toList()); + if (!CollectionUtils.isEmpty(printBoardIds)) { + List printBoardElements = collectionElementMapper.selectBatchIds(printBoardIds); + elementVO.setPrintBoardElements(printBoardElements); + }else { + elementVO.setPrintBoardElements(new ArrayList<>()); + } + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public void relationCollection(List elementIds, Long collectionId) { + if (CollectionUtils.isEmpty(elementIds) || null == collectionId) { + return; + } + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.lambda().in(CollectionElement::getId, elementIds); + CollectionElement element = new CollectionElement(); + element.setCollectionId(collectionId); + //批量关联 + collectionElementMapper.update(element, queryWrapper); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public List saveColorBoard(List colorBoards, Long collectionId, String timeZone) { + //用户信息 + AuthPrincipalVo userInfo = UserContext.getUserHolder(); + List colorElements = resolveColorData(colorBoards, userInfo, collectionId, timeZone); + if (!this.saveBatch(colorElements)) { + throw new BusinessException("batch.save.colorElements.failed"); + } + return CopyUtil.copyList(colorElements, CollectionElementVO.class); + } + + @Override + public void refreshHistoryData() { + //幂等 + if (!CollectionUtils.isEmpty(tCollectionElementRelationService.getByCollectionId(1083L))) { + return; + } + // 分页数据 + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.orderByAsc("id"); + PageQueryBaseVo pageQuery = new PageQueryBaseVo(); + pageQuery.setPage(1); + pageQuery.setSize(200); + while (true) { + IPage page = getBaseMapper().selectPage( + new Page<>(pageQuery.getPage(), pageQuery.getSize()), queryWrapper); + List list = page.getRecords(); + if (CollectionUtils.isEmpty(list)) { + break; + } + + //保存 + List relations = list.stream().map(element -> + TCollectionElementRelation.builder().elementId(element.getId()) + .collectionId(element.getCollectionId()).createDate(new Date()).build()) + .collect(Collectors.toList()); + tCollectionElementRelationService.saveBatch(relations); + pageQuery.setPage(pageQuery.getPage() + 1); + log.info("refreshHistoryData###process###page###" + pageQuery.getPage()); + } + } + + private List resolveColorData(List colorBoards, AuthPrincipalVo userInfo, Long collectionId, String timeZone) { + List elements = Lists.newArrayList(); + colorBoards.forEach(color -> { + CollectionElement element = new CollectionElement(); + element.setAccountId(userInfo.getId()); + element.setCollectionId(collectionId); + if (StringUtils.isEmpty(color.getName())) { + element.setName(null); + } else { + element.setName(color.getId() + "_" + color.getName() + "_" + color.getTcx()); + } + element.setLevel1Type(CollectionLevel1TypeEnum.COLOR_BOARD.getRealName()); + element.setHasPin((byte) 0); + element.setMd5("0"); + element.setColorRgb(color.getRgbValue()); + //按时区计算 + element.setCreateDate(DateUtil.getByTimeZone(timeZone)); + if (Objects.nonNull(color.getGradient())) { + color.getGradient().setColorImg(null); + } + element.setGradientString(JSON.toJSONString(color.getGradient())); + elements.add(element); + }); + return elements; + } + + @Override + public List getByCollectionId(Long collectionId) { +// List elementIds = tCollectionElementRelationService.getByCollectionId(collectionId); +// if (CollectionUtils.isEmpty(elementIds)) { +// return null; +// } + QueryWrapper queryWrapper = new QueryWrapper<>(); +// queryWrapper.in("id", elementIds); + queryWrapper.lambda().eq(CollectionElement::getCollectionId, collectionId); + return collectionElementMapper.selectList(queryWrapper); + } + + @Override + public List getByOnlyCollectionId(Long collectionId) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("collection_id", collectionId); + return collectionElementMapper.selectList(queryWrapper); + } + + private CollectionElement selectById(Long id) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("id", id); + return collectionElementMapper.selectOne(queryWrapper); + } + + private Boolean exists(Long id) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("id", id); + return collectionElementMapper.exists(queryWrapper); + } + + private boolean saveOne(CollectionElement collectionElement) { + if (collectionElementMapper.insert(collectionElement) <= 0) { + throw new BusinessException("save.collectionElement.failed"); + } + return Boolean.TRUE; + } + + @Override + public CollectionElement editLevel2Type(Long elementId, String level2Type, String designType) { + CollectionElement collectionElement = new CollectionElement(); + + if (!Objects.isNull(elementId)) { + if (!StringUtil.isNullOrEmpty(designType)){ + switch (designType){ + case "collection": + collectionElement = collectionElementMapper.selectById(elementId); + if (StringUtil.isNullOrEmpty(collectionElement.getLevel2Type()) || !(collectionElement.getLevel2Type()).equals(level2Type)) { + collectionElement.setLevel2Type(level2Type); + updateById(collectionElement); + } + break; + case "library": + Library libraryElement = libraryService.getById(elementId); + if (!Objects.isNull(libraryElement)) { + if (StringUtil.isNullOrEmpty(libraryElement.getLevel2Type()) || !(libraryElement.getLevel2Type()).equals(level2Type)){ + libraryElement.setLevel2Type(level2Type); + libraryService.updateById(libraryElement); + } + BeanUtils.copyProperties(libraryElement,collectionElement); + } + break; + } + } else { + log.error("designType cannot be empty"); + throw new BusinessException("element source type cannot be empty!"); + } + }else { + return null; + } + return collectionElement; + } + + @Override + public List getByProjectId(Long projectId) { + QueryWrapper qw = new QueryWrapper<>(); + qw.lambda().eq(CollectionElement::getProjectId, projectId); + List collectionElementList = collectionElementMapper.selectList(qw); + if (CollectionUtils.isEmpty(collectionElementList)) { + return new ArrayList<>(); + } + return collectionElementList; + } + + private Generate setGenerate(Long userId,String timeZone){ + Generate generate = new Generate(); + generate.setAccountId(userId); + generate.setLevel1Type(CollectionLevel1TypeEnum.PRINT_BOARD.getRealName()); + generate.setGenerateType("synthesis"); +// generate.setModelName("Image Synthesis Model"); + generate.setCreateDate(DateUtil.getByTimeZone(timeZone)); + return generate; + } + + private GenerateDetail setGenerateDetail(Long generateId, String url, String timeZone){ + GenerateDetail generateDetail = new GenerateDetail(); + generateDetail.setGenerateId(generateId); + generateDetail.setUrl(url); + String md5; + try { + md5 = MD5Utils.encryptFile(minioUtil.download(url)); + } catch (Exception e){ + throw new RuntimeException(e); + }/*catch (MinioException | IOException e) { + throw new RuntimeException(e); + }*/ + // 通过MD5来确认当前图片是否有被like过,避免重复like + List> libraryIds = generateDetailMapper.getLibraryIdThroughMD5(md5, CollectionLevel1TypeEnum.PRINT_BOARD.getRealName()); + if (libraryIds.isEmpty()){ + generateDetail.setIsLike((byte) 0); + }else { + generateDetail.setIsLike((byte) 1); + generateDetail.setLibraryId(libraryIds.get(0).get("library_id")); + } + generateDetail.setMd5(md5); + generateDetail.setCreateDate(LocalDateTime.now()); + + return generateDetail; + } + + // 对于上传图片或者从library选择的图片进行图片分割 + public List selectedImageSeg(List files, Long id, String type) { + Long accountId = UserContext.getUserHolder().getId(); + List resp = new ArrayList<>(); + List imageDates = new ArrayList<>(); + + boolean isUploadMode = !files.isEmpty(); + Library library = null; + + // 判断是否是上传的图片 + if (isUploadMode) { + String objectName = accountId + "/ImageSegment/input"; + for (MultipartFile file : files) { + String md5 = MD5Utils.encryptFile(file); + String segmentedResult = redisUtil.getFromString(RedisUtil.IMAGE_SEGMENTATION + md5); + // 判断上传的图片是否有已分割的数据 + if (StringUtil.isNullOrEmpty(segmentedResult)) { + String path = minioUtil.upload(userBucketName, objectName, file); + ImageSegmentation.ImageDate imageDate = new ImageSegmentation().new ImageDate(); + imageDate.setImage_url(path); + imageDate.setImage_type(type); + imageDates.add(imageDate); + } else { + ImageSegmentation.ImageDate imageData = JSONObject.parseObject(segmentedResult, ImageSegmentation.ImageDate.class); + resp.add(createCollectionElementVO(accountId, null, null, imageData.getImage_url(), imageData.getClothing_url())); + } + } + } else if (Objects.nonNull(id)) { + library = libraryService.getById(id); + // 判断从library中选择的图片是否有分割数据 + if (StringUtil.isNullOrEmpty(library.getSegmentedData())) { + ImageSegmentation.ImageDate imageDate = new ImageSegmentation().new ImageDate(); + imageDate.setImage_url(library.getUrl()); + imageDate.setImage_type(type); + imageDates.add(imageDate); + } else { + List restoredList = Arrays.asList(library.getSegmentedData().split(",")); + resp.add(createCollectionElementVO(accountId, id, library.getLevel1Type(), library.getUrl(), restoredList)); + } + } + + // 处理需要分割的图片 + if (!imageDates.isEmpty()) { + // 准备图片分割的参数 + ImageSegmentation imageSegmentation = new ImageSegmentation(); + imageSegmentation.setUser_id(accountId); + imageSegmentation.setImage_data(imageDates); + // 图片分割 + List segmented = pythonService.imageSegmentation(imageSegmentation); + // 处理图片分割结果 + for (ImageSegmentation.ImageDate imageData : segmented) { + if (isUploadMode) { + // 上传的图片需要添加到redis中存一天 + String key = RedisUtil.IMAGE_SEGMENTATION + + MD5Utils.encryptFile + (minioUtil.getPreSignedUrl + (imageData.getImage_url(), CommonConstant.MINIO_IMAGE_EXPIRE_TIME), false); + redisUtil.addToString(key, new Gson().toJson(imageData), CommonConstant.GENERATE_RESULT_EXPIRE_TIME); + resp.add(createCollectionElementVO(accountId, null, null, imageData.getImage_url(), imageData.getClothing_url())); + } else { + // 从library中选择的图片需要更新数据库中对应图片的分割数据 + String segmentedData = String.join(",", imageData.getClothing_url()); + library.setSegmentedData(segmentedData); + library.setUpdateDate(new Date()); + libraryService.updateById(library); + resp.add(createCollectionElementVO(accountId, id, library.getLevel1Type(), library.getUrl(), imageData.getClothing_url())); + } + } + } + return resp; + } + + // 准备返回数据 + private CollectionElementVO createCollectionElementVO(Long accountId, Long id, String level1Type, + String imageUrl, List clothingUrls) { + CollectionElementVO vo = new CollectionElementVO(); + vo.setAccountId(accountId); + vo.setId(id); + vo.setLevel1Type(level1Type); + vo.setUrl(minioUtil.getPreSignedUrl(imageUrl, CommonConstant.MINIO_IMAGE_EXPIRE_TIME)); + vo.setMinIOPath(imageUrl); + + List segUrls = new ArrayList<>(); + for (String seg : clothingUrls) { + segUrls.add(minioUtil.getPreSignedUrl(seg, CommonConstant.MINIO_IMAGE_EXPIRE_TIME)); + } + vo.setSegmentedImages(segUrls); + return vo; + } + +} diff --git a/src/main/java/com/ai/da/service/impl/ConvenientInquiryServiceImpl.java b/src/main/java/com/ai/da/service/impl/ConvenientInquiryServiceImpl.java index 8e92d0a8..00192bc7 100644 --- a/src/main/java/com/ai/da/service/impl/ConvenientInquiryServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/ConvenientInquiryServiceImpl.java @@ -5,14 +5,14 @@ import com.ai.da.common.constant.CommonConstant; import com.ai.da.common.context.UserContext; import com.ai.da.common.enums.CreditsEventsEnum; import com.ai.da.common.response.PageBaseResponse; +import com.ai.da.common.response.ResultEnum; import com.ai.da.common.utils.CopyUtil; import com.ai.da.common.utils.DateUtil; import com.ai.da.mapper.primary.*; import com.ai.da.mapper.primary.entity.Account; import com.ai.da.mapper.primary.entity.Questionnaire; import com.ai.da.mapper.primary.entity.TrialOrder; -import com.ai.da.model.dto.AccountAddDTO; -import com.ai.da.model.dto.QueryPaymentInfoDTO; +import com.ai.da.model.dto.*; import com.ai.da.model.enums.Language; import com.ai.da.model.vo.*; import com.ai.da.service.*; @@ -41,6 +41,7 @@ import java.math.BigDecimal; import java.math.RoundingMode; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; +import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; @@ -68,10 +69,15 @@ public class ConvenientInquiryServiceImpl extends ServiceImpl ADMIN_IDS = Arrays.asList(4L, 6L, 31L, 73L, 83L, 87L); + private static final List ADMIN_IDS_READ_ONLY = Arrays.asList(12592L, 12201L); + public IPage getTrial(QueryUserConditionsVO queryUserConditionsVO) { log.info("getTrial parameter : {},page:{}, size:{}", queryUserConditionsVO, queryUserConditionsVO.getPage(), queryUserConditionsVO.getSize()); /* 添加按条件查询试用用户 */ @@ -122,6 +128,46 @@ public class ConvenientInquiryServiceImpl extends ServiceImpl trialOrders = trialOrderMapper.selectList(null); } + public List getDesignStatistic(String startTime, String endTime, List ids, + String email) { + Long accountId = UserContext.getUserHolder().getId(); + Account account = accountService.getById(accountId); + // 允许查看数据的用户id + if (Objects.nonNull(account.getSystemUser()) + && (account.getSystemUser().equals(5) + || account.getSystemUser().equals(7) + || ADMIN_IDS.contains(account.getId()) + || ADMIN_IDS_READ_ONLY.contains(account.getId()) + )) { + if (StringUtil.isNullOrEmpty(startTime)) startTime = "2024-02-01 00:00:00"; + if (StringUtil.isNullOrEmpty(endTime)) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); + Date date = new Date(); + endTime = simpleDateFormat.format(date); + } + if (!StringUtil.isNullOrEmpty(email)){ + email = email.trim(); + } + String role; + switch (account.getSystemUser()){ + case 5: + role = "corp"; + break; + case 7: + role = "edu"; + break; + case 1: + role = "prsn"; + break; + default: + throw new BusinessException("Sorry, you don't have permission", ResultEnum.PROMPT.getCode()); + } + return designMapper.getDesignStatistic(startTime, endTime, ids, email, role); + } else { + throw new BusinessException("Sorry, you don't have permission", ResultEnum.PROMPT.getCode()); + } + } + public QuestionnaireFeedbackVO getQuestionnaireInfo() { String title = "AiDA_3.0 Feedback Survey--06/2024"; @@ -802,4 +848,61 @@ public class ConvenientInquiryServiceImpl extends ServiceImpl getGenerateFrequency(AccountCreditsUsageQueryDTO queryDTO){ + Long accountId = UserContext.getUserHolder().getId(); + Account account = accountService.getById(accountId); + // 允许查看数据的用户id + if (Objects.nonNull(account.getSystemUser()) + && (account.getSystemUser().equals(5) + || account.getSystemUser().equals(7) + || ADMIN_IDS.contains(account.getId()) + || ADMIN_IDS_READ_ONLY.contains(account.getId()) + )) { + boolean groupByEvent = !StringUtil.isNullOrEmpty(queryDTO.getChangeEvent()); + String role; + switch (account.getSystemUser()){ + case 5: + role = "corp"; + break; + case 7: + role = "edu"; + break; + case 1: + role = "prsn"; + break; + default: + throw new BusinessException("Sorry, you don't have permission"); + } + Integer size = queryDTO.getSize(); + int offset = (queryDTO.getPage() - 1) * size; + List creditsUsageDTOS = accountMapper.selectCreditUsage( + groupByEvent, queryDTO.getChangeEvent(), role, queryDTO.getUserEmail(), queryDTO.getId(), + queryDTO.getStartTime(), queryDTO.getEndTime(), size, offset); + if (!creditsUsageDTOS.isEmpty()){ + int total = accountMapper.countCreditUsage( + groupByEvent, queryDTO.getChangeEvent(), role, queryDTO.getUserEmail(), queryDTO.getId(), + queryDTO.getStartTime(), queryDTO.getEndTime()); + // 总页数 + double totalPage = Math.ceil((double) total / size); + // 组装返回参数 + PageBaseResponse response = new PageBaseResponse<>(); + response.setContent(creditsUsageDTOS); + response.setPage(queryDTO.getPage()); + response.setSize(size); + response.setTotal(total); + response.setPages((long) totalPage); + return response; + }else { + return new PageBaseResponse<>(); + } + }else { + throw new BusinessException("Sorry, you don't have permission"); + } + } + } diff --git a/src/main/resources/mapper/primary/AccountMapper.xml b/src/main/resources/mapper/primary/AccountMapper.xml index c1155b88..c41ba29d 100644 --- a/src/main/resources/mapper/primary/AccountMapper.xml +++ b/src/main/resources/mapper/primary/AccountMapper.xml @@ -29,5 +29,106 @@ where id = #{id} + + + + + diff --git a/src/main/resources/mapper/primary/DesignMapper.xml b/src/main/resources/mapper/primary/DesignMapper.xml index 50cd460c..34c86c92 100644 --- a/src/main/resources/mapper/primary/DesignMapper.xml +++ b/src/main/resources/mapper/primary/DesignMapper.xml @@ -34,8 +34,19 @@ from t_account a left join t_design b on a.id = b.account_id + + + a.system_user IN (5, 6) + + + a.system_user IN (7, 8) + + + a.system_user IN (0, 1, 2, 3, 4) + + - b.create_date between #{startTime} and #{endTime} + AND b.create_date between #{startTime} and #{endTime} and b.create_date not like '%:01' @@ -52,17 +63,6 @@ GROUP BY b.account_id ORDER BY b.account_id asc) d left join trial_order c on d.user_email = c.email -