diff --git a/src/main/java/com/ai/da/common/RabbitMQ/MQConfig.java b/src/main/java/com/ai/da/common/RabbitMQ/MQConfig.java index 337f12dd..b6565c86 100644 --- a/src/main/java/com/ai/da/common/RabbitMQ/MQConfig.java +++ b/src/main/java/com/ai/da/common/RabbitMQ/MQConfig.java @@ -12,23 +12,26 @@ public class MQConfig { // public static final String GENERATE_QUEUE = "generate-queue-test"; // ================================================================== // public static final String GENERATE_QUEUE = "generate-queue-local"; -// public static final String GENERATE_QUEUE = "generate-queue-dev"; - public static final String GENERATE_QUEUE = "generate-queue-prod"; + public static final String GENERATE_QUEUE = "generate-queue-dev"; +// public static final String GENERATE_QUEUE = "generate-queue-prod"; // // public static final String SR_QUEUE = "SR-queue-local"; -// public static final String SR_QUEUE = "SR-queue-dev"; - public static final String SR_QUEUE = "SR-queue-prod"; + public static final String SR_QUEUE = "SR-queue-dev"; +// public static final String SR_QUEUE = "SR-queue-prod"; // // public static final String SR_RESULT_QUEUE = "SuperResolution-local"; -// public static final String SR_RESULT_QUEUE = "SuperResolution-dev"; - public static final String SR_RESULT_QUEUE = "SuperResolution-prod"; + public static final String SR_RESULT_QUEUE = "SuperResolution-dev"; +// public static final String SR_RESULT_QUEUE = "SuperResolution-prod"; // // public static final String GENERATE_RESULT_QUEUE = "GenerateImage-local"; - public static final String GENERATE_RESULT_QUEUE = "GenerateImage-prod"; + public static final String GENERATE_RESULT_QUEUE = "GenerateImage-dev"; +// public static final String GENERATE_RESULT_QUEUE = "GenerateImage-prod"; - public static final String TO_PRODUCT_IMAGE_RESULT_QUEUE = "ToProductImage-prod"; + public static final String TO_PRODUCT_IMAGE_RESULT_QUEUE = "ToProductImage-dev"; +// public static final String TO_PRODUCT_IMAGE_RESULT_QUEUE = "ToProductImage-prod"; - public static final String RELIGHT_RESULT_QUEUE = "Relight-prod"; + public static final String RELIGHT_RESULT_QUEUE = "Relight-dev"; +// public static final String RELIGHT_RESULT_QUEUE = "Relight-prod"; public MQConfig() { } diff --git a/src/main/java/com/ai/da/common/config/MyTaskScheduler.java b/src/main/java/com/ai/da/common/config/MyTaskScheduler.java index 69f2ffd9..df7d8677 100644 --- a/src/main/java/com/ai/da/common/config/MyTaskScheduler.java +++ b/src/main/java/com/ai/da/common/config/MyTaskScheduler.java @@ -49,7 +49,7 @@ public class MyTaskScheduler { // 定时任务,每十五天执行一次 // @Scheduled(cron = "0 0 0 ? * MON") - @Scheduled(cron = "0 0 0 */15 * ?") +// @Scheduled(cron = "0 0 0 */15 * ?") public void checkExpiry() { // 检测正式用户是否快要过期 QueryWrapper qw = new QueryWrapper<>(); @@ -83,7 +83,7 @@ public class MyTaskScheduler { } } } - @Scheduled(cron = "0 0 8 * * ?") +// @Scheduled(cron = "0 0 8 * * ?") public void sendTrialOrderExcelToManagements() { // 获取前一天日期 LocalDate yesterday = LocalDate.now().minusDays(1); diff --git a/src/main/java/com/ai/da/common/task/AccountTask.java b/src/main/java/com/ai/da/common/task/AccountTask.java index 0151665d..9e232d83 100644 --- a/src/main/java/com/ai/da/common/task/AccountTask.java +++ b/src/main/java/com/ai/da/common/task/AccountTask.java @@ -24,14 +24,14 @@ public class AccountTask { accountService.refreshCreditsWeekly(); } - @Scheduled(cron = "0 */5 * * * *") // Run every 5 minutes +// @Scheduled(cron = "0 */5 * * * *") // Run every 5 minutes public void getPaidUser(){ // 获取code-create 表中 指定日期之后 订单状态为wc-processing的订单 accountService.extendValidityForCC(); } // 每天凌晨0点执行一次 -// @Scheduled(cron = "0 0 0 * * ?") + @Scheduled(cron = "0 0 0 * * ?") public void cancelActivityBenefits(){ // 1、查询当前所有参与了活动且过期的用户 List accountList = accountService.getExpiredUserBySystemUser(4); @@ -44,7 +44,7 @@ public class AccountTask { } // 每天检测正式用户到期情况,每天凌晨0点执行 -// @Scheduled(cron = "0 0 0 * * ?") + @Scheduled(cron = "0 0 0 * * ?") public void paidUserToVisitor(){ // 1、查询当前已过期正式用户或试用用户 List accountList = accountService.getExpiredUserBySystemUser(1); diff --git a/src/main/java/com/ai/da/common/task/AliPayTask.java b/src/main/java/com/ai/da/common/task/AliPayTask.java index 670a417c..f099752e 100644 --- a/src/main/java/com/ai/da/common/task/AliPayTask.java +++ b/src/main/java/com/ai/da/common/task/AliPayTask.java @@ -24,7 +24,7 @@ public class AliPayTask { /** * 从第0秒开始每隔30秒执行1次,查询创建超过5分钟,并且未支付的订单 */ -// @Scheduled(cron = "0/30 * * * * ?") + @Scheduled(cron = "0/30 * * * * ?") public void orderConfirm(){ // log.info("Alipay orderConfirm 被执行......"); diff --git a/src/main/java/com/ai/da/controller/ConvenientInquiryController.java b/src/main/java/com/ai/da/controller/ConvenientInquiryController.java index 93c00239..119baa5a 100644 --- a/src/main/java/com/ai/da/controller/ConvenientInquiryController.java +++ b/src/main/java/com/ai/da/controller/ConvenientInquiryController.java @@ -4,65 +4,65 @@ package com.ai.da.controller; import com.ai.da.common.context.UserContext; import com.ai.da.common.response.Response; import com.ai.da.mapper.primary.DesignMapper; -import com.ai.da.mapper.primary.TrialOrderMapper; +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.UserDesignStatisticDTO; import com.ai.da.model.vo.QuestionnaireFeedbackVO; import com.ai.da.model.vo.QuestionnaireVO; +import com.ai.da.model.vo.QueryUserConditionsVO; import com.ai.da.service.ConvenientInquiryService; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import io.netty.util.internal.StringUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.*; +import javax.annotation.Nullable; import javax.annotation.Resource; +import javax.validation.Valid; import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; +import java.util.*; @Api(tags = "便利查询") @Slf4j @RestController @RequestMapping("/api/inquiry") public class ConvenientInquiryController { - - @Resource - private TrialOrderMapper trialOrderMapper; - @Resource private DesignMapper designMapper; - @Resource private ConvenientInquiryService convenientInquiryService; @ApiOperation("获取当前所有试用用户") - @GetMapping("/getTrial") - public Response> getTrial(){ + @PostMapping("/getTrial") + public Response> getTrial(@Valid @RequestBody QueryUserConditionsVO queryUserConditionsVO) { Long accountId = UserContext.getUserHolder().getId(); - if (accountId.equals(31L) || accountId.equals(87L) || accountId.equals(83L) || accountId.equals(6L) || accountId.equals(4L) || accountId.equals(73L)){ - List trialOrders = trialOrderMapper.selectList(null); - return Response.success(trialOrders); - }else { + if (accountId.equals(31L) || accountId.equals(87L) || accountId.equals(83L) || accountId.equals(6L) || accountId.equals(4L) || accountId.equals(73L)) { + return Response.success(convenientInquiryService.getTrial(queryUserConditionsVO)); + } else { return Response.fail("Sorry, you don't have permission"); } } @ApiOperation("获取指定时间区间内所有用户design的使用情况") @GetMapping("/getDesignStatistic") - public Response> getDesignStatistic(@RequestParam String startTime,@RequestParam String endTime){ + public Response> getDesignStatistic(@RequestParam String startTime, @RequestParam String endTime) { Long accountId = UserContext.getUserHolder().getId(); - if (accountId.equals(31L) || accountId.equals(87L) || accountId.equals(83L) || accountId.equals(6L) || accountId.equals(4L) || accountId.equals(73L)){ + if (accountId.equals(31L) || accountId.equals(87L) || accountId.equals(83L) || accountId.equals(6L) || accountId.equals(4L) || accountId.equals(73L)) { if (StringUtil.isNullOrEmpty(startTime)) startTime = "2024-02-01 00:00:00"; - if (StringUtil.isNullOrEmpty(endTime)){ + if (StringUtil.isNullOrEmpty(endTime)) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date date = new Date(); endTime = simpleDateFormat.format(date); } List designStatistic = designMapper.getDesignStatistic(startTime, endTime); return Response.success(designStatistic); - }else { + } else { return Response.fail("Sorry, you don't have permission"); } } @@ -71,14 +71,94 @@ public class ConvenientInquiryController { //调查问卷 @ApiOperation("获取调查问卷统计详情") @GetMapping("/getQuestionnaireStatistic") - public Response getQuestionnaire(){ + public Response getQuestionnaire() { return Response.success(convenientInquiryService.getQuestionnaireInfo()); } @ApiOperation("获取所有调查问卷") @GetMapping("/getAllQuestionnaire") - public Response> getAllQuestionnaire(){ + public Response> getAllQuestionnaire() { return Response.success(convenientInquiryService.getAllQuestionnaire()); } + @ApiOperation("获取近期新用户") + @PostMapping("/recentNewUser") + public Response> recentNewUser(@Valid @RequestBody QueryUserConditionsVO queryUserConditionsVO) { + return Response.success(convenientInquiryService.recentNewUser(queryUserConditionsVO)); + } + + @ApiOperation("获取近期新用户图表数据") + @GetMapping("/recentNewUserChart") + public Response> recentNewUserChart(@ApiParam(value = "startTime") @RequestParam @Nullable String startTime, + @ApiParam(value = "endTime") @RequestParam @Nullable String endTime, + @ApiParam("userType") @RequestParam Integer userType) { + return Response.success(convenientInquiryService.recentNewUserChart(startTime, endTime, userType)); + } + + @ApiOperation("获取近期活跃用户") + @PostMapping("/recentActiveUser") + public Response> recentActiveUser(@Valid @RequestBody QueryUserConditionsVO queryUserConditionsVO) { + return Response.success(convenientInquiryService.recentActiveUser(queryUserConditionsVO)); + } + + @ApiOperation("获取近期活跃用户图表数据") + @GetMapping("/recentActiveUserChart") + public Response recentActiveUserChart(@ApiParam(value = "startTime") @RequestParam @Nullable String startTime, + @ApiParam(value = "endTime") @RequestParam @Nullable String endTime) { + return Response.success(convenientInquiryService.recentActiveUserChart(startTime, endTime)); + } + + @ApiOperation("获取用户的各模块功能使用详情") + @GetMapping("/getActiveUserFunc") + public Response>> getActiveUserFunc(@ApiParam(value = "startTime") @RequestParam @Nullable String startTime, + @ApiParam(value = "endTime") @RequestParam @Nullable String endTime, + @ApiParam("userIdList") @RequestParam @Nullable List userIdList) { + return Response.success(convenientInquiryService.getActiveUserFunc(startTime, endTime, userIdList)); + } + + @ApiOperation("试用用户到正式用户的转化率") + @GetMapping("/conversionRate") + public Response> conversionRate() { + return Response.success(convenientInquiryService.conversionRate()); + } + + @ApiOperation("试用用户国家/城市分布") + @GetMapping("/trialUserCountry") + public Response>> trialUserCountry() { + return Response.success(convenientInquiryService.trialUserCountry()); + } + + @ApiOperation("添加用户") + @PostMapping("/addUser") + public Response addUser(@Valid @RequestBody AccountAddDTO accountAddDTO) { + return Response.success(convenientInquiryService.addUser(accountAddDTO)); + } + + @ApiOperation("修改用户信息") + @PostMapping("/modifyUser") + public Response modifyUser(@ApiParam(value = "用户id") @RequestParam @Nullable Long accountId, + @ApiParam(value = "有效期截止时间的毫秒级unix格式") @RequestParam @Nullable Long validEndTime, + @ApiParam(value = "用户类型 1/2/3/0 -> yearly/monthly/trial/visitor") @RequestParam @Nullable Integer systemUser, + @ApiParam("积分") @RequestParam @Nullable Long credits) { + return Response.success(convenientInquiryService.modifyUser(accountId, validEndTime, systemUser, credits)); + } + + @ApiOperation("获取用户信息") + @PostMapping("/getUserInfo") + public Response> getUserInfo(@Valid @RequestBody QueryUserConditionsVO queryUserConditionsVO) { + Long accountId = UserContext.getUserHolder().getId(); + if (accountId.equals(31L) || accountId.equals(87L) || accountId.equals(83L) || accountId.equals(6L) || accountId.equals(4L) || accountId.equals(73L)) { + return Response.success(convenientInquiryService.getUserInfo(queryUserConditionsVO)); + } else { + return Response.fail("Sorry, you don't have permission"); + } + } + + @ApiOperation("获取所有用户id") + @GetMapping("/getAllUserId") + public Response>> getAllUsrIdList() { + return Response.success(convenientInquiryService.getAllUserIdList()); + } + + } diff --git a/src/main/java/com/ai/da/mapper/primary/GenerateMapper.java b/src/main/java/com/ai/da/mapper/primary/GenerateMapper.java index 9da22dbb..a5c6c7cb 100644 --- a/src/main/java/com/ai/da/mapper/primary/GenerateMapper.java +++ b/src/main/java/com/ai/da/mapper/primary/GenerateMapper.java @@ -3,5 +3,10 @@ package com.ai.da.mapper.primary; import com.ai.da.common.config.mybatis.plus.CommonMapper; import com.ai.da.mapper.primary.entity.Generate; +import java.util.List; +import java.util.Map; + public interface GenerateMapper extends CommonMapper { + + List> getByTypeAndTime(String startTime, String endTime, List accountIdList); } diff --git a/src/main/java/com/ai/da/mapper/primary/ToProductImageResultMapper.java b/src/main/java/com/ai/da/mapper/primary/ToProductImageResultMapper.java index 74163ae4..601c1381 100644 --- a/src/main/java/com/ai/da/mapper/primary/ToProductImageResultMapper.java +++ b/src/main/java/com/ai/da/mapper/primary/ToProductImageResultMapper.java @@ -3,5 +3,10 @@ package com.ai.da.mapper.primary; import com.ai.da.common.config.mybatis.plus.CommonMapper; import com.ai.da.mapper.primary.entity.ToProductImageResult; +import java.util.List; +import java.util.Map; + public interface ToProductImageResultMapper extends CommonMapper { + + List> getByTypeAndTime(String startTime, String endTime, List accountIdList); } diff --git a/src/main/java/com/ai/da/mapper/primary/TrialOrderMapper.java b/src/main/java/com/ai/da/mapper/primary/TrialOrderMapper.java index 39def53f..65709299 100644 --- a/src/main/java/com/ai/da/mapper/primary/TrialOrderMapper.java +++ b/src/main/java/com/ai/da/mapper/primary/TrialOrderMapper.java @@ -3,6 +3,8 @@ package com.ai.da.mapper.primary; import com.ai.da.common.config.mybatis.plus.CommonMapper; import com.ai.da.mapper.primary.entity.TrialOrder; +import java.util.Map; + /** * Mapper 接口 * @@ -11,6 +13,8 @@ import com.ai.da.mapper.primary.entity.TrialOrder; */ public interface TrialOrderMapper extends CommonMapper { + Map countOfficialUser(); + } diff --git a/src/main/java/com/ai/da/mapper/primary/entity/Account.java b/src/main/java/com/ai/da/mapper/primary/entity/Account.java index ac09310e..8e39896b 100644 --- a/src/main/java/com/ai/da/mapper/primary/entity/Account.java +++ b/src/main/java/com/ai/da/mapper/primary/entity/Account.java @@ -3,6 +3,7 @@ package com.ai.da.mapper.primary.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; @@ -69,11 +70,13 @@ public class Account implements Serializable { /** * 创建时间 */ + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8") private Date createDate; /** * 更新时间 */ + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8") private Date updateDate; private Integer isTrial; diff --git a/src/main/java/com/ai/da/mapper/primary/entity/TrialOrder.java b/src/main/java/com/ai/da/mapper/primary/entity/TrialOrder.java index 0e908b59..ea7a9118 100644 --- a/src/main/java/com/ai/da/mapper/primary/entity/TrialOrder.java +++ b/src/main/java/com/ai/da/mapper/primary/entity/TrialOrder.java @@ -3,6 +3,7 @@ package com.ai.da.mapper.primary.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; +import com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; @@ -49,11 +50,13 @@ public class TrialOrder implements Serializable { /** * 创建时间 */ + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8") private LocalDateTime createTime; /** * 更新时间 */ + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8") private LocalDateTime updateTime; diff --git a/src/main/java/com/ai/da/model/vo/QueryUserConditionsVO.java b/src/main/java/com/ai/da/model/vo/QueryUserConditionsVO.java new file mode 100644 index 00000000..37422556 --- /dev/null +++ b/src/main/java/com/ai/da/model/vo/QueryUserConditionsVO.java @@ -0,0 +1,38 @@ +package com.ai.da.model.vo; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.util.List; + +@EqualsAndHashCode(callSuper = true) +@Data +@ApiModel("按条件筛选试用用户") +public class QueryUserConditionsVO extends PageQueryBaseVo { + + + private List ids; + + private String userName; + + private String email; + + private String country; + + private String occupation; + + private String startTime; + + private String endTime; + + @ApiModelProperty("Ascending(升序) || Descending(降序)") + private String order; + + // by id | time | credits + private String orderBy; + + private Integer systemUser; + +} diff --git a/src/main/java/com/ai/da/service/AccountLoginLogService.java b/src/main/java/com/ai/da/service/AccountLoginLogService.java index 575f5e69..f1a4bf06 100644 --- a/src/main/java/com/ai/da/service/AccountLoginLogService.java +++ b/src/main/java/com/ai/da/service/AccountLoginLogService.java @@ -30,4 +30,12 @@ public interface AccountLoginLogService extends IService { */ List getByUserId(Long AccountId); + /** + * 查询指定时间区间内的登录用户 + * @param startTime 开始时间 + * @param endTime 结束时间 + * @return 登录用户id + */ + List getByDate(String startTime, String endTime); + } diff --git a/src/main/java/com/ai/da/service/AccountService.java b/src/main/java/com/ai/da/service/AccountService.java index 14ba9d77..a6a39011 100644 --- a/src/main/java/com/ai/da/service/AccountService.java +++ b/src/main/java/com/ai/da/service/AccountService.java @@ -10,6 +10,7 @@ import com.baomidou.mybatisplus.extension.service.IService; import javax.servlet.http.HttpServletRequest; import java.util.List; +import java.util.Map; /** * 服务类 @@ -149,4 +150,11 @@ public interface AccountService extends IService { void toVisitor(Account account); List setUserValidToDayEnd(); + + IPage getPageByDateAndUserType(String startTime, String endTime, Integer type, int pageNum, int size); + + Map getByDateAndUserType(String startTime, String endTime, Integer type); + + IPage getPageByIds(List ids, int pageNum, int size); + List getByIds(List ids); } diff --git a/src/main/java/com/ai/da/service/ChatRobotService.java b/src/main/java/com/ai/da/service/ChatRobotService.java index 1deaa19d..2475c0ee 100644 --- a/src/main/java/com/ai/da/service/ChatRobotService.java +++ b/src/main/java/com/ai/da/service/ChatRobotService.java @@ -1,12 +1,15 @@ package com.ai.da.service; +import com.ai.da.mapper.primary.entity.ChatRobot; import com.ai.da.mapper.primary.entity.Library; import com.ai.da.model.dto.ChatFlushDTO; import com.ai.da.model.dto.ChatRobotLibraryDTO; import com.ai.da.model.dto.ChatSendDTO; import com.ai.da.model.vo.ChatRobotVO; +import com.baomidou.mybatisplus.extension.service.IService; import java.math.BigDecimal; +import java.util.List; /** * @author aida @@ -15,7 +18,7 @@ import java.math.BigDecimal; * @description 对话机器人服务接口 * @date 2023/7/25 16:42:18 */ -public interface ChatRobotService { +public interface ChatRobotService extends IService { ChatRobotVO sendMessageToChatRobot(ChatSendDTO chatSendDTO); String chatBufferFlush(ChatFlushDTO chatFlushDTO); @@ -23,4 +26,6 @@ public interface ChatRobotService { Library pictureLikeOrUnLike(ChatRobotLibraryDTO chatRobotLibraryDTO); BigDecimal getBloodBars(Long userId); + + Long getCountByUserAndTime(String startTime, String endTime, List accountIds); } diff --git a/src/main/java/com/ai/da/service/ConvenientInquiryService.java b/src/main/java/com/ai/da/service/ConvenientInquiryService.java index 30bffc86..49424df6 100644 --- a/src/main/java/com/ai/da/service/ConvenientInquiryService.java +++ b/src/main/java/com/ai/da/service/ConvenientInquiryService.java @@ -1,15 +1,46 @@ package com.ai.da.service; +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.vo.QuestionnaireFeedbackVO; import com.ai.da.model.vo.QuestionnaireVO; +import com.ai.da.model.vo.QueryUserConditionsVO; +import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List; +import java.util.Map; public interface ConvenientInquiryService extends IService { + IPage getTrial(QueryUserConditionsVO queryUserConditionsVO); + QuestionnaireFeedbackVO getQuestionnaireInfo(); List getAllQuestionnaire(); + + IPage recentNewUser(QueryUserConditionsVO queryUserConditionsVO); + + Map recentNewUserChart(String startTime, String endTime, Integer userType); + + IPage recentActiveUser(QueryUserConditionsVO queryUserConditionsVO); + + + int recentActiveUserChart(String startTime, String endTime); + + Map> getActiveUserFunc(String startTime, String endTime, List ids); + + Map conversionRate(); + + Map> trialUserCountry(); + + Boolean addUser(AccountAddDTO accountAddDTO); + + Boolean modifyUser(Long accountId, Long validEndTime, Integer systemUser, Long credits); + + IPage getUserInfo(QueryUserConditionsVO queryUserConditionsVO); + + List> getAllUserIdList(); } diff --git a/src/main/java/com/ai/da/service/DesignItemService.java b/src/main/java/com/ai/da/service/DesignItemService.java index 08d25d72..788fd5b1 100644 --- a/src/main/java/com/ai/da/service/DesignItemService.java +++ b/src/main/java/com/ai/da/service/DesignItemService.java @@ -58,4 +58,6 @@ public interface DesignItemService extends IService { ComposeLayersVO editLayersPositionAndScale(EditLayersPositionAndScaleVO positionAndScaleVO) throws IOException; List selectDesignIdById(List designItemIdList); + + Long getCountByUserAndTime(String startTime, String endTime, List accountIds); } diff --git a/src/main/java/com/ai/da/service/DesignService.java b/src/main/java/com/ai/da/service/DesignService.java index 839ce443..0558f185 100644 --- a/src/main/java/com/ai/da/service/DesignService.java +++ b/src/main/java/com/ai/da/service/DesignService.java @@ -95,4 +95,6 @@ public interface DesignService extends IService { List sketchesBoundingBox(SketchesBoundingBoxDTO sketchesBoundingBoxDTO); List getModel(List designItemIdList); + + Long getCountByUserAndTime(String startTime, String endTime, List accountIds); } diff --git a/src/main/java/com/ai/da/service/GenerateService.java b/src/main/java/com/ai/da/service/GenerateService.java index 7dca1588..f1f219aa 100644 --- a/src/main/java/com/ai/da/service/GenerateService.java +++ b/src/main/java/com/ai/da/service/GenerateService.java @@ -8,6 +8,7 @@ import com.ai.da.model.vo.*; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List; +import java.util.Map; public interface GenerateService extends IService { @@ -38,4 +39,6 @@ public interface GenerateService extends IService { void cancelGenerate(Long userId, List uniqueId, String timeZone, String type); void processRelightResult(String taskId, String url, String category); + + List> getCountByUserAndTime(String startTime, String endTime, List accountIdList); } diff --git a/src/main/java/com/ai/da/service/impl/AccountLoginLogServiceImpl.java b/src/main/java/com/ai/da/service/impl/AccountLoginLogServiceImpl.java index fb09cc10..827013fc 100644 --- a/src/main/java/com/ai/da/service/impl/AccountLoginLogServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/AccountLoginLogServiceImpl.java @@ -12,6 +12,7 @@ import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.Date; import java.util.List; +import java.util.stream.Collectors; //import com.ai.da.common.utils.SendSmsUtil; @@ -44,4 +45,14 @@ public class AccountLoginLogServiceImpl extends ServiceImpl getByDate(String startTime, String endTime){ + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.gt("create_date", startTime).lt("create_date", endTime); + queryWrapper.select("distinct account_id"); + + List accountLoginLogs = baseMapper.selectList(queryWrapper); + return accountLoginLogs.stream().map(AccountLoginLog::getAccountId).collect(Collectors.toList()); + } + } diff --git a/src/main/java/com/ai/da/service/impl/AccountServiceImpl.java b/src/main/java/com/ai/da/service/impl/AccountServiceImpl.java index ceb7fe6b..eec39d47 100644 --- a/src/main/java/com/ai/da/service/impl/AccountServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/AccountServiceImpl.java @@ -47,10 +47,7 @@ import java.text.SimpleDateFormat; import java.time.*; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Objects; +import java.util.*; import java.util.stream.Collectors; /** @@ -1348,5 +1345,66 @@ public class AccountServiceImpl extends ServiceImpl impl return ids; } + public IPage getPageByDateAndUserType(String startTime, String endTime, Integer type, int pageNum, int size){ + QueryWrapper queryWrapper = new QueryWrapper<>(); + setTimeAndSystemUser(queryWrapper,startTime, endTime, type); + + Page accountPage = new Page<>(pageNum, size); + return baseMapper.selectPage(accountPage, queryWrapper); + } + + private void setTimeAndSystemUser(QueryWrapper queryWrapper, String startTime, String endTime, Integer type){ + queryWrapper.gt("create_date", startTime).lt("create_date",endTime); + + if (!Objects.isNull(type)){ + switch (type){ + case 0: + // 游客 + queryWrapper.eq("system_user", 0); + break; + case 1: + queryWrapper.eq("system_user", 1); + break; + case 2: + queryWrapper.eq("system_user", 2); + break; + case 3: + // 试用用户 + queryWrapper.eq("system_user", 3).or().eq("system_user", 4); + break; + + } + } + } + + public Map getByDateAndUserType(String startTime, String endTime, Integer type){ + QueryWrapper queryWrapper = new QueryWrapper<>(); + setTimeAndSystemUser(queryWrapper,startTime, endTime, type); + queryWrapper.groupBy("system_user"); + + queryWrapper.select("system_user as type, count(id) as count"); + List> maps = baseMapper.selectMaps(queryWrapper); + return maps.stream() + .collect(Collectors.toMap( + map -> map.get("type").toString(), + map -> Objects.isNull(map.get("count")) ? 0L : (Long) map.get("count"))); + } + + public IPage getPageByIds(List ids, int pageNum, int size){ + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.in("id", ids); + + return baseMapper.selectPage(new Page<>(pageNum, size), queryWrapper); + } + + public List getByIds(List ids){ + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.in("id", ids); + + return baseMapper.selectList(queryWrapper); + } + + + } diff --git a/src/main/java/com/ai/da/service/impl/ChatRobotServiceImpl.java b/src/main/java/com/ai/da/service/impl/ChatRobotServiceImpl.java index 686e5376..e249ba90 100644 --- a/src/main/java/com/ai/da/service/impl/ChatRobotServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/ChatRobotServiceImpl.java @@ -9,6 +9,7 @@ import com.ai.da.common.enums.LibraryLevel1TypeEnum; import com.ai.da.common.utils.CopyUtil; import com.ai.da.common.utils.MD5Utils; import com.ai.da.common.utils.MinioUtil; +import com.ai.da.common.utils.S3Util; import com.ai.da.mapper.primary.AccountMapper; import com.ai.da.mapper.primary.LibraryMapper; import com.ai.da.mapper.primary.entity.Account; @@ -26,6 +27,7 @@ import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.minio.errors.MinioException; @@ -56,7 +58,7 @@ import java.util.concurrent.TimeUnit; */ @Slf4j @Service -public class ChatRobotServiceImpl implements ChatRobotService { +public class ChatRobotServiceImpl extends ServiceImpl implements ChatRobotService { // @Value("") String chatStreamUrl = "http://18.167.251.121:6789/api/chat_stream"; @@ -382,4 +384,23 @@ public class ChatRobotServiceImpl implements ChatRobotService { return "images/female/" + minioPath; } + public Long getCountByUserAndTime(String startTime, String endTime, List accountIds){ + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.gt("create_time", startTime) + .lt("create_time", endTime) + .select("count(id) as count"); + + if (!accountIds.isEmpty()){ + queryWrapper.in("user_id", accountIds); + } + + List> result = baseMapper.selectMaps(queryWrapper); + if (result != null && !result.isEmpty()) { + Object countObj = result.get(0).get("count"); + return (Long) countObj; + }else { + return 0L; + } + } + } 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 79a3336b..b664ed21 100644 --- a/src/main/java/com/ai/da/service/impl/ConvenientInquiryServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/ConvenientInquiryServiceImpl.java @@ -1,31 +1,101 @@ package com.ai.da.service.impl; +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.CreditsEventsEnum; +import com.ai.da.common.utils.CopyUtil; +import com.ai.da.mapper.primary.AccountMapper; import com.ai.da.mapper.primary.QuestionnaireMapper; +import com.ai.da.mapper.primary.ToProductImageResultMapper; +import com.ai.da.mapper.primary.TrialOrderMapper; 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.enums.Language; import com.ai.da.model.vo.QuestionnaireFeedbackVO; import com.ai.da.model.vo.QuestionnaireVO; -import com.ai.da.service.AccountService; -import com.ai.da.service.ConvenientInquiryService; +import com.ai.da.model.vo.QueryUserConditionsVO; +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.mysql.cj.util.StringUtils; import io.netty.util.internal.StringUtil; +import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import javax.annotation.Resource; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.stream.Collectors; @Service +@Slf4j public class ConvenientInquiryServiceImpl extends ServiceImpl implements ConvenientInquiryService { @Resource private AccountService accountService; + @Resource + private AccountLoginLogService accountLoginLogService; + + public IPage getTrial(QueryUserConditionsVO queryUserConditionsVO) { + log.info("getTrial parameter : {},page:{}, size:{}", queryUserConditionsVO, queryUserConditionsVO.getPage(), queryUserConditionsVO.getSize()); + /* 添加按条件查询试用用户 */ + // 按用户邮箱/用户名/用户id查指定用户 + QueryWrapper queryWrapper = new QueryWrapper<>(); + if (!Objects.isNull(queryUserConditionsVO.getIds()) && !queryUserConditionsVO.getIds().isEmpty()) { + queryWrapper.in("id", queryUserConditionsVO.getIds()); + } + if (!StringUtils.isNullOrEmpty(queryUserConditionsVO.getUserName())) { + queryWrapper.eq("user_name", queryUserConditionsVO.getUserName()); + } + if (!StringUtils.isNullOrEmpty(queryUserConditionsVO.getEmail())) { + queryWrapper.eq("email", queryUserConditionsVO.getEmail()); + } + if (!StringUtils.isNullOrEmpty(queryUserConditionsVO.getCountry())) { + queryWrapper.eq("country", queryUserConditionsVO.getCountry()); + } + if (!StringUtils.isNullOrEmpty(queryUserConditionsVO.getOccupation())) { + queryWrapper.eq("occupation", queryUserConditionsVO.getOccupation()); + } + + // 按时间区间查 + if (!StringUtils.isNullOrEmpty(queryUserConditionsVO.getStartTime())) { + queryWrapper.gt("create_time", queryUserConditionsVO.getStartTime()); + } + if (!StringUtils.isNullOrEmpty(queryUserConditionsVO.getEndTime())) { + queryWrapper.lt("create_time", queryUserConditionsVO.getEndTime()); + } + + // 排序 + if (!StringUtils.isNullOrEmpty(queryUserConditionsVO.getOrder()) && !StringUtils.isNullOrEmpty(queryUserConditionsVO.getOrderBy())) { + String orderBy = "id"; + if (queryUserConditionsVO.getOrderBy().equals("time")) { + orderBy = "create_time"; + } + switch (queryUserConditionsVO.getOrder()) { + case "Ascending": + queryWrapper.orderByAsc(orderBy); + break; + case "Descending": + queryWrapper.orderByDesc(orderBy); + break; + } + } + + // 分页查询 + return trialOrderMapper.selectPage(new Page<>(queryUserConditionsVO.getPage(), queryUserConditionsVO.getSize()), queryWrapper); +// List trialOrders = trialOrderMapper.selectList(null); + } + public QuestionnaireFeedbackVO getQuestionnaireInfo() { String title = "AiDA_3.0 Feedback Survey--06/2024"; @@ -181,26 +251,335 @@ public class ConvenientInquiryServiceImpl extends ServiceImpl recentNewUser(String startTime, String endTime, String userType){ - return null; - /*if (StringUtil.isNullOrEmpty(startTime) && StringUtil.isNullOrEmpty(endTime) && StringUtil.isNullOrEmpty(userType)){ + public IPage recentNewUser(QueryUserConditionsVO queryUserConditionsVO) { + log.info("recentActiveUser parameter : {}, page:{}, size:{}", queryUserConditionsVO, queryUserConditionsVO.getPage(), queryUserConditionsVO.getSize()); + if (StringUtil.isNullOrEmpty(queryUserConditionsVO.getStartTime()) && StringUtil.isNullOrEmpty(queryUserConditionsVO.getEndTime())) { return null; } + if (!StringUtil.isNullOrEmpty(queryUserConditionsVO.getStartTime()) && StringUtil.isNullOrEmpty(queryUserConditionsVO.getEndTime())) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + queryUserConditionsVO.setEndTime(LocalDateTime.now().format(formatter)); + } + Integer type = null; + if (!Objects.isNull(queryUserConditionsVO.getSystemUser())) { + type = queryUserConditionsVO.getSystemUser(); + } - int type = userType.equals("visitor") ? 0 : userType.equals("trial") ? 1 : 2; - return accountService.getByDateAndUserType(startTime, endTime, type);*/ + return accountService.getPageByDateAndUserType(queryUserConditionsVO.getStartTime(), + queryUserConditionsVO.getEndTime(), + type, + queryUserConditionsVO.getPage(), + queryUserConditionsVO.getSize()); + } + + // 图表数据 + public Map recentNewUserChart(String startTime, String endTime, Integer userType) { + log.info("recentNewUserChart startTime : {},endTime : {},userType:{}", startTime, endTime, userType); + if (StringUtil.isNullOrEmpty(startTime) && StringUtil.isNullOrEmpty(endTime)) { + return null; + } + if (!StringUtil.isNullOrEmpty(startTime) && StringUtil.isNullOrEmpty(endTime)) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + endTime = LocalDateTime.now().format(formatter); + } + + Map countMap = accountService.getByDateAndUserType(startTime, endTime, userType); + long type1 = countMap.get("1") == null ? 0L : countMap.get("1"); + long type2 = countMap.get("2") == null ? 0L : countMap.get("2"); + long type3 = countMap.get("3") == null ? 0L : countMap.get("3"); + long type4 = countMap.get("4") == null ? 0L : countMap.get("4"); + List names = Arrays.asList("Visitor", "Trials", "Official"); + List values = Arrays.asList(countMap.get("0") == null ? 0L : countMap.get("0"), + type3 + type4, + type1 + type2); + + HashMap resp = new HashMap<>(); + resp.put("names", names); + resp.put("values", values); + + return resp; } // 近期活跃用户 - public List recentActiveUser(String startTime, String endTime){ - return null; + public IPage recentActiveUser(QueryUserConditionsVO queryUserConditionsVO) { + log.info("recentActiveUser parameter : {}, page:{}, size:{}", queryUserConditionsVO, queryUserConditionsVO.getPage(), queryUserConditionsVO.getSize()); + if (!StringUtil.isNullOrEmpty(queryUserConditionsVO.getStartTime()) && StringUtil.isNullOrEmpty(queryUserConditionsVO.getEndTime())) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + queryUserConditionsVO.setEndTime(LocalDateTime.now().format(formatter)); + } + List accountIds = accountLoginLogService.getByDate(queryUserConditionsVO.getStartTime(), queryUserConditionsVO.getEndTime()); + return accountService.getPageByIds(accountIds, queryUserConditionsVO.getPage(), queryUserConditionsVO.getSize()); + } + + // 图表数据 + public int recentActiveUserChart(String startTime, String endTime) { + if (!StringUtil.isNullOrEmpty(startTime) && StringUtil.isNullOrEmpty(endTime)) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + endTime = LocalDateTime.now().format(formatter); + } + List accountIds = accountLoginLogService.getByDate(startTime, endTime); + return accountIds.size(); + } + + @Resource + private GenerateService generateService; + @Resource + private ToProductImageResultMapper toProductImageResultMapper; + @Resource + private DesignService designService; + @Resource + private DesignItemService designItemService; + @Resource + private ChatRobotService chatRobotService; + + public Map> getActiveUserFunc(String startTime, String endTime, List ids) { + + log.info("getActiveUserFunc ==> startTime:{}, endTime:{}, accountList:{}", startTime, endTime, ids); + // 必须指定时间区间 + if (StringUtil.isNullOrEmpty(startTime) && StringUtil.isNullOrEmpty(endTime)) { + return null; + } else if (!StringUtil.isNullOrEmpty(startTime) && StringUtil.isNullOrEmpty(endTime)) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + endTime = LocalDateTime.now().format(formatter); + } + + // design + Long designTimes = designService.getCountByUserAndTime(startTime, endTime, ids); + + // single design + Long singleDesignTimes = designItemService.getCountByUserAndTime(startTime, endTime, ids); + + // generate -> MoodBoard\PrintBoard\SketchBoard + List> countGenerate = generateService.getCountByUserAndTime(startTime, endTime, ids); + // 使用Stream API和lambda表达式将数据合并到一个Map中 + Map countGenerateMerge = countGenerate.stream() + .collect(Collectors.toMap( + map -> (String) map.get("type"), + map -> Objects.isNull(map.get("count")) ? 0L : (Long) map.get("count"))); + + // toProductImage\ReLight + List> countProduct = toProductImageResultMapper.getByTypeAndTime(startTime, endTime, ids); + Map countProductMerge = countProduct.stream() + .collect(Collectors.toMap( + map -> (String) map.get("type"), + map -> Objects.isNull(map.get("count")) ? 0L : (Long) map.get("count"))); + + // chatRobot + Long chatTimes = chatRobotService.getCountByUserAndTime(startTime, endTime, ids); + + List names = Arrays.asList("Design", "SingleDesign", "MoodBoard", "PrintBoard", "SketchBoard", "Pattern", "Logo", "Slogan", "ToProductImage", "Relight", "ChatRobot"); + List values = Arrays.asList(designTimes, singleDesignTimes, + countGenerateMerge.get("Moodboard") == null ? 0L : countGenerateMerge.get("Moodboard"), + countGenerateMerge.get("Printboard") == null ? 0L : countGenerateMerge.get("Printboard"), + countGenerateMerge.get("Sketchboard") == null ? 0L : countGenerateMerge.get("Sketchboard"), + countGenerateMerge.get("Pattern") == null ? 0L : countGenerateMerge.get("Pattern"), + countGenerateMerge.get("Logo") == null ? 0L : countGenerateMerge.get("Logo"), + countGenerateMerge.get("Slogan") == null ? 0L : countGenerateMerge.get("Slogan"), + countProductMerge.get("ToProductImage") == null ? 0L : countProductMerge.get("ToProductImage"), + countProductMerge.get("Relight") == null ? 0L : countProductMerge.get("Relight"), + chatTimes); + + HashMap> resp = new HashMap<>(); + resp.put("names", names); + resp.put("values", values); + + return resp; + } + + @Resource + private TrialOrderMapper trialOrderMapper; + + // 试用用户到正式用户的转化率 + public Map conversionRate() { + + QueryWrapper queryWrapper = new QueryWrapper<>(); + // 获取试用用户总数 + queryWrapper.select("count(distinct email) as count"); + + List> trialMaps = trialOrderMapper.selectMaps(queryWrapper); + Long totalTrials = (Long) trialMaps.get(0).get("count"); + + // 获取从试用用户转为正式用户的用户数量 + Map officialMaps = trialOrderMapper.countOfficialUser(); + Long trialToOfficial = officialMaps.get("count"); + + // 计算转化率 + HashMap resp = new HashMap<>(); + resp.put("trialUserCount", totalTrials.floatValue()); + resp.put("trialToOfficialCount", trialToOfficial.floatValue()); + resp.put("conversionRate", new BigDecimal(trialToOfficial).divide(new BigDecimal(totalTrials), 2, RoundingMode.HALF_UP).floatValue()); + + return resp; + + } + + // 试用用户地区统计 + public Map> trialUserCountry() { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.select("country, count(id) as count") + .groupBy("country"); + List> countryCount = trialOrderMapper.selectMaps(queryWrapper); + + Map countryCountMap = countryCount.stream().collect(Collectors.toMap( + map -> map.get("country"), + map -> map.get("count") + )); + HashMap> resp = new HashMap<>(); + resp.put("names", new ArrayList<>(countryCountMap.keySet())); + resp.put("values", new ArrayList<>(countryCountMap.values())); + + return resp; } + // 新增用户 + public Boolean addUser(AccountAddDTO accountAddDTO) { + // 需要给的数据 用户邮箱、用户名、账号有效期截止时间、账号类型 + Account account = CopyUtil.copyObject(accountAddDTO, Account.class); + + // 添加正式用户 + if (Objects.isNull(accountAddDTO.getSystemUser())) { + throw new BusinessException("you have to choose user type"); + } else { + switch (accountAddDTO.getSystemUser()) { + case 0: + account.setCredits(new BigDecimal(0)); + account.setIsTrial(0); + break; + case 1: + account.setCredits(new BigDecimal(CreditsEventsEnum.INIT_YEARLY.getValue())); + account.setIsTrial(0); + break; + case 2: + account.setCredits(new BigDecimal(CreditsEventsEnum.INIT_MONTHLY.getValue())); + account.setIsTrial(0); + break; + case 3: + account.setCredits(new BigDecimal(CreditsEventsEnum.INIT_TRIAL.getValue())); + account.setIsTrial(1); + break; + } + } + account.setValidStartTime(Long.parseLong(accountAddDTO.getValidStartTime())); + account.setValidEndTime(Long.parseLong(accountAddDTO.getValidEndTime())); + account.setUserPassword("Third-000000"); + account.setLanguage(Language.ENGLISH.name()); + account.setCreateDate(new Date()); + account.setIsBeginner(1); + + log.info("添加用户:{}", accountAddDTO.getUserEmail()); + return accountService.save(account); + } + + // 修改用户信息 + public Boolean modifyUser(Long accountId, Long validEndTime, Integer systemUser, Long credits) { + log.info("modifyUser ==> accountId:{}, validEndTime:{}, systemUser:{}, systemUser:{}", accountId, validEndTime, systemUser, credits); + if (Objects.isNull(accountId) && Objects.isNull(validEndTime) && Objects.isNull(systemUser) && Objects.isNull(credits)) { + return null; + } else if (Objects.isNull(accountId)) { + throw new BusinessException("you have to choose a user"); + } + + Account account = new Account(); + // 修改用户有效期截止日期、用户类型、积分 + if (!Objects.isNull(validEndTime)) { + account.setValidEndTime(validEndTime); + } + if (!Objects.isNull(systemUser)) { + account.setSystemUser(systemUser); + } + /*if (!StringUtils.isNullOrEmpty(systemUser)) { + int systemUser = 0; + switch (systemUser) { + case "yearly": + systemUser = 1; + break; + case "monthly": + systemUser = 2; + break; + case "trial": + systemUser = 3; + break; + case "visitor": + systemUser = 0; + break; + } + account.setSystemUser(systemUser); + }*/ + if (!Objects.isNull(credits)) { + account.setCredits(new BigDecimal(credits)); + } + account.setId(accountId); + account.setUpdateDate(new Date()); + log.info("修改用户信息:{}", accountId); + return accountMapper.updateById(account) == 1; +// accountService.update(account,null); + } + + @Resource + private AccountMapper accountMapper; + + // 按条件查询用户信息 + public IPage getUserInfo(QueryUserConditionsVO queryUserConditionsVO) { + log.info("getUserInfo parameter : {},page:{}, size:{}", queryUserConditionsVO, queryUserConditionsVO.getPage(), queryUserConditionsVO.getSize()); + // 按用户邮箱/用户名/用户id查指定用户 + QueryWrapper queryWrapper = new QueryWrapper<>(); + if (!Objects.isNull(queryUserConditionsVO.getIds()) && !queryUserConditionsVO.getIds().isEmpty()) { + queryWrapper.in("id", queryUserConditionsVO.getIds()); + } + if (!StringUtils.isNullOrEmpty(queryUserConditionsVO.getUserName())) { + queryWrapper.eq("user_name", queryUserConditionsVO.getUserName()); + } + if (!StringUtils.isNullOrEmpty(queryUserConditionsVO.getEmail())) { + queryWrapper.eq("user_email", queryUserConditionsVO.getEmail()); + } + if (!StringUtils.isNullOrEmpty(queryUserConditionsVO.getCountry())) { + queryWrapper.eq("country", queryUserConditionsVO.getCountry()); + } + if (!Objects.isNull(queryUserConditionsVO.getSystemUser())) { + queryWrapper.eq("system_user", queryUserConditionsVO.getSystemUser()); + } + + // 按时间区间查 + if (!StringUtils.isNullOrEmpty(queryUserConditionsVO.getStartTime())) { + queryWrapper.gt("create_date", queryUserConditionsVO.getStartTime()); + } + if (!StringUtils.isNullOrEmpty(queryUserConditionsVO.getEndTime())) { + queryWrapper.lt("create_date", queryUserConditionsVO.getEndTime()); + } + + // 排序 + if (!StringUtils.isNullOrEmpty(queryUserConditionsVO.getOrder()) && !StringUtils.isNullOrEmpty(queryUserConditionsVO.getOrderBy())) { + String orderBy = "id"; + switch (queryUserConditionsVO.getOrderBy()) { + case "time": + orderBy = "create_date"; + break; + case "credits": + orderBy = "credits"; + break; + } + switch (queryUserConditionsVO.getOrder()) { + case "Ascending": + queryWrapper.orderByAsc(orderBy); + break; + case "Descending": + queryWrapper.orderByDesc(orderBy); + break; + } + } + // 分页查询 + return accountMapper.selectPage(new Page<>(queryUserConditionsVO.getPage(), queryUserConditionsVO.getSize()), queryWrapper); + } + + public List> getAllUserIdList() { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.select("id as value, user_name as label"); + + return accountMapper.selectMaps(queryWrapper); +// return maps.stream().map(map -> (Long)map.get("id")).collect(Collectors.toList()); + } + } diff --git a/src/main/java/com/ai/da/service/impl/DesignItemServiceImpl.java b/src/main/java/com/ai/da/service/impl/DesignItemServiceImpl.java index edb83b7f..1a12f6e4 100644 --- a/src/main/java/com/ai/da/service/impl/DesignItemServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/DesignItemServiceImpl.java @@ -1,858 +1,877 @@ -package com.ai.da.service.impl; - -import cn.hutool.core.collection.CollectionUtil; -import cn.hutool.core.util.ObjectUtil; -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.CollectionLevel1TypeEnum; -import com.ai.da.common.enums.SingleOverallEnum; -import com.ai.da.common.enums.SysFileLevel2TypeEnum; -import com.ai.da.common.utils.*; -import com.ai.da.mapper.primary.DesignItemMapper; -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.vo.*; -import com.ai.da.python.PythonService; -import com.ai.da.python.vo.*; -import com.ai.da.service.*; -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -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.apache.commons.lang3.SerializationUtils; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import javax.annotation.Resource; -import java.io.IOException; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.util.*; -import java.util.stream.Collectors; - -/** - * 服务实现类 - * - * @author yanglei - * @since 2022-09-30 - */ -@Slf4j -@Service -public class DesignItemServiceImpl extends ServiceImpl implements DesignItemService { - @Resource - private DesignItemMapper designItemMapper; - @Resource - private SysFileService sysFileService; - @Resource - private PythonService pythonService; - @Resource - private DesignService designService; - @Resource - private DesignItemDetailService designItemDetailService; - @Resource - private LibraryModelPointService libraryModelPointService; - @Resource - private LibraryService libraryService; - @Resource - private CollectionElementService collectionElementService; - @Resource - private ITDesignPythonOutfitService designPythonOutfitService; - @Resource - private ITDesignPythonOutfitDetailService designPythonOutfitDetailService; - @Resource - private PanToneService panToneService; - @Resource - private DesignItemDetailPrintService designItemDetailPrintService; - @Resource - private MinioUtil minioUtil; - @Resource - private UserLikeService userLikeService; - @Resource - private UserLikeGroupService userLikeGroupService; - - @Value("${minio.bucketName.modifiedSketch}") - private String modifiedSketchBucket; - - @Override - public Long saveOne(DesignItem designItem) { - if (designItemMapper.insertDesignItem(designItem) <= 0) { - throw new BusinessException("save.designItem.failed"); - } - return designItem.getId(); - } - - @Override - public int deleteByCollectionId(Long collectionId) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("collection_id", collectionId); - - DesignItem designItem = new DesignItem(); - designItem.setCollectionId(0L); - return designItemMapper.update(designItem, queryWrapper); - } - - @Override - public List getByDesignId(Long designId) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("design_id", designId); - queryWrapper.eq("is_like", (byte) 0); - return designItemMapper.selectList(queryWrapper); - } - - @Override - public void updateLikeStatus(Long designItemId, Byte hasLike) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("id", designItemId); - - DesignItem designItem = new DesignItem(); - designItem.setHasLike(hasLike); - designItemMapper.update(designItem, queryWrapper); - } - - @Override - public void updateDesignHighUrl(Long designItemId, String highUrl, String timeZone) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("id", designItemId); - - DesignItem designItem = new DesignItem(); - designItem.setHighDesignUrl(highUrl); - designItem.setUpdateDate(DateUtil.getByTimeZone(timeZone)); - designItemMapper.update(designItem, queryWrapper); - } - - @Override - public GetNextSysElementVO getNextSysElement(Long id, String level2Type, String operateType) { - //校验 - if (!DesignPythonItem.SYS_HAIRSTYLE_SHOES_BODY.contains(level2Type)) { - throw new BusinessException("unknown.type"); - } - List operateTypes = Arrays.asList("PREV", "NEXT"); - if (!operateTypes.contains(operateType)) { - throw new BusinessException("unknown.operateType"); - } - if (null == id) { - throw new BusinessException("id.cannot.be.empty"); - } - Long maxId = sysFileService.getMaxIdByLevel2Type(level2Type, null); - Long minId = sysFileService.getMinIdByLevel2Type(level2Type, null); - - if (id > maxId || id < minId) { - throw new BusinessException("the.id.value.is.out.of.range"); - } - Long idValue = null; - if ("PREV".equals(operateType)) { - if (minId.equals(id)) { - idValue = minId; - } else { - idValue = id - 1; - } - } - if ("NEXT".equals(operateType)) { - if (maxId.equals(id)) { - idValue = maxId; - } else { - idValue = id + 1; - } - } - SysFileVO sysFileVO = sysFileService.getById(idValue); - return new GetNextSysElementVO(sysFileVO.getId(), level2Type, sysFileVO.getUrl()); - } - - @Override - public DesignCollectionItemVO designSingle(DesignSingleDTO designSingleDTO) { - AuthPrincipalVo userInfo = UserContext.getUserHolder(); - DesignItem designItem = selectById(designSingleDTO.getDesignItemId()); - if (Objects.isNull(designItem)) { - throw new BusinessException("designItem.not.found"); - } - Design design = designService.getById(designItem.getDesignId()); - if (Objects.isNull(design)) { - throw new BusinessException("design.not.found"); - } - DesignLibraryModelPointVO designLibraryModelPointVO = null; - if (Objects.nonNull(design.getTemplateId())) { - LibraryModelPoint modelPoint = libraryModelPointService.getById(design.getTemplateId()); - if (Objects.isNull(modelPoint)) { - throw new BusinessException("modelPoint.not.found"); - } - Library library = libraryService.getById(modelPoint.getRelationId()); - // ??和上面重复 - if (Objects.isNull(library)) { - throw new BusinessException("library.not.found"); - } - designLibraryModelPointVO = collectionElementService.calculateTemplatePoint(modelPoint, library.getHigh(), library.getWidth(), library.getUrl()); - } - - Set newTypes = designSingleDTO.getClothes().stream().map(DesignSingleItemDTO::getType).collect(Collectors.toSet()); - //校验category - validateCategory(newTypes, design.getSingleOverall(), design.getSwitchCategory()); - DesignPythonObjects objects = pythonService.covertDesignSingleParam( - designSingleDTO, design.getSingleOverall(), design.getSwitchCategory(), designLibraryModelPointVO); - pythonService.design(objects); - //designSingle - DesignCollectionItemVO response = saveSingleDesignItemAndDetail(objects, design.getId(), designSingleDTO.getDesignItemId(), - design.getCollectionId(), userInfo, designSingleDTO.getTimeZone()); - // ?? - designItem.setDesignUrl(response.getDesignItemUrl()); - return response; - } - - private LibraryModelPointVO resloveVoByModelPoint(LibraryModelPoint modelPoint, Library library) { - LibraryModelPointVO libraryModelPointVO = CopyUtil.copyObject(modelPoint, LibraryModelPointVO.class); - libraryModelPointVO.setTemplateId(modelPoint.getId()); - libraryModelPointVO.setHandLeft(JSON.parseObject(modelPoint.getHandLeft(), List.class)); - libraryModelPointVO.setHandRight(JSON.parseObject(modelPoint.getHandRight(), List.class)); - libraryModelPointVO.setShoulderRight(JSON.parseObject(modelPoint.getShoulderRight(), List.class)); - libraryModelPointVO.setShoulderLeft(JSON.parseObject(modelPoint.getShoulderLeft(), List.class)); - libraryModelPointVO.setWaistbandRight(JSON.parseObject(modelPoint.getWaistbandRight(), List.class)); - libraryModelPointVO.setWaistbandLeft(JSON.parseObject(modelPoint.getWaistbandLeft(), List.class)); - return libraryModelPointVO; - } - - @Override - public String printDot(DesignSingleDTO designSingleDTO) { - DesignItem designItem = selectById(designSingleDTO.getDesignItemId()); - if (Objects.isNull(designItem)) { - throw new BusinessException("designItem.not.found"); - } - Design design = designService.getById(designItem.getDesignId()); - if (Objects.isNull(design)) { - throw new BusinessException("design.not.found"); - } - DesignLibraryModelPointVO designLibraryModelPointVO = null; - if (Objects.nonNull(design.getTemplateId())) { - LibraryModelPoint modelPoint = libraryModelPointService.getById(design.getTemplateId()); - if (Objects.isNull(modelPoint)) { - throw new BusinessException("modelPoint.not.found"); - } - Library library = libraryService.getById(modelPoint.getRelationId()); - if (Objects.isNull(library)) { - throw new BusinessException("library.not.found"); - } - designLibraryModelPointVO = collectionElementService.calculateTemplatePoint(modelPoint, library.getHigh(), library.getWidth(), library.getUrl()); - } - Set newTypes = designSingleDTO.getClothes().stream().map(DesignSingleItemDTO::getType).collect(Collectors.toSet()); - //校验category - validateCategory(newTypes, design.getSingleOverall(), design.getSwitchCategory()); - DesignPythonObjects objects = pythonService.covertDesignSingleParam( - designSingleDTO, design.getSingleOverall(), design.getSwitchCategory(), designLibraryModelPointVO); - pythonService.design(objects); - - return objects.getObjects().get(0).getBasic().getSave_name(); - } - - private void validateCategory(Set newTypes, String singleOverall, String switchCategory) { - if (SingleOverallEnum.SINGLE.getRealName().equals(singleOverall)) { - if (newTypes.size() > 1) { - throw new BusinessException("wrong.clothes.type"); - } - //一个的时候 - if (!switchCategory.equals(CollectionUtil.newArrayList(newTypes).get(0))) { - throw new BusinessException("wrong.clothes.type"); - } - } - } - // todo check这个方法是否还在用 - private DesignCollectionItemVO saveSingleDesignItemAndDetail(DesignPythonObjects pythonObjects - , Long designId, Long designItemId, Long collectionId, AuthPrincipalVo userInfo, String timeZone) { - DesignCollectionItemVO response = new DesignCollectionItemVO(); - response.setDesignItemId(designItemId); - - DesignItem designItem = new DesignItem(); - String url = pythonObjects.getObjects().get(0).getBasic().getSave_name(); - designItem.setUpdateDate(DateUtil.getByTimeZone(timeZone)); - designItem.setDesignUrl(url); - designItem.setId(designItemId); - response.setDesignItemUrl(url); - //更新item - updateById(designItem); - //删除itemDetail - designItemDetailService.deleteByDesignItemId(designItemId); - - List designItemDetails = Lists.newArrayList(); - pythonObjects.getObjects().get(0).getItems().forEach(detail -> { - if (null == detail) { - return; - } - DesignItemDetail designItemDetail = CopyUtil.copyObject(detail, DesignItemDetail.class); - designItemDetail.setAccountId(userInfo.getId()); - designItemDetail.setDesignId(designId); - designItemDetail.setDesignItemId(designItemId); - designItemDetail.setCollectionElementId(detail.getElementId()); - designItemDetail.setCreateDate(DateUtil.getByTimeZone(timeZone)); - if (SysFileLevel2TypeEnum.BODY.getRealName().equals(detail.getType())) { - designItemDetail.setPath(detail.getBody_path()); - //BODY不关联businessId - designItemDetail.setBusinessId(0L); - } - designItemDetail.setIconPath(detail.getIcon()); - // todo - DesignPythonItemPrint printObject = detail.getPrint().getSingle(); - designItemDetail.setPrintPath(Objects.isNull(printObject) ? "" : printObject.getPath()); - designItemDetail.setPrintJson(JSON.toJSONString(printObject)); - designItemDetails.add(designItemDetail); - }); - designItemDetailService.saveBatch(designItemDetails); - //封装item信息 - List designCollectionItems = CopyUtil.copyList(getByDesignId(designId) - , DesignCollectionItemVO.class, (o, d) -> { - d.setDesignItemId(o.getId()); - d.setDesignItemUrl(o.getDesignUrl()); - }); - return response; - } - - private List saveDesignSingleItemDetailAndLayers(DesignPythonObjects pythonObjects - , Long designId, Long designItemId, Long userId - , JSONObject outfit, String timeZone, List designSingleItemDTOList - , Map categoryAndUndividedLayer) { - - DesignItem designItem = new DesignItem(); -// String url = pythonObjects.getObjects().get(0).getBasic().getSave_name(); - designItem.setUpdateDate(DateUtil.getByTimeZone(timeZone)); - designItem.setDesignUrl(outfit.getString("synthesis_url")); - designItem.setId(designItemId); - // 1、更新designItem - updateById(designItem); - // 2、删除designItemDetail(逻辑删除) - designItemDetailService.deleteByDesignItemId(designItemId); - List designItemDetails = Lists.newArrayList(); - // 3、保存新的designItemDetail - pythonObjects.getObjects().get(0).getItems().forEach(detail -> { - if (null == detail) { - return; - } - DesignItemDetail designItemDetail = CopyUtil.copyObject(detail, DesignItemDetail.class); - designItemDetail.setAccountId(userId); - designItemDetail.setDesignId(designId); - designItemDetail.setDesignItemId(designItemId); - designItemDetail.setCollectionElementId(detail.getElementId()); - designItemDetail.setPriority(detail.getPriority()); - designItemDetail.setCreateDate(DateUtil.getByTimeZone(timeZone)); - if (SysFileLevel2TypeEnum.BODY.getRealName().equals(detail.getType())) { - designItemDetail.setPath(detail.getBody_path()); - //BODY不关联businessId - designItemDetail.setBusinessId(0L); - designItemDetail.setPriority(0); - } - designItemDetail.setIconPath(detail.getIcon()); - designItemDetail.setUndividedLayer(categoryAndUndividedLayer.get(detail.getType().toLowerCase())); - // 印花存储在design_item_detail_print表中 这里还要存吗? -// DesignPythonItemPrint printObject = detail.getPrintToPython(); -// designItemDetail.setPrintPath(Objects.isNull(printObject) ? "" : printObject.getPath()); -// 当有多个印花后,返回的printObject太长,导致存储到数据库时报错 -// designItemDetail.setPrintJson(JSON.toJSONString(printObject)); - designItemDetails.add(designItemDetail); - }); - // businessId 来自t_sys_file或者t_library - designItemDetailService.saveBatch(designItemDetails); - - // 4、保存印花信息到designItemDetailPrint - List designItemDetailPrints = setDesignItemDetailPrintList(designItemDetails, designSingleItemDTOList, timeZone); - designItemDetailPrintService.saveBatch(designItemDetailPrints); - - // 5、覆盖designPythonOutfit表中的模特全身图 - TDesignPythonOutfit designPythonOutfit = new TDesignPythonOutfit(); - designPythonOutfit.setDesignUrl(outfit.getString("synthesis_url")); - designPythonOutfit.setId(designPythonOutfitService.getByDesignItemId(designItemId).getId()); - designPythonOutfit.setUpdateDate(LocalDateTime.now(ZoneId.of(timeZone))); - designPythonOutfitService.updateById(designPythonOutfit); - - // 6、删除designPythonOutfitDetail表中原始的图层信息(逻辑删除) - designPythonOutfitDetailService.deleteByDesignPythonOutfitId(designPythonOutfit.getId()); - - // 7、将新生成的图层信息存入designPythonOutfitDetail表 - JSONArray layers = outfit.getJSONArray("layers"); - - Map> priorityOffset = designSingleItemDTOList.stream() - .collect(Collectors.toMap(DesignSingleItemDTO::getPriority, DesignSingleItemDTO::getOffset)); - List list = setTDesignPythonOutfitDetailList(layers, designId, designPythonOutfit.getId(), userId, priorityOffset); - - designPythonOutfitDetailService.saveBatch(list); - - return list; - } - - public List setTDesignPythonOutfitDetailList(JSONArray layers, Long designId, - Long designPythonOutfitId, Long userId, - Map> priorityOffset) { - // 设置图层信息; - List list = new ArrayList<>(); - for (int i = 0; i < layers.size(); i++) { - JSONObject jsonObject = layers.getJSONObject(i); - TDesignPythonOutfitDetail designPythonOutfitDetail = new TDesignPythonOutfitDetail(); - designPythonOutfitDetail.setDesignId(designId); - designPythonOutfitDetail.setDesignPythonOutfitId(designPythonOutfitId); - designPythonOutfitDetail.setPosition(jsonObject.getString("position")); - designPythonOutfitDetail.setImageUrl(jsonObject.getString("image_url")); - designPythonOutfitDetail.setImageSize(jsonObject.getString("image_size")); - designPythonOutfitDetail.setImageCategory(jsonObject.getString("image_category")); - designPythonOutfitDetail.setMaskUrl(jsonObject.getString("mask_url")); - designPythonOutfitDetail.setScale(Objects.isNull(jsonObject.getString("resize_scale")) ? "1.0" : jsonObject.getString("resize_scale")); - designPythonOutfitDetail.setUserId(userId); - designPythonOutfitDetail.setOffset(String.valueOf(priorityOffset.get(Math.abs(Integer.parseInt(jsonObject.getString("priority")))))); - designPythonOutfitDetail.setPriority((Integer) jsonObject.get("priority")); - list.add(designPythonOutfitDetail); - } - return list; - } - - private DesignItem selectById(Long id) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("id", id); - return designItemMapper.selectOne(queryWrapper); - } - - private Boolean exists(Long id) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("id", id); - return designItemMapper.exists(queryWrapper); - } - - @Override - @Transactional(rollbackFor = Exception.class) - public DesignSingleVO designSingleIncludeLayers(DesignSingleIncludeLayersDTO designSingleIncludeLayersDTO) { - // 记录入参 base64数据太长,所以这里去掉 - DesignSingleIncludeLayersDTO clone = SerializationUtils.clone(designSingleIncludeLayersDTO); - clone.getDesignSingleItemDTOList().forEach( i -> { - // 渐变色 - if (!Objects.isNull(i.getGradient()) && !StringUtil.isNullOrEmpty(i.getGradient().getColorImg())){ - log.info("set gradient colorImage为空,便于日志打印"); - i.getGradient().setColorImg(null); - } - // 画笔修改过的sketch - if (!StringUtil.isNullOrEmpty(i.getSketchString())){ - log.info("set sketchString为空,便于日志打印"); - i.setSketchString(null); - } - }); - - log.info("designSingle request入参 ==> " + JSONObject.toJSONString(clone)); - - Long userId = UserContext.getUserHolder().getId(); - DesignItem designItem = selectById(designSingleIncludeLayersDTO.getDesignItemId()); - if (Objects.isNull(designItem)) { - throw new BusinessException("designItem.not.found"); - } - Design design = designService.getById(designItem.getDesignId()); - if (Objects.isNull(design)) { - throw new BusinessException("design.not.found"); - } - - DesignLibraryModelPointVO designLibraryModelPointVO = null; - // 设置模特 - if (Objects.nonNull(design.getTemplateId())) { - String modelUrl; - Integer high; - Integer width; - if (design.getModelType().equals(ModelType.SYSTEM.getValue())) { - SysFileVO sysFile = sysFileService.getById(design.getTemplateId()); - if (Objects.isNull(sysFile)) { - throw new BusinessException("model.not.found"); - } - modelUrl = sysFile.getUrl(); - high = 700; - width = 320; - } else if (design.getModelType().equals(ModelType.LIBRARY.getValue())){ - Library libFile = libraryService.getById(design.getTemplateId()); - if (Objects.isNull(libFile)) { - throw new BusinessException("model.not.found"); - } - modelUrl = libFile.getUrl(); - high = libFile.getHigh(); - width = libFile.getWidth(); - }else { - throw new BusinessException("unknown.modelType"); - } - LibraryModelPoint modelPoint = libraryModelPointService.getByRelationId(design.getTemplateId(), design.getModelType()); - if (Objects.isNull(modelPoint)) { - throw new BusinessException("modelPoint.not.found"); - } -// Assert.notNull(modelPoint, "The model has not been tagged"); - - designLibraryModelPointVO = collectionElementService.calculateTemplatePoint(modelPoint, high, width, modelUrl); - } - - // 画笔修改的sketch截图 上传后替换path - // 由于用户在系统或自己上传sketch的基础上修改过的衣服,再次修改后,第一次修改的衣服不会回到某个池子被再次利用, - // 所以,这里选择使用system或collection相同的地址,只是放在不同的桶,这样能保证图片服务器上,类似的sketch不会存在很多 - sketchBase64ToPath(designSingleIncludeLayersDTO); - - // 组装入参 - DesignPythonObjects objects = pythonService.covertDesignSingleParam( - designSingleIncludeLayersDTO, design.getSingleOverall(), design.getSwitchCategory(), designLibraryModelPointVO); - // design - JSONObject jsonObject = pythonService.designNew(objects); - // preview -> 不存数据库 submit -> 存数据库 - List tDesignPythonOutfitDetails; - JSONObject data = jsonObject.getJSONObject("data"); - if (data == null) { - throw new BusinessException("python response data is null"); - } - JSONObject outfit = data.getJSONObject("0"); - // 通过priority将offset关联到layers - Map> priorityOffset = new HashMap<>(); - try{ - priorityOffset = designSingleIncludeLayersDTO.getDesignSingleItemDTOList().stream() - .collect(Collectors.toMap(DesignSingleItemDTO::getPriority, DesignSingleItemDTO::getOffset)); - }catch (IllegalStateException e){ - // priority重复 - log.info("服装的priority重复"); - throw new BusinessException("priority.cannot.be.repeated"); - } - - JSONArray layers = outfit.getJSONArray("layers"); - Map categoryAndUndividedLayer = setTypeAndUndividedLayer(layers); - if (!designSingleIncludeLayersDTO.getIsPreview()) { - // 更新及保存图层信息 - tDesignPythonOutfitDetails = saveDesignSingleItemDetailAndLayers(objects, design.getId(), designSingleIncludeLayersDTO.getDesignItemId() - , userId, outfit, designSingleIncludeLayersDTO.getTimeZone() - , designSingleIncludeLayersDTO.getDesignSingleItemDTOList() - , categoryAndUndividedLayer); - - saveCollectionElement(designSingleIncludeLayersDTO); - } else { - tDesignPythonOutfitDetails = setTDesignPythonOutfitDetailList(layers, designItem.getDesignId(), null, userId, priorityOffset); - } - - List detailsVO = new ArrayList<>(); - - tDesignPythonOutfitDetails.forEach(detail -> { - String type = detail.getImageCategory().split("_")[0]; - detailsVO.add(designPythonOutfitDetailService.convertToDesignPythonOutfitVO(detail, null)); - }); - - TDesignPythonOutfit designPythonOutfit = designPythonOutfitService.getByDesignItemId(designSingleIncludeLayersDTO.getDesignItemId()); -// Assert.notNull(designItem, "design item detail layers does not exists!"); - - // 如果当前item被like过,需要更新t_user_like表和t_user_like_group表 - if (!designSingleIncludeLayersDTO.getIsPreview()){ - updateUserLikeDate(designSingleIncludeLayersDTO.getDesignItemId(),designSingleIncludeLayersDTO.getTimeZone()); - } - - return assembleDesignSingleResponse(designItem.getId(), - minioUtil.getPreSignedUrl(designPythonOutfit.getDesignUrl(), 24 * 60), - outfit.getString("synthesis_url"), - designSingleIncludeLayersDTO.getDesignSingleItemDTOList(), - detailsVO, - design.getSingleOverall(), - categoryAndUndividedLayer); - } - - private void sketchBase64ToPath(DesignSingleIncludeLayersDTO designSingleIncludeLayersDTO){ - designSingleIncludeLayersDTO.getDesignSingleItemDTOList().forEach(item -> { - // 如果sketch截图不为空,则将该截图上传,并替换path - if (!StringUtil.isNullOrEmpty(item.getSketchString())){ - if (StringUtil.isNullOrEmpty(item.getPath())){ - throw new BusinessException("path.cannot.be.empty"); - } - String sourcePath = item.getPath(); - String path = sourcePath.substring(sourcePath.indexOf("/") + 1, sourcePath.lastIndexOf(".")); - // 将原图地址作为修改后的图片地址,放在不同的桶 - String newPath = minioUtil.base64UploadToPath(item.getSketchString(), modifiedSketchBucket, path); - if (StringUtil.isNullOrEmpty(newPath)){ - log.error("修改过的sketch图片上传失败"); - throw new BusinessException("image.modify.failed"); - } - item.setPath(newPath); - } - }); - } - - @Override - public Map setTypeAndUndividedLayer(JSONArray layers){ - HashMap categoryAndLayer = new HashMap<>(); - for (int i = 0; i < layers.size(); i++) { - JSONObject jsonObject = layers.getJSONObject(i); - String category = jsonObject.getString("image_category").split("_")[0]; - if (!category.equals("body") && !categoryAndLayer.containsKey(category)) categoryAndLayer.put(category, jsonObject.getString("pattern_image_url")); - } - return categoryAndLayer; - } - - @Override - @Transactional(rollbackFor = Exception.class) - public ComposeLayersVO editLayersPositionAndScale(EditLayersPositionAndScaleVO positionAndScaleVO) throws IOException { - ComposeLayersVO designItemLayer = positionAndScaleVO.getLayers(); - // 1、校验designItem是是否存在 - DesignItem designItem = selectById(designItemLayer.getDesignItemId()); - if (Objects.isNull(designItem)){ - throw new BusinessException("design.item.does.not.exist"); - } - TDesignPythonOutfit designPythonOutfit = designPythonOutfitService.getByDesignItemId(designItemLayer.getDesignItemId()); - if (Objects.isNull(designPythonOutfit)){ - throw new BusinessException("layers.does.not.exists"); - } - - // 2、校验layers是否存在 - designItemLayer.getLayers().forEach(layer -> { - TDesignPythonOutfitDetail detail = designPythonOutfitDetailService.getById(layer.getId()); - if (Objects.isNull(detail)){ - log.error(layer.getImageCategory() + " layer does not exists!"); - throw new BusinessException("layers.does.not.exists"); - } - }); - - // 3、组装python入参 - List outfitDetailPythonItems = convertToOutfitDetailPythonItemList(designItemLayer.getLayers()); - - // 4、合成图层 - String synthesisUrl = pythonService.composeLayers(outfitDetailPythonItems); - designItemLayer.setDesignItemUrl(minioUtil.getPreSignedUrl(synthesisUrl, 24 * 60)); - - // 5、更新数据库,根据designItemId更新designItemUrl - designItem.setUpdateDate(DateUtil.getByTimeZone(positionAndScaleVO.getTimeZone())); - designItem.setDesignUrl(synthesisUrl); - designItem.setId(designItemLayer.getDesignItemId()); - designItem.setUpdateDate(DateUtil.getByTimeZone(positionAndScaleVO.getTimeZone())); - updateById(designItem); - - // 6、更新数据库,根据designItemId更新t_design_python_outfit的designUrl - TDesignPythonOutfit tDesignPythonOutfit = new TDesignPythonOutfit(); - tDesignPythonOutfit.setDesignUrl(synthesisUrl); - tDesignPythonOutfit.setId(designPythonOutfit.getId()); - tDesignPythonOutfit.setUpdateDate(LocalDateTime.now(ZoneId.of(positionAndScaleVO.getTimeZone()))); - designPythonOutfitService.updateById(tDesignPythonOutfit); - - // 7、将图层信息position和scale更新到t_design_python_outfit_detail表 - ArrayList details = new ArrayList<>(); - designItemLayer.getLayers().forEach(layer -> { - TDesignPythonOutfitDetail layerDetail = new TDesignPythonOutfitDetail(); - layerDetail.setPosition(layer.getPosition().toString()); - layerDetail.setScale(layer.getScale().toString()); - layerDetail.setId(layer.getId()); - details.add(layerDetail); - }); - designPythonOutfitDetailService.updateBatchById(details); - - // 8、返回图层及合成图信息 - designItemLayer.getLayers().forEach(layer -> { - ArrayList imageSize = new ArrayList<>(); - for (int i = 0; i < layer.getImageSize().size(); i++) { - // todo check这里的计算是否正确 - imageSize.add((long) (layer.getImageSize().get(i) * layer.getScale()[i])); - } - layer.setImageSize(imageSize); - if (!StringUtil.isNullOrEmpty(layer.getImageUrl())) { - layer.setImageUrl(minioUtil.getPreSignedUrl(layer.getImageUrl(), 24 * 60)); - } - if (!StringUtil.isNullOrEmpty(layer.getMaskUrl())) { - layer.setMaskUrl(minioUtil.getPreSignedUrl(layer.getMaskUrl(), 24 * 60)); - } - }); - - // 9、如果当前item被like过,需要更新t_user_like表和t_user_like_group表 - updateUserLikeDate(designItemLayer.getDesignItemId(),positionAndScaleVO.getTimeZone()); - return designItemLayer; - } - - private void updateUserLikeDate(Long designItemId,String timeZone){ - UserLike userLike = userLikeService.getByDesignItemId(designItemId); - if (!ObjectUtil.isEmpty(userLike)){ - Long userLikeGroupId = userLike.getUserLikeGroupId(); - // 更新t_user_like和t_user_like_group表的update_date - userLikeService.updateDate(designItemId,timeZone); - userLikeGroupService.updateDate(userLikeGroupId,timeZone); - } - } - - private DesignSingleVO assembleDesignSingleResponse(Long designItemId, String designItemUrl, - String currentFullBodyView, - List designSingleItemDTOList, - List layersObject, - String singleOrOverall, - Map categoryAndUndividedLayer) { - - DesignSingleVO designSingleVO = new DesignSingleVO(); - ArrayList clothes = new ArrayList<>(); - DesignItemClothesDetailVO body = new DesignItemClothesDetailVO("body"); - designSingleVO.setDesignItemId(designItemId); - // 图片用于修改前后的一键对比 - designSingleVO.setDesignItemUrl(designItemUrl); - // 当前全身图 - designSingleVO.setCurrentFullBodyView(minioUtil.getPreSignedUrl(currentFullBodyView, 24 * 60)); - designSingleVO.setClothes(clothes); - - // 获取每个单品的id是否被改变过,该状态需要再返回给前端 - Map idChanged = designSingleItemDTOList.stream().collect(Collectors.toMap(DesignSingleItemDTO::getId, DesignSingleItemDTO::getChanged)); - // 获取每个单品的designType,该状态需要再返回给前端 - Map idDesignType = designSingleItemDTOList.stream().collect(Collectors.toMap(DesignSingleItemDTO::getId, DesignSingleItemDTO::getDesignType)); - - boolean flag = singleOrOverall.equals("single"); - designSingleItemDTOList.forEach(singleItem -> { - DesignItemClothesDetailVO designItemClothesDetailVO = new DesignItemClothesDetailVO(); - designItemClothesDetailVO.setId(singleItem.getId()); - designItemClothesDetailVO.setChanged(idChanged.get(singleItem.getId())); - designItemClothesDetailVO.setDesignType(idDesignType.get(singleItem.getId())); - designItemClothesDetailVO.setType(singleItem.getType()); - designItemClothesDetailVO.setPath(minioUtil.getPreSignedUrl(singleItem.getPath(), 24 * 60)); - designItemClothesDetailVO.setMinIOPath(singleItem.getPath()); - designItemClothesDetailVO.setColor(panToneService.getPantoneByRgb(singleItem.getColor())); - designItemClothesDetailVO.setPrintObject(singleItem.getPrintObject()); - designItemClothesDetailVO.setTrims(singleItem.getTrims()); - designItemClothesDetailVO.setLayersObject(layersObject.stream().filter( - layers -> (singleItem.getType().toLowerCase().equals(layers.getImageCategory().split("_")[0]) - && (flag ? Boolean.TRUE : singleItem.getPriority().equals(layers.getPriority()))) - ).collect(Collectors.toList())); - designItemClothesDetailVO.setGradient(singleItem.getGradient()); - if (categoryAndUndividedLayer.containsKey(singleItem.getType().toLowerCase())) designItemClothesDetailVO.setUndividedLayer(minioUtil.getPreSignedUrl(categoryAndUndividedLayer.get(singleItem.getType().toLowerCase()), CommonConstant.MINIO_IMAGE_EXPIRE_TIME)); - body.setLayersObject(layersObject.stream().filter(layers -> layers.getImageCategory().equals("body")).collect(Collectors.toList())); - - clothes.add(designItemClothesDetailVO); - }); - clothes.add(body); - - return designSingleVO; - } - - private List setDesignItemDetailPrintList(List designItemDetails, - List designSingleItemDTOList, - String timeZone) { - - Map designItemDetailTypeIdMap = designItemDetails.stream().collect(Collectors.toMap(DesignItemDetail::getPriority, DesignItemDetail::getId)); - ArrayList designItemDetailPrints = new ArrayList<>(); - - designSingleItemDTOList.forEach(designSingleItem -> { - // 1、判断有无印花,无印花则跳过 - setDesignItemDetailPrintList(designSingleItem, designItemDetailPrints, "print", designItemDetailTypeIdMap, timeZone); - - // 2、判断有无装饰配件 - setDesignItemDetailPrintList(designSingleItem, designItemDetailPrints, "trims", designItemDetailTypeIdMap, timeZone); - }); - return designItemDetailPrints; - } - - private void setDesignItemDetailPrintList(DesignSingleItemDTO designSingleItem, - ArrayList designItemDetailPrints, - String printType, - Map designItemDetailTypeIdMap, - String timeZone){ - - // todo 这边这样做对吗 - DesignSinglePrintDTO printObject; - if (printType.equals("print")){ - printObject = designSingleItem.getPrintObject(); - }else { - printObject = designSingleItem.getTrims(); - } - - if (!CollectionUtil.isEmpty(printObject.getPrints())) { - // 2、有印花,添加到list - printObject.getPrints().forEach(print -> { - // 2.1 判断是否第一次添加印花,是:直接添加 - List designItemDetailPrintList = designItemDetailPrintService.getByDesignItemDetailId(designItemDetailTypeIdMap.get(designSingleItem.getPriority()), printType); - if (!designItemDetailPrintList.isEmpty()) { - // 2.2 否:先删除原始印花,再添加新印花信息 - designItemDetailPrintService.deleteByDesignItemDetailId(designItemDetailTypeIdMap.get(designSingleItem.getPriority())); - } - DesignItemDetailPrint designItemDetailPrint = new DesignItemDetailPrint(); - designItemDetailPrint.setDesignItemDetailId(designItemDetailTypeIdMap.get(designSingleItem.getPriority())); - designItemDetailPrint.setPrintType(printType); - designItemDetailPrint.setLevel2Type(print.getLevel2Type()); - designItemDetailPrint.setPath(print.getMinIOPath()); - designItemDetailPrint.setScale(print.getScale()); - designItemDetailPrint.setSingleOrOverall(printType.equals("print") ? print.getIfSingle() ? "single" : "overall" : "single"); - designItemDetailPrint.setCreateDate(LocalDateTime.now(ZoneId.of(timeZone))); - // single、overall模式下都有position、angle和priority - designItemDetailPrint.setPosition(print.getLocation().toString()); - designItemDetailPrint.setAngle(print.getAngle()); - designItemDetailPrint.setPriority(print.getPriority()); - designItemDetailPrints.add(designItemDetailPrint); - }); - } - } - - private List convertToOutfitDetailPythonItemList(List layers) { - List composeLayerPythonItem = Arrays.asList(new OutfitDetailPythonItem[layers.size()]); - layers.forEach(layer -> { - composeLayerPythonItem.set(layer.getPriority() - 1, new OutfitDetailPythonItem(layer.getImageCategory(), - layer.getPosition(), - layer.getImageSize(), - layer.getScale(), - layer.getImageUrl(), - layer.getMaskUrl())); - }); - return composeLayerPythonItem; - } - - @Override - public List selectDesignIdById(List designItemIdList){ - QueryWrapper queryWrapper = new QueryWrapper<>(); - - queryWrapper.in("id",designItemIdList); - return designItemMapper.selectList(queryWrapper); - } - - private void saveCollectionElement(DesignSingleIncludeLayersDTO designSingleIncludeLayersDTO){ - - ArrayList libraries = new ArrayList<>(); - // 添加sketch到library - designSingleIncludeLayersDTO.getDesignSingleItemDTOList().forEach(designSingleItem -> { - - if (!StringUtil.isNullOrEmpty(designSingleItem.getDesignType()) && designSingleItem.getDesignType().equals("Collection")){ - String path = minioUtil.getPreSignedUrl(designSingleItem.getPath(), CommonConstant.MINIO_IMAGE_EXPIRE_TIME); - try { - String md5 = MD5Utils.encryptFile(path, false); - // 先判断是否需要被加入到library - Boolean needAdd = libraryService.checkMd5(CollectionLevel1TypeEnum.SKETCH_BOARD.getRealName(), - designSingleItem.getType(), - designSingleIncludeLayersDTO.getGender(), - md5); - // 加入到library - if (needAdd){ - Library library = new Library(); - library.setAccountId(UserContext.getUserHolder().getId()); - library.setLevel1Type(CollectionLevel1TypeEnum.SKETCH_BOARD.getRealName()); - library.setLevel2Type(designSingleItem.getType()); - library.setLevel3Type(designSingleIncludeLayersDTO.getGender()); - library.setUrl(designSingleItem.getPath()); - library.setName(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))); - library.setMd5(md5); - library.setCreateDate(DateUtil.getByTimeZone(designSingleIncludeLayersDTO.getTimeZone())); - libraries.add(library); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - // 添加print到library - designSingleItem.getPrintObject().getPrints().forEach(print -> { - if (!StringUtil.isNullOrEmpty(print.getDesignType()) && print.getDesignType().equals("Collection")){ - String path = minioUtil.getPreSignedUrl(print.getMinIOPath(), CommonConstant.MINIO_IMAGE_EXPIRE_TIME); - try { - String md5 = MD5Utils.encryptFile(path, false); - // 先判断是否已被加入到library - Boolean needAdd = libraryService.checkMd5(CollectionLevel1TypeEnum.PRINT_BOARD.getRealName(), - null, - null, - md5); - // 加入到library - if (needAdd){ - Library library = new Library(); - library.setAccountId(UserContext.getUserHolder().getId()); - library.setLevel1Type(CollectionLevel1TypeEnum.PRINT_BOARD.getRealName()); - library.setUrl(print.getMinIOPath()); - library.setName(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))); - library.setMd5(md5); - library.setCreateDate(DateUtil.getByTimeZone(designSingleIncludeLayersDTO.getTimeZone())); - libraries.add(library); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - } - }); - } ); - libraryService.saveBatch(libraries); - } -} +package com.ai.da.service.impl; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.util.ObjectUtil; +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.CollectionLevel1TypeEnum; +import com.ai.da.common.enums.SingleOverallEnum; +import com.ai.da.common.enums.SysFileLevel2TypeEnum; +import com.ai.da.common.utils.*; +import com.ai.da.mapper.primary.DesignItemMapper; +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.vo.*; +import com.ai.da.python.PythonService; +import com.ai.da.python.vo.*; +import com.ai.da.service.*; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +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.apache.commons.lang3.SerializationUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.Resource; +import java.io.IOException; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.stream.Collectors; + +/** + * 服务实现类 + * + * @author yanglei + * @since 2022-09-30 + */ +@Slf4j +@Service +public class DesignItemServiceImpl extends ServiceImpl implements DesignItemService { + @Resource + private DesignItemMapper designItemMapper; + @Resource + private SysFileService sysFileService; + @Resource + private PythonService pythonService; + @Resource + private DesignService designService; + @Resource + private DesignItemDetailService designItemDetailService; + @Resource + private LibraryModelPointService libraryModelPointService; + @Resource + private LibraryService libraryService; + @Resource + private CollectionElementService collectionElementService; + @Resource + private ITDesignPythonOutfitService designPythonOutfitService; + @Resource + private ITDesignPythonOutfitDetailService designPythonOutfitDetailService; + @Resource + private PanToneService panToneService; + @Resource + private DesignItemDetailPrintService designItemDetailPrintService; + @Resource + private MinioUtil minioUtil; + @Resource + private UserLikeService userLikeService; + @Resource + private UserLikeGroupService userLikeGroupService; + + @Value("${minio.bucketName.modifiedSketch}") + private String modifiedSketchBucket; + + @Override + public Long saveOne(DesignItem designItem) { + if (designItemMapper.insertDesignItem(designItem) <= 0) { + throw new BusinessException("save.designItem.failed"); + } + return designItem.getId(); + } + + @Override + public int deleteByCollectionId(Long collectionId) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("collection_id", collectionId); + + DesignItem designItem = new DesignItem(); + designItem.setCollectionId(0L); + return designItemMapper.update(designItem, queryWrapper); + } + + @Override + public List getByDesignId(Long designId) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("design_id", designId); + queryWrapper.eq("is_like", (byte) 0); + return designItemMapper.selectList(queryWrapper); + } + + @Override + public void updateLikeStatus(Long designItemId, Byte hasLike) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("id", designItemId); + + DesignItem designItem = new DesignItem(); + designItem.setHasLike(hasLike); + designItemMapper.update(designItem, queryWrapper); + } + + @Override + public void updateDesignHighUrl(Long designItemId, String highUrl, String timeZone) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("id", designItemId); + + DesignItem designItem = new DesignItem(); + designItem.setHighDesignUrl(highUrl); + designItem.setUpdateDate(DateUtil.getByTimeZone(timeZone)); + designItemMapper.update(designItem, queryWrapper); + } + + @Override + public GetNextSysElementVO getNextSysElement(Long id, String level2Type, String operateType) { + //校验 + if (!DesignPythonItem.SYS_HAIRSTYLE_SHOES_BODY.contains(level2Type)) { + throw new BusinessException("unknown.type"); + } + List operateTypes = Arrays.asList("PREV", "NEXT"); + if (!operateTypes.contains(operateType)) { + throw new BusinessException("unknown.operateType"); + } + if (null == id) { + throw new BusinessException("id.cannot.be.empty"); + } + Long maxId = sysFileService.getMaxIdByLevel2Type(level2Type, null); + Long minId = sysFileService.getMinIdByLevel2Type(level2Type, null); + + if (id > maxId || id < minId) { + throw new BusinessException("the.id.value.is.out.of.range"); + } + Long idValue = null; + if ("PREV".equals(operateType)) { + if (minId.equals(id)) { + idValue = minId; + } else { + idValue = id - 1; + } + } + if ("NEXT".equals(operateType)) { + if (maxId.equals(id)) { + idValue = maxId; + } else { + idValue = id + 1; + } + } + SysFileVO sysFileVO = sysFileService.getById(idValue); + return new GetNextSysElementVO(sysFileVO.getId(), level2Type, sysFileVO.getUrl()); + } + + @Override + public DesignCollectionItemVO designSingle(DesignSingleDTO designSingleDTO) { + AuthPrincipalVo userInfo = UserContext.getUserHolder(); + DesignItem designItem = selectById(designSingleDTO.getDesignItemId()); + if (Objects.isNull(designItem)) { + throw new BusinessException("designItem.not.found"); + } + Design design = designService.getById(designItem.getDesignId()); + if (Objects.isNull(design)) { + throw new BusinessException("design.not.found"); + } + DesignLibraryModelPointVO designLibraryModelPointVO = null; + if (Objects.nonNull(design.getTemplateId())) { + LibraryModelPoint modelPoint = libraryModelPointService.getById(design.getTemplateId()); + if (Objects.isNull(modelPoint)) { + throw new BusinessException("modelPoint.not.found"); + } + Library library = libraryService.getById(modelPoint.getRelationId()); + // ??和上面重复 + if (Objects.isNull(library)) { + throw new BusinessException("library.not.found"); + } + designLibraryModelPointVO = collectionElementService.calculateTemplatePoint(modelPoint, library.getHigh(), library.getWidth(), library.getUrl()); + } + + Set newTypes = designSingleDTO.getClothes().stream().map(DesignSingleItemDTO::getType).collect(Collectors.toSet()); + //校验category + validateCategory(newTypes, design.getSingleOverall(), design.getSwitchCategory()); + DesignPythonObjects objects = pythonService.covertDesignSingleParam( + designSingleDTO, design.getSingleOverall(), design.getSwitchCategory(), designLibraryModelPointVO); + pythonService.design(objects); + //designSingle + DesignCollectionItemVO response = saveSingleDesignItemAndDetail(objects, design.getId(), designSingleDTO.getDesignItemId(), + design.getCollectionId(), userInfo, designSingleDTO.getTimeZone()); + // ?? + designItem.setDesignUrl(response.getDesignItemUrl()); + return response; + } + + private LibraryModelPointVO resloveVoByModelPoint(LibraryModelPoint modelPoint, Library library) { + LibraryModelPointVO libraryModelPointVO = CopyUtil.copyObject(modelPoint, LibraryModelPointVO.class); + libraryModelPointVO.setTemplateId(modelPoint.getId()); + libraryModelPointVO.setHandLeft(JSON.parseObject(modelPoint.getHandLeft(), List.class)); + libraryModelPointVO.setHandRight(JSON.parseObject(modelPoint.getHandRight(), List.class)); + libraryModelPointVO.setShoulderRight(JSON.parseObject(modelPoint.getShoulderRight(), List.class)); + libraryModelPointVO.setShoulderLeft(JSON.parseObject(modelPoint.getShoulderLeft(), List.class)); + libraryModelPointVO.setWaistbandRight(JSON.parseObject(modelPoint.getWaistbandRight(), List.class)); + libraryModelPointVO.setWaistbandLeft(JSON.parseObject(modelPoint.getWaistbandLeft(), List.class)); + return libraryModelPointVO; + } + + @Override + public String printDot(DesignSingleDTO designSingleDTO) { + DesignItem designItem = selectById(designSingleDTO.getDesignItemId()); + if (Objects.isNull(designItem)) { + throw new BusinessException("designItem.not.found"); + } + Design design = designService.getById(designItem.getDesignId()); + if (Objects.isNull(design)) { + throw new BusinessException("design.not.found"); + } + DesignLibraryModelPointVO designLibraryModelPointVO = null; + if (Objects.nonNull(design.getTemplateId())) { + LibraryModelPoint modelPoint = libraryModelPointService.getById(design.getTemplateId()); + if (Objects.isNull(modelPoint)) { + throw new BusinessException("modelPoint.not.found"); + } + Library library = libraryService.getById(modelPoint.getRelationId()); + if (Objects.isNull(library)) { + throw new BusinessException("library.not.found"); + } + designLibraryModelPointVO = collectionElementService.calculateTemplatePoint(modelPoint, library.getHigh(), library.getWidth(), library.getUrl()); + } + Set newTypes = designSingleDTO.getClothes().stream().map(DesignSingleItemDTO::getType).collect(Collectors.toSet()); + //校验category + validateCategory(newTypes, design.getSingleOverall(), design.getSwitchCategory()); + DesignPythonObjects objects = pythonService.covertDesignSingleParam( + designSingleDTO, design.getSingleOverall(), design.getSwitchCategory(), designLibraryModelPointVO); + pythonService.design(objects); + + return objects.getObjects().get(0).getBasic().getSave_name(); + } + + private void validateCategory(Set newTypes, String singleOverall, String switchCategory) { + if (SingleOverallEnum.SINGLE.getRealName().equals(singleOverall)) { + if (newTypes.size() > 1) { + throw new BusinessException("wrong.clothes.type"); + } + //一个的时候 + if (!switchCategory.equals(CollectionUtil.newArrayList(newTypes).get(0))) { + throw new BusinessException("wrong.clothes.type"); + } + } + } + // todo check这个方法是否还在用 + private DesignCollectionItemVO saveSingleDesignItemAndDetail(DesignPythonObjects pythonObjects + , Long designId, Long designItemId, Long collectionId, AuthPrincipalVo userInfo, String timeZone) { + DesignCollectionItemVO response = new DesignCollectionItemVO(); + response.setDesignItemId(designItemId); + + DesignItem designItem = new DesignItem(); + String url = pythonObjects.getObjects().get(0).getBasic().getSave_name(); + designItem.setUpdateDate(DateUtil.getByTimeZone(timeZone)); + designItem.setDesignUrl(url); + designItem.setId(designItemId); + response.setDesignItemUrl(url); + //更新item + updateById(designItem); + //删除itemDetail + designItemDetailService.deleteByDesignItemId(designItemId); + + List designItemDetails = Lists.newArrayList(); + pythonObjects.getObjects().get(0).getItems().forEach(detail -> { + if (null == detail) { + return; + } + DesignItemDetail designItemDetail = CopyUtil.copyObject(detail, DesignItemDetail.class); + designItemDetail.setAccountId(userInfo.getId()); + designItemDetail.setDesignId(designId); + designItemDetail.setDesignItemId(designItemId); + designItemDetail.setCollectionElementId(detail.getElementId()); + designItemDetail.setCreateDate(DateUtil.getByTimeZone(timeZone)); + if (SysFileLevel2TypeEnum.BODY.getRealName().equals(detail.getType())) { + designItemDetail.setPath(detail.getBody_path()); + //BODY不关联businessId + designItemDetail.setBusinessId(0L); + } + designItemDetail.setIconPath(detail.getIcon()); + // todo + DesignPythonItemPrint printObject = detail.getPrint().getSingle(); + designItemDetail.setPrintPath(Objects.isNull(printObject) ? "" : printObject.getPath()); + designItemDetail.setPrintJson(JSON.toJSONString(printObject)); + designItemDetails.add(designItemDetail); + }); + designItemDetailService.saveBatch(designItemDetails); + //封装item信息 + List designCollectionItems = CopyUtil.copyList(getByDesignId(designId) + , DesignCollectionItemVO.class, (o, d) -> { + d.setDesignItemId(o.getId()); + d.setDesignItemUrl(o.getDesignUrl()); + }); + return response; + } + + private List saveDesignSingleItemDetailAndLayers(DesignPythonObjects pythonObjects + , Long designId, Long designItemId, Long userId + , JSONObject outfit, String timeZone, List designSingleItemDTOList + , Map categoryAndUndividedLayer) { + + DesignItem designItem = new DesignItem(); +// String url = pythonObjects.getObjects().get(0).getBasic().getSave_name(); + designItem.setUpdateDate(DateUtil.getByTimeZone(timeZone)); + designItem.setDesignUrl(outfit.getString("synthesis_url")); + designItem.setId(designItemId); + // 1、更新designItem + updateById(designItem); + // 2、删除designItemDetail(逻辑删除) + designItemDetailService.deleteByDesignItemId(designItemId); + List designItemDetails = Lists.newArrayList(); + // 3、保存新的designItemDetail + pythonObjects.getObjects().get(0).getItems().forEach(detail -> { + if (null == detail) { + return; + } + DesignItemDetail designItemDetail = CopyUtil.copyObject(detail, DesignItemDetail.class); + designItemDetail.setAccountId(userId); + designItemDetail.setDesignId(designId); + designItemDetail.setDesignItemId(designItemId); + designItemDetail.setCollectionElementId(detail.getElementId()); + designItemDetail.setPriority(detail.getPriority()); + designItemDetail.setCreateDate(DateUtil.getByTimeZone(timeZone)); + if (SysFileLevel2TypeEnum.BODY.getRealName().equals(detail.getType())) { + designItemDetail.setPath(detail.getBody_path()); + //BODY不关联businessId + designItemDetail.setBusinessId(0L); + designItemDetail.setPriority(0); + } + designItemDetail.setIconPath(detail.getIcon()); + designItemDetail.setUndividedLayer(categoryAndUndividedLayer.get(detail.getType().toLowerCase())); + // 印花存储在design_item_detail_print表中 这里还要存吗? +// DesignPythonItemPrint printObject = detail.getPrintToPython(); +// designItemDetail.setPrintPath(Objects.isNull(printObject) ? "" : printObject.getPath()); +// 当有多个印花后,返回的printObject太长,导致存储到数据库时报错 +// designItemDetail.setPrintJson(JSON.toJSONString(printObject)); + designItemDetails.add(designItemDetail); + }); + // businessId 来自t_sys_file或者t_library + designItemDetailService.saveBatch(designItemDetails); + + // 4、保存印花信息到designItemDetailPrint + List designItemDetailPrints = setDesignItemDetailPrintList(designItemDetails, designSingleItemDTOList, timeZone); + designItemDetailPrintService.saveBatch(designItemDetailPrints); + + // 5、覆盖designPythonOutfit表中的模特全身图 + TDesignPythonOutfit designPythonOutfit = new TDesignPythonOutfit(); + designPythonOutfit.setDesignUrl(outfit.getString("synthesis_url")); + designPythonOutfit.setId(designPythonOutfitService.getByDesignItemId(designItemId).getId()); + designPythonOutfit.setUpdateDate(LocalDateTime.now(ZoneId.of(timeZone))); + designPythonOutfitService.updateById(designPythonOutfit); + + // 6、删除designPythonOutfitDetail表中原始的图层信息(逻辑删除) + designPythonOutfitDetailService.deleteByDesignPythonOutfitId(designPythonOutfit.getId()); + + // 7、将新生成的图层信息存入designPythonOutfitDetail表 + JSONArray layers = outfit.getJSONArray("layers"); + + Map> priorityOffset = designSingleItemDTOList.stream() + .collect(Collectors.toMap(DesignSingleItemDTO::getPriority, DesignSingleItemDTO::getOffset)); + List list = setTDesignPythonOutfitDetailList(layers, designId, designPythonOutfit.getId(), userId, priorityOffset); + + designPythonOutfitDetailService.saveBatch(list); + + return list; + } + + public List setTDesignPythonOutfitDetailList(JSONArray layers, Long designId, + Long designPythonOutfitId, Long userId, + Map> priorityOffset) { + // 设置图层信息; + List list = new ArrayList<>(); + for (int i = 0; i < layers.size(); i++) { + JSONObject jsonObject = layers.getJSONObject(i); + TDesignPythonOutfitDetail designPythonOutfitDetail = new TDesignPythonOutfitDetail(); + designPythonOutfitDetail.setDesignId(designId); + designPythonOutfitDetail.setDesignPythonOutfitId(designPythonOutfitId); + designPythonOutfitDetail.setPosition(jsonObject.getString("position")); + designPythonOutfitDetail.setImageUrl(jsonObject.getString("image_url")); + designPythonOutfitDetail.setImageSize(jsonObject.getString("image_size")); + designPythonOutfitDetail.setImageCategory(jsonObject.getString("image_category")); + designPythonOutfitDetail.setMaskUrl(jsonObject.getString("mask_url")); + designPythonOutfitDetail.setScale(Objects.isNull(jsonObject.getString("resize_scale")) ? "1.0" : jsonObject.getString("resize_scale")); + designPythonOutfitDetail.setUserId(userId); + designPythonOutfitDetail.setOffset(String.valueOf(priorityOffset.get(Math.abs(Integer.parseInt(jsonObject.getString("priority")))))); + designPythonOutfitDetail.setPriority((Integer) jsonObject.get("priority")); + list.add(designPythonOutfitDetail); + } + return list; + } + + private DesignItem selectById(Long id) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("id", id); + return designItemMapper.selectOne(queryWrapper); + } + + private Boolean exists(Long id) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("id", id); + return designItemMapper.exists(queryWrapper); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public DesignSingleVO designSingleIncludeLayers(DesignSingleIncludeLayersDTO designSingleIncludeLayersDTO) { + // 记录入参 base64数据太长,所以这里去掉 + DesignSingleIncludeLayersDTO clone = SerializationUtils.clone(designSingleIncludeLayersDTO); + clone.getDesignSingleItemDTOList().forEach( i -> { + // 渐变色 + if (!Objects.isNull(i.getGradient()) && !StringUtil.isNullOrEmpty(i.getGradient().getColorImg())){ + log.info("set gradient colorImage为空,便于日志打印"); + i.getGradient().setColorImg(null); + } + // 画笔修改过的sketch + if (!StringUtil.isNullOrEmpty(i.getSketchString())){ + log.info("set sketchString为空,便于日志打印"); + i.setSketchString(null); + } + }); + + log.info("designSingle request入参 ==> " + JSONObject.toJSONString(clone)); + + Long userId = UserContext.getUserHolder().getId(); + DesignItem designItem = selectById(designSingleIncludeLayersDTO.getDesignItemId()); + if (Objects.isNull(designItem)) { + throw new BusinessException("designItem.not.found"); + } + Design design = designService.getById(designItem.getDesignId()); + if (Objects.isNull(design)) { + throw new BusinessException("design.not.found"); + } + + DesignLibraryModelPointVO designLibraryModelPointVO = null; + // 设置模特 + if (Objects.nonNull(design.getTemplateId())) { + String modelUrl; + Integer high; + Integer width; + if (design.getModelType().equals(ModelType.SYSTEM.getValue())) { + SysFileVO sysFile = sysFileService.getById(design.getTemplateId()); + if (Objects.isNull(sysFile)) { + throw new BusinessException("model.not.found"); + } + modelUrl = sysFile.getUrl(); + high = 700; + width = 320; + } else if (design.getModelType().equals(ModelType.LIBRARY.getValue())){ + Library libFile = libraryService.getById(design.getTemplateId()); + if (Objects.isNull(libFile)) { + throw new BusinessException("model.not.found"); + } + modelUrl = libFile.getUrl(); + high = libFile.getHigh(); + width = libFile.getWidth(); + }else { + throw new BusinessException("unknown.modelType"); + } + LibraryModelPoint modelPoint = libraryModelPointService.getByRelationId(design.getTemplateId(), design.getModelType()); + if (Objects.isNull(modelPoint)) { + throw new BusinessException("modelPoint.not.found"); + } +// Assert.notNull(modelPoint, "The model has not been tagged"); + + designLibraryModelPointVO = collectionElementService.calculateTemplatePoint(modelPoint, high, width, modelUrl); + } + + // 画笔修改的sketch截图 上传后替换path + // 由于用户在系统或自己上传sketch的基础上修改过的衣服,再次修改后,第一次修改的衣服不会回到某个池子被再次利用, + // 所以,这里选择使用system或collection相同的地址,只是放在不同的桶,这样能保证图片服务器上,类似的sketch不会存在很多 + sketchBase64ToPath(designSingleIncludeLayersDTO); + + // 组装入参 + DesignPythonObjects objects = pythonService.covertDesignSingleParam( + designSingleIncludeLayersDTO, design.getSingleOverall(), design.getSwitchCategory(), designLibraryModelPointVO); + // design + JSONObject jsonObject = pythonService.designNew(objects); + // preview -> 不存数据库 submit -> 存数据库 + List tDesignPythonOutfitDetails; + JSONObject data = jsonObject.getJSONObject("data"); + if (data == null) { + throw new BusinessException("python response data is null"); + } + JSONObject outfit = data.getJSONObject("0"); + // 通过priority将offset关联到layers + Map> priorityOffset = new HashMap<>(); + try{ + priorityOffset = designSingleIncludeLayersDTO.getDesignSingleItemDTOList().stream() + .collect(Collectors.toMap(DesignSingleItemDTO::getPriority, DesignSingleItemDTO::getOffset)); + }catch (IllegalStateException e){ + // priority重复 + log.info("服装的priority重复"); + throw new BusinessException("priority.cannot.be.repeated"); + } + + JSONArray layers = outfit.getJSONArray("layers"); + Map categoryAndUndividedLayer = setTypeAndUndividedLayer(layers); + if (!designSingleIncludeLayersDTO.getIsPreview()) { + // 更新及保存图层信息 + tDesignPythonOutfitDetails = saveDesignSingleItemDetailAndLayers(objects, design.getId(), designSingleIncludeLayersDTO.getDesignItemId() + , userId, outfit, designSingleIncludeLayersDTO.getTimeZone() + , designSingleIncludeLayersDTO.getDesignSingleItemDTOList() + , categoryAndUndividedLayer); + + saveCollectionElement(designSingleIncludeLayersDTO); + } else { + tDesignPythonOutfitDetails = setTDesignPythonOutfitDetailList(layers, designItem.getDesignId(), null, userId, priorityOffset); + } + + List detailsVO = new ArrayList<>(); + + tDesignPythonOutfitDetails.forEach(detail -> { + String type = detail.getImageCategory().split("_")[0]; + detailsVO.add(designPythonOutfitDetailService.convertToDesignPythonOutfitVO(detail, null)); + }); + + TDesignPythonOutfit designPythonOutfit = designPythonOutfitService.getByDesignItemId(designSingleIncludeLayersDTO.getDesignItemId()); +// Assert.notNull(designItem, "design item detail layers does not exists!"); + + // 如果当前item被like过,需要更新t_user_like表和t_user_like_group表 + if (!designSingleIncludeLayersDTO.getIsPreview()){ + updateUserLikeDate(designSingleIncludeLayersDTO.getDesignItemId(),designSingleIncludeLayersDTO.getTimeZone()); + } + + return assembleDesignSingleResponse(designItem.getId(), + minioUtil.getPreSignedUrl(designPythonOutfit.getDesignUrl(), 24 * 60), + outfit.getString("synthesis_url"), + designSingleIncludeLayersDTO.getDesignSingleItemDTOList(), + detailsVO, + design.getSingleOverall(), + categoryAndUndividedLayer); + } + + private void sketchBase64ToPath(DesignSingleIncludeLayersDTO designSingleIncludeLayersDTO){ + designSingleIncludeLayersDTO.getDesignSingleItemDTOList().forEach(item -> { + // 如果sketch截图不为空,则将该截图上传,并替换path + if (!StringUtil.isNullOrEmpty(item.getSketchString())){ + if (StringUtil.isNullOrEmpty(item.getPath())){ + throw new BusinessException("path.cannot.be.empty"); + } + String sourcePath = item.getPath(); + String path = sourcePath.substring(sourcePath.indexOf("/") + 1, sourcePath.lastIndexOf(".")); + // 将原图地址作为修改后的图片地址,放在不同的桶 + String newPath = minioUtil.base64UploadToPath(item.getSketchString(), modifiedSketchBucket, path); + if (StringUtil.isNullOrEmpty(newPath)){ + log.error("修改过的sketch图片上传失败"); + throw new BusinessException("image.modify.failed"); + } + item.setPath(newPath); + } + }); + } + + @Override + public Map setTypeAndUndividedLayer(JSONArray layers){ + HashMap categoryAndLayer = new HashMap<>(); + for (int i = 0; i < layers.size(); i++) { + JSONObject jsonObject = layers.getJSONObject(i); + String category = jsonObject.getString("image_category").split("_")[0]; + if (!category.equals("body") && !categoryAndLayer.containsKey(category)) categoryAndLayer.put(category, jsonObject.getString("pattern_image_url")); + } + return categoryAndLayer; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public ComposeLayersVO editLayersPositionAndScale(EditLayersPositionAndScaleVO positionAndScaleVO) throws IOException { + ComposeLayersVO designItemLayer = positionAndScaleVO.getLayers(); + // 1、校验designItem是是否存在 + DesignItem designItem = selectById(designItemLayer.getDesignItemId()); + if (Objects.isNull(designItem)){ + throw new BusinessException("design.item.does.not.exist"); + } + TDesignPythonOutfit designPythonOutfit = designPythonOutfitService.getByDesignItemId(designItemLayer.getDesignItemId()); + if (Objects.isNull(designPythonOutfit)){ + throw new BusinessException("layers.does.not.exists"); + } + + // 2、校验layers是否存在 + designItemLayer.getLayers().forEach(layer -> { + TDesignPythonOutfitDetail detail = designPythonOutfitDetailService.getById(layer.getId()); + if (Objects.isNull(detail)){ + log.error(layer.getImageCategory() + " layer does not exists!"); + throw new BusinessException("layers.does.not.exists"); + } + }); + + // 3、组装python入参 + List outfitDetailPythonItems = convertToOutfitDetailPythonItemList(designItemLayer.getLayers()); + + // 4、合成图层 + String synthesisUrl = pythonService.composeLayers(outfitDetailPythonItems); + designItemLayer.setDesignItemUrl(minioUtil.getPreSignedUrl(synthesisUrl, 24 * 60)); + + // 5、更新数据库,根据designItemId更新designItemUrl + designItem.setUpdateDate(DateUtil.getByTimeZone(positionAndScaleVO.getTimeZone())); + designItem.setDesignUrl(synthesisUrl); + designItem.setId(designItemLayer.getDesignItemId()); + designItem.setUpdateDate(DateUtil.getByTimeZone(positionAndScaleVO.getTimeZone())); + updateById(designItem); + + // 6、更新数据库,根据designItemId更新t_design_python_outfit的designUrl + TDesignPythonOutfit tDesignPythonOutfit = new TDesignPythonOutfit(); + tDesignPythonOutfit.setDesignUrl(synthesisUrl); + tDesignPythonOutfit.setId(designPythonOutfit.getId()); + tDesignPythonOutfit.setUpdateDate(LocalDateTime.now(ZoneId.of(positionAndScaleVO.getTimeZone()))); + designPythonOutfitService.updateById(tDesignPythonOutfit); + + // 7、将图层信息position和scale更新到t_design_python_outfit_detail表 + ArrayList details = new ArrayList<>(); + designItemLayer.getLayers().forEach(layer -> { + TDesignPythonOutfitDetail layerDetail = new TDesignPythonOutfitDetail(); + layerDetail.setPosition(layer.getPosition().toString()); + layerDetail.setScale(layer.getScale().toString()); + layerDetail.setId(layer.getId()); + details.add(layerDetail); + }); + designPythonOutfitDetailService.updateBatchById(details); + + // 8、返回图层及合成图信息 + designItemLayer.getLayers().forEach(layer -> { + ArrayList imageSize = new ArrayList<>(); + for (int i = 0; i < layer.getImageSize().size(); i++) { + // todo check这里的计算是否正确 + imageSize.add((long) (layer.getImageSize().get(i) * layer.getScale()[i])); + } + layer.setImageSize(imageSize); + if (!StringUtil.isNullOrEmpty(layer.getImageUrl())) { + layer.setImageUrl(minioUtil.getPreSignedUrl(layer.getImageUrl(), 24 * 60)); + } + if (!StringUtil.isNullOrEmpty(layer.getMaskUrl())) { + layer.setMaskUrl(minioUtil.getPreSignedUrl(layer.getMaskUrl(), 24 * 60)); + } + }); + + // 9、如果当前item被like过,需要更新t_user_like表和t_user_like_group表 + updateUserLikeDate(designItemLayer.getDesignItemId(),positionAndScaleVO.getTimeZone()); + return designItemLayer; + } + + private void updateUserLikeDate(Long designItemId,String timeZone){ + UserLike userLike = userLikeService.getByDesignItemId(designItemId); + if (!ObjectUtil.isEmpty(userLike)){ + Long userLikeGroupId = userLike.getUserLikeGroupId(); + // 更新t_user_like和t_user_like_group表的update_date + userLikeService.updateDate(designItemId,timeZone); + userLikeGroupService.updateDate(userLikeGroupId,timeZone); + } + } + + private DesignSingleVO assembleDesignSingleResponse(Long designItemId, String designItemUrl, + String currentFullBodyView, + List designSingleItemDTOList, + List layersObject, + String singleOrOverall, + Map categoryAndUndividedLayer) { + + DesignSingleVO designSingleVO = new DesignSingleVO(); + ArrayList clothes = new ArrayList<>(); + DesignItemClothesDetailVO body = new DesignItemClothesDetailVO("body"); + designSingleVO.setDesignItemId(designItemId); + // 图片用于修改前后的一键对比 + designSingleVO.setDesignItemUrl(designItemUrl); + // 当前全身图 + designSingleVO.setCurrentFullBodyView(minioUtil.getPreSignedUrl(currentFullBodyView, 24 * 60)); + designSingleVO.setClothes(clothes); + + // 获取每个单品的id是否被改变过,该状态需要再返回给前端 + Map idChanged = designSingleItemDTOList.stream().collect(Collectors.toMap(DesignSingleItemDTO::getId, DesignSingleItemDTO::getChanged)); + // 获取每个单品的designType,该状态需要再返回给前端 + Map idDesignType = designSingleItemDTOList.stream().collect(Collectors.toMap(DesignSingleItemDTO::getId, DesignSingleItemDTO::getDesignType)); + + boolean flag = singleOrOverall.equals("single"); + designSingleItemDTOList.forEach(singleItem -> { + DesignItemClothesDetailVO designItemClothesDetailVO = new DesignItemClothesDetailVO(); + designItemClothesDetailVO.setId(singleItem.getId()); + designItemClothesDetailVO.setChanged(idChanged.get(singleItem.getId())); + designItemClothesDetailVO.setDesignType(idDesignType.get(singleItem.getId())); + designItemClothesDetailVO.setType(singleItem.getType()); + designItemClothesDetailVO.setPath(minioUtil.getPreSignedUrl(singleItem.getPath(), 24 * 60)); + designItemClothesDetailVO.setMinIOPath(singleItem.getPath()); + designItemClothesDetailVO.setColor(panToneService.getPantoneByRgb(singleItem.getColor())); + designItemClothesDetailVO.setPrintObject(singleItem.getPrintObject()); + designItemClothesDetailVO.setTrims(singleItem.getTrims()); + designItemClothesDetailVO.setLayersObject(layersObject.stream().filter( + layers -> (singleItem.getType().toLowerCase().equals(layers.getImageCategory().split("_")[0]) + && (flag ? Boolean.TRUE : singleItem.getPriority().equals(layers.getPriority()))) + ).collect(Collectors.toList())); + designItemClothesDetailVO.setGradient(singleItem.getGradient()); + if (categoryAndUndividedLayer.containsKey(singleItem.getType().toLowerCase())) designItemClothesDetailVO.setUndividedLayer(minioUtil.getPreSignedUrl(categoryAndUndividedLayer.get(singleItem.getType().toLowerCase()), CommonConstant.MINIO_IMAGE_EXPIRE_TIME)); + body.setLayersObject(layersObject.stream().filter(layers -> layers.getImageCategory().equals("body")).collect(Collectors.toList())); + + clothes.add(designItemClothesDetailVO); + }); + clothes.add(body); + + return designSingleVO; + } + + private List setDesignItemDetailPrintList(List designItemDetails, + List designSingleItemDTOList, + String timeZone) { + + Map designItemDetailTypeIdMap = designItemDetails.stream().collect(Collectors.toMap(DesignItemDetail::getPriority, DesignItemDetail::getId)); + ArrayList designItemDetailPrints = new ArrayList<>(); + + designSingleItemDTOList.forEach(designSingleItem -> { + // 1、判断有无印花,无印花则跳过 + setDesignItemDetailPrintList(designSingleItem, designItemDetailPrints, "print", designItemDetailTypeIdMap, timeZone); + + // 2、判断有无装饰配件 + setDesignItemDetailPrintList(designSingleItem, designItemDetailPrints, "trims", designItemDetailTypeIdMap, timeZone); + }); + return designItemDetailPrints; + } + + private void setDesignItemDetailPrintList(DesignSingleItemDTO designSingleItem, + ArrayList designItemDetailPrints, + String printType, + Map designItemDetailTypeIdMap, + String timeZone){ + + // todo 这边这样做对吗 + DesignSinglePrintDTO printObject; + if (printType.equals("print")){ + printObject = designSingleItem.getPrintObject(); + }else { + printObject = designSingleItem.getTrims(); + } + + if (!CollectionUtil.isEmpty(printObject.getPrints())) { + // 2、有印花,添加到list + printObject.getPrints().forEach(print -> { + // 2.1 判断是否第一次添加印花,是:直接添加 + List designItemDetailPrintList = designItemDetailPrintService.getByDesignItemDetailId(designItemDetailTypeIdMap.get(designSingleItem.getPriority()), printType); + if (!designItemDetailPrintList.isEmpty()) { + // 2.2 否:先删除原始印花,再添加新印花信息 + designItemDetailPrintService.deleteByDesignItemDetailId(designItemDetailTypeIdMap.get(designSingleItem.getPriority())); + } + DesignItemDetailPrint designItemDetailPrint = new DesignItemDetailPrint(); + designItemDetailPrint.setDesignItemDetailId(designItemDetailTypeIdMap.get(designSingleItem.getPriority())); + designItemDetailPrint.setPrintType(printType); + designItemDetailPrint.setLevel2Type(print.getLevel2Type()); + designItemDetailPrint.setPath(print.getMinIOPath()); + designItemDetailPrint.setScale(print.getScale()); + designItemDetailPrint.setSingleOrOverall(printType.equals("print") ? print.getIfSingle() ? "single" : "overall" : "single"); + designItemDetailPrint.setCreateDate(LocalDateTime.now(ZoneId.of(timeZone))); + // single、overall模式下都有position、angle和priority + designItemDetailPrint.setPosition(print.getLocation().toString()); + designItemDetailPrint.setAngle(print.getAngle()); + designItemDetailPrint.setPriority(print.getPriority()); + designItemDetailPrints.add(designItemDetailPrint); + }); + } + } + + private List convertToOutfitDetailPythonItemList(List layers) { + List composeLayerPythonItem = Arrays.asList(new OutfitDetailPythonItem[layers.size()]); + layers.forEach(layer -> { + composeLayerPythonItem.set(layer.getPriority() - 1, new OutfitDetailPythonItem(layer.getImageCategory(), + layer.getPosition(), + layer.getImageSize(), + layer.getScale(), + layer.getImageUrl(), + layer.getMaskUrl())); + }); + return composeLayerPythonItem; + } + + @Override + public List selectDesignIdById(List designItemIdList){ + QueryWrapper queryWrapper = new QueryWrapper<>(); + + queryWrapper.in("id",designItemIdList); + return designItemMapper.selectList(queryWrapper); + } + + private void saveCollectionElement(DesignSingleIncludeLayersDTO designSingleIncludeLayersDTO){ + + ArrayList libraries = new ArrayList<>(); + // 添加sketch到library + designSingleIncludeLayersDTO.getDesignSingleItemDTOList().forEach(designSingleItem -> { + + if (!StringUtil.isNullOrEmpty(designSingleItem.getDesignType()) && designSingleItem.getDesignType().equals("Collection")){ + String path = minioUtil.getPreSignedUrl(designSingleItem.getPath(), CommonConstant.MINIO_IMAGE_EXPIRE_TIME); + try { + String md5 = MD5Utils.encryptFile(path, false); + // 先判断是否需要被加入到library + Boolean needAdd = libraryService.checkMd5(CollectionLevel1TypeEnum.SKETCH_BOARD.getRealName(), + designSingleItem.getType(), + designSingleIncludeLayersDTO.getGender(), + md5); + // 加入到library + if (needAdd){ + Library library = new Library(); + library.setAccountId(UserContext.getUserHolder().getId()); + library.setLevel1Type(CollectionLevel1TypeEnum.SKETCH_BOARD.getRealName()); + library.setLevel2Type(designSingleItem.getType()); + library.setLevel3Type(designSingleIncludeLayersDTO.getGender()); + library.setUrl(designSingleItem.getPath()); + library.setName(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))); + library.setMd5(md5); + library.setCreateDate(DateUtil.getByTimeZone(designSingleIncludeLayersDTO.getTimeZone())); + libraries.add(library); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + // 添加print到library + designSingleItem.getPrintObject().getPrints().forEach(print -> { + if (!StringUtil.isNullOrEmpty(print.getDesignType()) && print.getDesignType().equals("Collection")){ + String path = minioUtil.getPreSignedUrl(print.getMinIOPath(), CommonConstant.MINIO_IMAGE_EXPIRE_TIME); + try { + String md5 = MD5Utils.encryptFile(path, false); + // 先判断是否已被加入到library + Boolean needAdd = libraryService.checkMd5(CollectionLevel1TypeEnum.PRINT_BOARD.getRealName(), + null, + null, + md5); + // 加入到library + if (needAdd){ + Library library = new Library(); + library.setAccountId(UserContext.getUserHolder().getId()); + library.setLevel1Type(CollectionLevel1TypeEnum.PRINT_BOARD.getRealName()); + library.setUrl(print.getMinIOPath()); + library.setName(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))); + library.setMd5(md5); + library.setCreateDate(DateUtil.getByTimeZone(designSingleIncludeLayersDTO.getTimeZone())); + libraries.add(library); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + }); + } ); + libraryService.saveBatch(libraries); + } + + public Long getCountByUserAndTime(String startTime, String endTime, List accountIds){ + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.gt("create_date", startTime) + .lt("create_date", endTime) + .select("count(distinct design_id) as count"); + + if (!accountIds.isEmpty()){ + queryWrapper.in("account_id", accountIds); + } + + List> result = baseMapper.selectMaps(queryWrapper); + if (result != null && !result.isEmpty()) { + Object countObj = result.get(0).get("count"); + return (Long) countObj; + }else { + return 0L; + } + } +} diff --git a/src/main/java/com/ai/da/service/impl/DesignServiceImpl.java b/src/main/java/com/ai/da/service/impl/DesignServiceImpl.java index 60bfd069..7f779570 100644 --- a/src/main/java/com/ai/da/service/impl/DesignServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/DesignServiceImpl.java @@ -1,1287 +1,1308 @@ -package com.ai.da.service.impl; - -import cn.hutool.core.collection.CollectionUtil; -import cn.hutool.core.exceptions.ExceptionUtil; -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.utils.*; -import com.ai.da.mapper.primary.DesignMapper; -import com.ai.da.mapper.primary.GenerateDetailMapper; -import com.ai.da.mapper.primary.TDesignPythonOutfitMapper; -import com.ai.da.mapper.primary.entity.*; -import com.ai.da.mapper.primary.entity.Collection; -import com.ai.da.model.dto.*; -import com.ai.da.model.vo.*; -import com.ai.da.python.PythonService; -import com.ai.da.python.vo.*; -import com.ai.da.service.*; -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.JSONObject; -import com.alibaba.fastjson.serializer.SerializerFeature; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -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 okhttp3.*; -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.io.IOException; -import java.math.BigDecimal; -import java.time.LocalDateTime; -import java.util.*; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -import static com.ai.da.python.vo.DesignPythonItem.*; - -/** - * 服务实现类 - * - * @author yanglei - * @since 2022-09-30 - */ -@Slf4j -@Service -public class DesignServiceImpl extends ServiceImpl implements DesignService { - @Resource - private DesignMapper designMapper; - @Resource - private CollectionElementService collectionElementService; - @Resource - private CollectionService collectionService; - @Resource - private PythonService pythonService; - @Resource - private LibraryService libraryService; - @Resource - private GenerateDetailMapper generateDetailMapper; - @Resource - private DesignItemService designItemService; - @Resource - private DesignItemDetailService designItemDetailService; - @Resource - private FileProperties fileProperties; - @Resource - private UserLikeGroupService userLikeGroupService; - @Resource - private UserLikeService userLikeService; - @Resource - private SysFileService sysFileService; - @Resource - private TCollectionElementRelationService tCollectionElementRelationService; - @Resource - private ITDesignPythonOutfitService designPythonOutfitService; - @Resource - private ITDesignPythonOutfitDetailService designPythonOutfitDetailService; - @Resource - private PanToneService panToneService; - @Resource - private PythonTAllInfoService pythonTAllInfoService; - @Resource - private DesignItemDetailPrintService designItemDetailPrintService; - - @Resource - private TDesignPythonOutfitMapper designPythonOutfitMapper; - - @Value("${minio.endpoint}") - private String endpoint; - @Value("${minio.bucketName.results}") - private String bucketName; - - @Value("${access.python.ip:''}") - private String accessPythonIp; - - @Value("${access.python.port:''}") - private String accessPythonPort; - - @Override - public DesignCollectionVO designCollection(DesignCollectionDTO designDTO) { - AuthPrincipalVo userInfo = UserContext.getUserHolder(); - //校验collection element - ValidateElementVO elementVO = collectionElementService.validateElement(designDTO); - //design - return designOrRedesignOperateNew(designDTO, userInfo, null, elementVO); - } - - private void calculateLibraryAndSysFile(DesignCollectionDTO designDTO, ValidateElementVO elementVO, AuthPrincipalVo userInfo) { - //查询用户 sketch library - List libraryVos; - if (CollectionUtil.isNotEmpty(designDTO.getSketchBoards())) { - List sketchUrlList = elementVO.getSketchBoardElements() - .stream() - .map(CollectionElement::getUrl) - .collect(Collectors.toList()); - DesignAttributeRetrievalDTO designAttributeRetrievalDTO = - pythonService.generateAttributeRetrieval(sketchUrlList, userInfo.getId(), elementVO.getModelSex()); - if (CollectionUtils.isEmpty(designAttributeRetrievalDTO.getLibraryUrls())) { - libraryVos = null; - } else { - libraryVos = libraryService.getByUrlList(designAttributeRetrievalDTO.getLibraryUrls(), userInfo.getId()); - } - List sysFileVOS = sysFileService.getByUrlList(designAttributeRetrievalDTO.getSysFileUrlS()); - elementVO.setSysFileVo(sysFileVOS); - } else { - libraryVos = libraryService.selectByAccountIdAnd1TypeList(userInfo.getId(), - Collections.singletonList(CollectionLevel1TypeEnum.SKETCH_BOARD.getRealName())); - } - elementVO.setLibraryVos(libraryVos); - //校验比列 - validateRatio(designDTO, libraryVos); - } - - private void validateRatio(DesignCollectionDTO designDTO, List libraryVos) { - //校验系统比列,先去掉 考虑到程序已经进入比较后面了,该校验不重要,且会产生脏数据 -// BigDecimal bigDecimal = designDTO.getSystemScale(); -// //池子是包括三部分 = 本次用户上传的sketch + library的sketch +系统的sketch,systemScale计算的是 library和sysFile的比列 -// if (/*CollectionUtil.isEmpty(designDTO.getSketchBoards()) -// && */CollectionUtils.isEmpty(libraryVos) -// && bigDecimal.compareTo(BigDecimal.ZERO) <= 0) { -// throw new BusinessException("No sketch, please increase the system rate"); -// } - } - - private void saveCollectionElemntsByLibrarys(ValidateElementVO elementVO, Long collectionId) { - if (CollectionUtils.isEmpty(elementVO.getLibraryCollectionElements())) { - return; - } - elementVO.getLibraryCollectionElements() - .forEach(element -> { - element.setCollectionId(collectionId); - Byte hasPin = element.getHasPin(); - if (Objects.isNull(hasPin)) { - element.setHasPin((byte) 0); - } - element.setId(null); - }); - List saveElements = elementVO.getLibraryCollectionElements(); - collectionElementService.saveBatch(saveElements); - elementVO.getUsedElementIds().addAll(saveElements.stream().map(CollectionElement::getId).collect(Collectors.toList())); - //sketch - List newSketchAboard = saveElements.stream() - .filter(f -> f.getLevel1Type().equals(CollectionLevel1TypeEnum.SKETCH_BOARD.getRealName())) - .collect(Collectors.toList()); - if (!CollectionUtils.isEmpty(newSketchAboard)) { - elementVO.getSketchBoardElements().addAll(newSketchAboard); - } - //print - List newPrintboard = saveElements.stream() - .filter(f -> f.getLevel1Type().equals(CollectionLevel1TypeEnum.PRINT_BOARD.getRealName())) - .collect(Collectors.toList()); - if (!CollectionUtils.isEmpty(newPrintboard)) { - elementVO.getPrintBoardElements().addAll(newPrintboard); - } - //mood - List newMoodboard = saveElements.stream() - .filter(f -> f.getLevel1Type().equals(CollectionLevel1TypeEnum.MOOD_BOARD.getRealName())) - .collect(Collectors.toList()); - if (!CollectionUtils.isEmpty(newMoodboard)) { - if (CollectionUtils.isEmpty(elementVO.getMoodBoardElements())) { - elementVO.setMoodBoardElements(new ArrayList<>()); - } - elementVO.getMoodBoardElements().addAll(newMoodboard); - } - } - - private void saveCollectionElemntsByGenerates(ValidateElementVO elementVO, Long collectionId) { - if (CollectionUtils.isEmpty(elementVO.getGenerateCollectionElements())) { - return; - } - elementVO.getGenerateCollectionElements() - .forEach(element -> { - element.setCollectionId(collectionId); - Byte hasPin = element.getHasPin(); - if (Objects.isNull(hasPin)) { - element.setHasPin((byte) 0); - } - element.setId(null); -// element.setType(DesignTypeEnum.GENERATE.getRealName()); - }); - List saveElements = elementVO.getGenerateCollectionElements(); - collectionElementService.saveBatch(saveElements); - elementVO.getUsedElementIds().addAll(saveElements.stream().map(CollectionElement::getId).collect(Collectors.toList())); - //sketch - List newSketchAboard = saveElements.stream() - .filter(f -> f.getLevel1Type().equals(CollectionLevel1TypeEnum.SKETCH_BOARD.getRealName())) - .collect(Collectors.toList()); - if (!CollectionUtils.isEmpty(newSketchAboard)) { - elementVO.getSketchBoardElements().addAll(newSketchAboard); - } - //print - List newPrintboard = saveElements.stream() - .filter(f -> f.getLevel1Type().equals(CollectionLevel1TypeEnum.PRINT_BOARD.getRealName())) - .collect(Collectors.toList()); - if (!CollectionUtils.isEmpty(newPrintboard)) { - elementVO.getPrintBoardElements().addAll(newPrintboard); - } - //mood - List newMoodboard = saveElements.stream() - .filter(f -> f.getLevel1Type().equals(CollectionLevel1TypeEnum.MOOD_BOARD.getRealName())) - .collect(Collectors.toList()); - if (!CollectionUtils.isEmpty(newMoodboard)) { - if (CollectionUtils.isEmpty(elementVO.getMoodBoardElements())) { - elementVO.setMoodBoardElements(new ArrayList<>()); - } - elementVO.getMoodBoardElements().addAll(newMoodboard); - } - } - -// private DesignCollectionVO designOrRedesignOperate(DesignCollectionDTO designDTO, AuthPrincipalVo userInfo, -// Long collectionIdParam, ValidateElementVO elementVO) { -// if (CollectionUtil.isNotEmpty(designDTO.getSketchBoards())) { -// //编辑sketchBoard -// collectionElementService.editSketchBoardsElement(elementVO, designDTO.getSketchBoards()); -// } -// if (CollectionUtil.isNotEmpty(designDTO.getPrintBoards())) { -// //编辑printBoard -// collectionElementService.editPrintBoardsElement(elementVO, designDTO.getPrintBoards()); -// } -// //保存collection -// Long collectionId = (null == collectionIdParam) ? -// collectionService.saveCollection(userInfo.getId(), designDTO.getTimeZone(), designDTO.getMoodTemplateId()) : collectionIdParam; -// List elementIds = getElementId(elementVO); -// //批量关联element 到 collection -// collectionElementService.relationCollection(elementIds, collectionId); -// //library转化为collection(生成) -// saveCollectionElemntsByLibrarys(elementVO, collectionId); -// //保存颜色版 -// List colorElementList = collectionElementService.saveColorBoard(designDTO.getColorBoards(), collectionId, designDTO.getTimeZone()); -// //保存design -// Long designId = saveOne(designDTO, collectionId, userInfo.getId()); -// //计算library -// calculateLibraryAndSysFile(designDTO, elementVO, userInfo); -// //组装design入参 -// DesignPythonObjects pythonObjects = pythonService.covertDesignParam(designDTO.getSystemScale(), -// designDTO.getSingleOverall(), designDTO.getSwitchCategory(), elementVO, designDTO.getProcessId()); -// //缓存保存的文件 方便后面处理进度问题 采用新的进度条获取方式 根据processId获取 -//// setDesignProcess(userInfo.getId(), pythonObjects); -// //design -// pythonService.design(pythonObjects); -// //生成library -// generateLibrary(elementVO, designDTO.getTimeZone()); -// //处理关联关系,修复element覆盖得情况 -// List reLationelements = collectionElementService.getByOnlyCollectionId(collectionId); -// List reLationelementIds = reLationelements.stream().map(CollectionElement::getId).collect(Collectors.toList()); -// handleCollectionElementRelation(collectionId, (null == collectionIdParam) ? false : true, reLationelementIds); -// //保存python返回信息 -//// return savePythonDesignItemAndDetail(pythonObjects,designId,collectionId,userInfo,designDTO.getTimeZone(),responseJSONObject); -// //保存designItem 和detail -// return saveDesignItemAndDetail(pythonObjects, designId, collectionId, userInfo, designDTO.getTimeZone()); -// } - - private DesignCollectionVO designOrRedesignOperateNew(DesignCollectionDTO designDTO, AuthPrincipalVo userInfo, - Long collectionIdParam, ValidateElementVO elementVO) { - if (CollectionUtil.isNotEmpty(designDTO.getSketchBoards())) { - //编辑sketchBoard - collectionElementService.editSketchBoardsElement(elementVO, designDTO.getSketchBoards()); - } - if (CollectionUtil.isNotEmpty(designDTO.getPrintBoards())) { - //编辑printBoard - collectionElementService.editPrintBoardsElement(elementVO, designDTO.getPrintBoards()); - } - //保存collection - Long collectionId = (null == collectionIdParam) ? - collectionService.saveCollection(userInfo.getId(), designDTO.getTimeZone(), designDTO.getMoodTemplateId()) : collectionIdParam; - List elementIds = getElementId(elementVO); - //批量关联element 到 collection - collectionElementService.relationCollection(elementIds, collectionId); - //library转化为collection(生成) - saveCollectionElemntsByLibrarys(elementVO, collectionId); - //generate转化为collection(生成) - saveCollectionElemntsByGenerates(elementVO, collectionId); - //保存颜色版 - collectionElementService.saveColorBoard(designDTO.getColorBoards(), collectionId, designDTO.getTimeZone()); - //保存design - Long designId = saveOne(designDTO, collectionId, userInfo.getId()); - //计算library -// calculateLibraryAndSysFile(designDTO, elementVO, userInfo); - //组装design入参 - long startTime = System.currentTimeMillis(); - DesignPythonObjects pythonObjects = pythonService.covertDesignParam(designDTO.getSystemScale(), - designDTO.getSingleOverall(), designDTO.getSwitchCategory(), elementVO, designDTO.getProcessId()); - long endTime = System.currentTimeMillis(); - long totalTimeInSeconds = (endTime - startTime) / 1000; - log.info("组装入参运行时间:" + totalTimeInSeconds + " 秒"); - // pythonObjects增加image_id关联 - startTime = System.currentTimeMillis(); - List imageIds = relationImageIds(pythonObjects); - endTime = System.currentTimeMillis(); - totalTimeInSeconds = (endTime - startTime) / 1000; - log.info("增加image_id关联运行时间:" + totalTimeInSeconds + " 秒"); - //design - startTime = System.currentTimeMillis(); - JSONObject responseJSONObject = pythonService.designNew(pythonObjects); - endTime = System.currentTimeMillis(); - totalTimeInSeconds = (endTime - startTime) / 1000; - log.info("design python端运行时间:" + totalTimeInSeconds + " 秒"); - //生成library - startTime = System.currentTimeMillis(); - generateLibrary(elementVO, designDTO.getTimeZone()); - //处理关联关系,修复element覆盖得情况 - List relationElements = collectionElementService.getByOnlyCollectionId(collectionId); - List relationElementIds = relationElements.stream().map(CollectionElement::getId).collect(Collectors.toList()); - handleCollectionElementRelation(collectionId, null != collectionIdParam, relationElementIds); - endTime = System.currentTimeMillis(); - totalTimeInSeconds = (endTime - startTime) / 1000; - log.info("处理关联关系运行时间:" + totalTimeInSeconds + " 秒"); - //保存python返回信息;保存designItem和detail - return savePythonDesignItemAndDetail(pythonObjects, designId, collectionId, userInfo, designDTO.getTimeZone(), responseJSONObject, designDTO.getSingleOverall()); - } - - @Override - public void relationImageId(DesignPythonObjects pythonObjects) { - if (Objects.isNull(pythonObjects)) { - return; - } - pythonObjects.getObjects().forEach( - o -> { - for (DesignPythonItem item : o.getItems()) { - List list = new ArrayList<>(); - list.add(1L); - list.add(1L); - item.setOffset(list); - item.setResize_scale(new Float[]{1.0f,1.0f}); - String path = item.getPath(); - if (StringUtils.isEmpty(path)) { - String bodyPath = item.getBody_path(); - Long imageId = pythonTAllInfoService.getImageIdByPath(bodyPath); - item.setImage_id(imageId); - } else { - Long imageId = pythonTAllInfoService.getImageIdByPath(path); - item.setImage_id(imageId); - } - } - } - ); - } - - @Override - public List sketchesBoundingBox(SketchesBoundingBoxDTO sketchesBoundingBoxDTO) { - List sketchBoards = sketchesBoundingBoxDTO.getSketchBoards(); - if (CollectionUtil.isNotEmpty(sketchBoards)) { - List result = new ArrayList<>(); - List collect = sketchBoards.stream() - .filter(o -> !o.getDesignType().equals(DesignTypeEnum.LIBRARY.getRealName())) - .collect(Collectors.toList()); - if (CollectionUtil.isNotEmpty(collect)) { - for (CollectionSketchDTO collectionSketchDTO : collect) { - CollectionSketchVO vo = CopyUtil.copyObject(collectionSketchDTO, CollectionSketchVO.class); - if (collectionSketchDTO.getDesignType().equals(DesignTypeEnum.COLLECTION.getRealName())) { - CollectionElement byId = collectionElementService.getById(collectionSketchDTO.getSketchBoardId()); - libraryService.processSketchBoards(byId.getUrl(), collectionSketchDTO.getLevel2Type()); - String url = byId.getUrl(); - if (url.contains(".")) { - String[] split = url.split("\\."); - vo.setUrlWithWhiteSide(minioUtil.getPreSignedUrl(split[0] + "-show." + split[1], 24 * 60)); - }else { - vo.setUrlWithWhiteSide(minioUtil.getPreSignedUrl(url + "-show", 24 * 60)); - } - result.add(vo); - }else if (collectionSketchDTO.getDesignType().equals(DesignTypeEnum.GENERATE.getRealName())) { - GenerateDetail generateDetail = generateDetailMapper.selectById(collectionSketchDTO.getSketchBoardId()); - libraryService.processSketchBoards(generateDetail.getUrl(), collectionSketchDTO.getLevel2Type()); - String url = generateDetail.getUrl(); - if (url.contains(".")) { - String[] split = url.split("\\."); - vo.setUrlWithWhiteSide(minioUtil.getPreSignedUrl(split[0] + "-show." + split[1], 24 * 60)); - }else { - vo.setUrlWithWhiteSide(minioUtil.getPreSignedUrl(url + "-show", 24 * 60)); - } - result.add(vo); - } - } - } - List libraryList = sketchBoards.stream() - .filter(o -> o.getDesignType().equals(DesignTypeEnum.LIBRARY.getRealName())) - .collect(Collectors.toList()); - for (CollectionSketchDTO collectionSketchDTO : libraryList) { - Library byId = libraryService.getById(collectionSketchDTO.getSketchBoardId()); - libraryService.processSketchBoards(byId.getUrl(), collectionSketchDTO.getLevel2Type()); - CollectionSketchVO vo = CopyUtil.copyObject(collectionSketchDTO, CollectionSketchVO.class); - String url = byId.getUrl(); - if (url.contains(".")) { - String[] split = url.split("\\."); - vo.setUrlWithWhiteSide(minioUtil.getPreSignedUrl(split[0] + "-show." + split[1], 24 * 60)); - }else { - vo.setUrlWithWhiteSide(minioUtil.getPreSignedUrl(url + "-show", 24 * 60)); - } - result.add(vo); - } - return result; - } - return new ArrayList<>(); - } - - public List relationImageIds(DesignPythonObjects pythonObjects) { - List imageIds = new ArrayList<>(); - if (Objects.isNull(pythonObjects)) { - return imageIds; - } - pythonObjects.getObjects().forEach( - o -> { - for (DesignPythonItem item : o.getItems()) { - List list = new ArrayList<>(); - list.add(1L); - list.add(1L); - item.setOffset(list); - item.setResize_scale(new Float[]{1.0f,1.0f}); - String path = item.getPath(); - if (StringUtils.isEmpty(path)) { - String bodyPath = item.getBody_path(); - Long imageId = pythonTAllInfoService.getImageIdByPath(bodyPath); - imageIds.add(imageId); - item.setImage_id(imageId); - } else { - Long imageId = pythonTAllInfoService.getImageIdByPath(path); - imageIds.add(imageId); - item.setImage_id(imageId); - } - } - } - ); - return imageIds; - } - - private void handleCollectionElementRelation(Long collectionId, Boolean isEdit, List elementIds) { - if (CollectionUtils.isEmpty(elementIds) || collectionId == null) { - return; - } - if (isEdit) { - //删除 - tCollectionElementRelationService.deleteByCollectionId(collectionId); - } - //新增 - tCollectionElementRelationService.saveBatch(elementIds.stream().map(elementId -> - TCollectionElementRelation.builder() - .collectionId(collectionId) - .elementId(elementId) - .createDate(new Date()) - .build() - ).collect(Collectors.toList())); - } - - private void generateLibrary(ValidateElementVO elementVO, String timeZone) { - List elements = Lists.newArrayList(); - if (!CollectionUtils.isEmpty(elementVO.getMoodBoardElements())) { - elements.addAll(elementVO.getMoodBoardElements()); - } - if (!CollectionUtils.isEmpty(elementVO.getPrintBoardElements())) { - elements.addAll(elementVO.getPrintBoardElements()); - } - if (!CollectionUtils.isEmpty(elementVO.getSketchBoardElements())) { - elements.addAll(elementVO.getSketchBoardElements()); - } - if (!CollectionUtils.isEmpty(elementVO.getMarketingSketchElements())) { - elements.addAll(elementVO.getMarketingSketchElements()); - } - collectionElementService.saveLibraryByCollectionElement(elements, timeZone, elementVO.getModelSex()); - } - - @Override - public BigDecimal countDesignProcess() { - AuthPrincipalVo userInfo = UserContext.getUserHolder(); - List saveNames = LocalCacheUtils.getDesignProcessCache(userInfo.getId()); - if (CollectionUtils.isEmpty(saveNames)) { - return BigDecimal.ZERO; - } - int totalProcess = 0; - log.info("design 统计进度###totalProcess1{}", totalProcess); - //转成本地文件先 - for (String saveName : saveNames) { - String localFileUrl = saveName; - String linuxDomain = fileProperties.getLinuxDomain(); - if (!StringUtils.isEmpty(linuxDomain)) { - //linux 系统 - String oldPath = fileProperties.getSys().getPath(); - localFileUrl = saveName.replace(linuxDomain, oldPath); - } - File file = new File(localFileUrl); - if (file.exists()) { - totalProcess++; - log.info("design 统计进度++###totalProcess+++{}", totalProcess); - } - } - log.info("design 统计进度###totalProcess2{}", totalProcess); - BigDecimal result = BigDecimal.valueOf(totalProcess).divide(BigDecimal.valueOf(8)).setScale(3, BigDecimal.ROUND_HALF_UP); - if (result.compareTo(BigDecimal.ONE) == 0) { - LocalCacheUtils.delDesignProcessCache(userInfo.getId()); - } - return result; - } - - private void setDesignProcess(Long userId, DesignPythonObjects pythonObjects) { - List saveNames = pythonObjects.getObjects().stream().map(object -> { - return object.getBasic().getSave_name(); - }).collect(Collectors.toList()); - LocalCacheUtils.setDesignProcessCache(userId, saveNames); - } - - @Resource - private MinioUtil minioUtil; - - private DesignCollectionVO savePythonDesignItemAndDetail(DesignPythonObjects pythonObjects - , Long designId, Long collectionId, AuthPrincipalVo userInfo, String timeZone, JSONObject responseJSONObject, String singleOverall) { - DesignCollectionVO response = new DesignCollectionVO(); - response.setDesignId(designId); - response.setCollectionId(collectionId); - List designCollectionItems = Lists.newArrayList(); - response.setDesignCollectionItems(designCollectionItems); - JSONObject data = responseJSONObject.getJSONObject("data"); - if (data == null) { - throw new BusinessException("design.interface.exception"); - } - for (int i = 0; i < pythonObjects.getObjects().size(); i++) { - DesignPythonObject item = pythonObjects.getObjects().get(i); - DesignItem designItem = new DesignItem(); - designItem.setAccountId(userInfo.getId()); - designItem.setCollectionId(collectionId); - designItem.setDesignId(designId); - designItem.setCreateDate(DateUtil.getByTimeZone(timeZone)); - //生成的八张图片 - designItem.setDesignUrl(item.getBasic().getSave_name()); - designItem.setHasLike((byte) 0); - //生成designItem - Long designItemId = designItemService.saveOne(designItem); - // python design返回入库及封装 - JSONObject outfit = data.getJSONObject(i + ""); - if (null == outfit) { - continue; - } - TDesignPythonOutfit designPythonOutfit = new TDesignPythonOutfit(); - designPythonOutfit.setDesignItemId(designItemId); - designPythonOutfit.setUserId(userInfo.getId()); - designPythonOutfit.setDesignId(designId); - designPythonOutfit.setCollectionId(collectionId); - String synthesisUrl = outfit.getString("synthesis_url"); - if (!StringUtils.isEmpty(synthesisUrl)) { - designPythonOutfit.setDesignUrl(synthesisUrl); - } else { - throw new BusinessException("design.interface.exception"); - } - designPythonOutfitService.save(designPythonOutfit); - JSONArray layers = outfit.getJSONArray("layers"); - List list = new ArrayList<>(); - DesignCollectionItemVO designCollectionItemVO = new DesignCollectionItemVO(); - for (int i1 = 0; i1 < layers.size(); i1++) { - JSONObject jsonObject = layers.getJSONObject(i1); - TDesignPythonOutfitDetail designPythonOutfitDetail = new TDesignPythonOutfitDetail(); - designPythonOutfitDetail.setDesignId(designId); - designPythonOutfitDetail.setDesignPythonOutfitId(designPythonOutfit.getId()); - designPythonOutfitDetail.setPosition(jsonObject.getString("position")); - designPythonOutfitDetail.setImageSize(jsonObject.getString("image_size")); - designPythonOutfitDetail.setImageUrl(jsonObject.getString("image_url")); - if (singleOverall.equals(SingleOverallEnum.SINGLE.getRealName())) { - designCollectionItemVO.setDesignItemUrl(designItem.getDesignUrl()); - } - designPythonOutfitDetail.setImageCategory(jsonObject.getString("image_category")); - designPythonOutfitDetail.setMaskUrl(jsonObject.getString("mask_url")); - designPythonOutfitDetail.setUserId(userInfo.getId()); - designPythonOutfitDetail.setPriority(Integer.parseInt(jsonObject.getString("priority"))); - designPythonOutfitDetail.setCreateDate(LocalDateTime.now()); - list.add(designPythonOutfitDetail); - } - designPythonOutfitDetailService.saveBatch(list); - designCollectionItemVO.setDesignItemId(designItemId); - designCollectionItemVO.setDesignItemUrl(designItem.getDesignUrl()); - designCollectionItemVO.setDesignOutfitId(designPythonOutfit.getId()); - String designUrl = designPythonOutfit.getDesignUrl(); - if (!StringUtils.isEmpty(designUrl) && designUrl.contains("/")) { - int firstIndex = designUrl.indexOf("/"); - designCollectionItemVO.setDesignOutfitUrl(minioUtil.getPreSignedUrl(designUrl.substring(0, firstIndex) + "/" + designUrl.substring(firstIndex + 1), 24 * 60)); - } - //response - designCollectionItems.add(designCollectionItemVO); - - List designItemDetails = Lists.newArrayList(); - Map typePriority = list.stream().collect(Collectors.toMap(d -> d.getImageCategory().split("_")[0], - d -> Math.abs(d.getPriority()), - (existing, replacement) -> replacement)); - Map typeAndUndividedLayer = designItemService.setTypeAndUndividedLayer(layers); - for (DesignPythonItem detail : item.getItems()) { - if (null == detail) { - continue; - } - DesignItemDetail designItemDetail = CopyUtil.copyObject(detail, DesignItemDetail.class); - designItemDetail.setAccountId(userInfo.getId()); - designItemDetail.setDesignId(designId); - designItemDetail.setDesignItemId(designItemId); - designItemDetail.setCollectionElementId(detail.getElementId()); - designItemDetail.setCreateDate(DateUtil.getByTimeZone(timeZone)); - designItemDetail.setUndividedLayer(typeAndUndividedLayer.get(designItemDetail.getType().toLowerCase())); - if (SysFileLevel2TypeEnum.BODY.getRealName().equals(detail.getType())) { - designItemDetail.setPath(detail.getBody_path()); - //BODY不关联businessId - designItemDetail.setBusinessId(0L); - } - designItemDetail.setIconPath(detail.getIcon()); - designItemDetail.setPriority(typePriority.get(detail.getType().toLowerCase())); - if (!detail.getType().equals("Body")){ - DesignPythonItemPrint printObject = detail.getPrint().getOverall(); -// designItemDetail.setPrintPath(Objects.isNull(printObject) ? "" : printObject.getPath()); - designItemDetail.setPrintPath(CollectionUtils.isEmpty(printObject.getPrint_path_list()) ? "" : printObject.getPrint_path_list().get(0)); - } - designItemDetailService.save(designItemDetail); - if (!SysFileLevel2TypeEnum.BODY.getRealName().equals(detail.getType()) && !StringUtil.isNullOrEmpty(designItemDetail.getPrintPath())) { - DesignItemDetailPrint print = new DesignItemDetailPrint(); - print.setDesignItemDetailId(designItemDetail.getId()); - print.setPrintType("print"); - print.setPath(designItemDetail.getPrintPath()); - print.setSingleOrOverall("overall"); - print.setPosition("[0.0,0.0]"); -// print.setScale(1d); - // todo mark 将print默认scale置为0.3 - print.setScale(0.3d); - print.setAngle(0.0); - print.setPriority(1); - QueryWrapper getPrintboardLevel2TypeQw = new QueryWrapper<>(); - getPrintboardLevel2TypeQw.lambda().eq(CollectionElement::getUrl, print.getPath()); - getPrintboardLevel2TypeQw.lambda().orderByDesc(CollectionElement::getCreateDate); - getPrintboardLevel2TypeQw.last("limit 1"); - CollectionElement one = collectionElementService.getOne(getPrintboardLevel2TypeQw); - print.setLevel2Type(one.getLevel2Type()); - print.setCreateDate(LocalDateTime.now()); - designItemDetailPrintService.save(print); - } - } - } - response.setProcessId(pythonObjects.getProcess_id()); - return response; - } - - private DesignCollectionVO saveDesignItemAndDetail(DesignPythonObjects pythonObjects - , Long designId, Long collectionId, AuthPrincipalVo userInfo, String timeZone) { - DesignCollectionVO response = new DesignCollectionVO(); - response.setDesignId(designId); - response.setCollectionId(collectionId); - List designCollectionItems = Lists.newArrayList(); - response.setDesignCollectionItems(designCollectionItems); - - pythonObjects.getObjects().forEach(item -> { - DesignItem designItem = new DesignItem(); - designItem.setAccountId(userInfo.getId()); - designItem.setCollectionId(collectionId); - designItem.setDesignId(designId); - designItem.setCreateDate(DateUtil.getByTimeZone(timeZone)); - //生成的八张图片 - designItem.setDesignUrl(item.getBasic().getSave_name()); - designItem.setHasLike((byte) 0); - //生成designItem - Long designItemId = designItemService.saveOne(designItem); - //response - designCollectionItems.add(new DesignCollectionItemVO(designItemId, designItem.getDesignUrl(), null, null)); - - List designItemDetails = Lists.newArrayList(); - item.getItems().forEach(detail -> { - if (null == detail) { - return; - } - DesignItemDetail designItemDetail = CopyUtil.copyObject(detail, DesignItemDetail.class); - designItemDetail.setAccountId(userInfo.getId()); - designItemDetail.setDesignId(designId); - designItemDetail.setDesignItemId(designItemId); - designItemDetail.setCollectionElementId(detail.getElementId()); - designItemDetail.setCreateDate(DateUtil.getByTimeZone(timeZone)); - if (SysFileLevel2TypeEnum.BODY.getRealName().equals(detail.getType())) { - designItemDetail.setPath(detail.getBody_path()); - //BODY不关联businessId - designItemDetail.setBusinessId(0L); - } - designItemDetail.setIconPath(detail.getIcon()); - DesignPythonItemPrint printObject = detail.getPrint().getOverall(); - designItemDetail.setPrintPath(Objects.isNull(printObject) ? "" : printObject.getPath()); - designItemDetails.add(designItemDetail); - }); - designItemDetailService.saveBatch(designItemDetails); - }); - return response; - } - - private List getElementId(ValidateElementVO elementVO) { - List elementIds = Lists.newArrayList(); - // collection type - if (CollectionUtil.isNotEmpty(elementVO.getSketchBoardElements())) { - elementIds.addAll(elementVO.getSketchBoardElements().stream().map(CollectionElement::getId).collect(Collectors.toList())); - } - if (CollectionUtil.isNotEmpty(elementVO.getMoodBoardElements())) { - elementIds.addAll(elementVO.getMoodBoardElements().stream().map(CollectionElement::getId).collect(Collectors.toList())); - } - if (CollectionUtil.isNotEmpty(elementVO.getPrintBoardElements())) { - elementIds.addAll(elementVO.getPrintBoardElements().stream().map(CollectionElement::getId).collect(Collectors.toList())); - } -// if(CollectionUtil.isNotEmpty(elementVO.getMarketingSketchElements())){ -// elementIds.addAll(elementVO.getMarketingSketchElements().stream().map(CollectionElement::getId).collect(Collectors.toList())); -// } - return elementIds; - } - - @Override - public DesignCollectionVO reDesignCollection(ReDesignCollectionDTO reDesignDTO) { - //校验collection - Collection collection = collectionService.getById(reDesignDTO.getCollectionId()); - if (Objects.isNull(collection)) { - throw new BusinessException("collection.not.found"); - } - AuthPrincipalVo userInfo = UserContext.getUserHolder(); -// //查询用户 sketch library -// List libraryVos = libraryService.selectByAccountIdAnd1TypeList(userInfo.getId(), -// Arrays.asList(CollectionLevel1TypeEnum.PRINT_BOARD.getRealName(), -// CollectionLevel1TypeEnum.SKETCH_BOARD.getRealName())); - //校验collection element - DesignCollectionDTO designCollectionDTO = CopyUtil.copyObject(reDesignDTO, DesignCollectionDTO.class); - ValidateElementVO elementVO = collectionElementService.validateElement(designCollectionDTO); - //计算并删除对应的未关联的element - List longs = calculateNoRelationElement(reDesignDTO.getCollectionId(), elementVO.getUsedElementIds()); - if (!CollectionUtils.isEmpty(longs)) { - collectionElementService.batchDelete(longs); - } - Design oldDesign = selectByCollectionId(reDesignDTO.getCollectionId()); - //删除老的关联的design - deleteByCollectionId(reDesignDTO.getCollectionId()); - designItemService.deleteByCollectionId(reDesignDTO.getCollectionId()); - designItemDetailService.deleteByDesignId(oldDesign.getId()); - //redesign - return designOrRedesignOperateNew(CopyUtil.copyObject( - reDesignDTO, DesignCollectionDTO.class), userInfo, reDesignDTO.getCollectionId(), elementVO); - } - - private List calculateNoRelationElement(Long collectionId, List usedElementIds) { - List collectionElements = collectionElementService.getByCollectionId(collectionId); - if (CollectionUtils.isEmpty(collectionElements)) { -// throw new BusinessException("get collection elements cannot be empty"); - return new ArrayList<>(); - } - if (CollectionUtils.isEmpty(usedElementIds)) { - return collectionElements.stream().map(CollectionElement::getId).collect(Collectors.toList()); - } - return collectionElements.stream() - .filter(filter -> !usedElementIds.contains(filter.getId())) - .map(CollectionElement::getId) - .collect(Collectors.toList()); - } - - @Override - public DesignCollectionVO designItemList(Long designId) { - Design design = baseMapper.selectById(designId); - if (Objects.isNull(design)) { - throw new BusinessException("design.not.found"); - } - List designItems = designItemService.getByDesignId(designId); - if (CollectionUtils.isEmpty(designItems)) { - return new DesignCollectionVO(designId, design.getCollectionId(), null, null); - } - return new DesignCollectionVO(designId, design.getCollectionId(), coverDesignItemToVO(designItems), null); - } - - private List coverDesignItemToVO(List designItems) { - List response = Lists.newArrayList(); - designItems.forEach(designItem -> { - response.add(new DesignCollectionItemVO(designItem.getId(), designItem.getDesignUrl(), null, null)); - }); - return response; - } - - @Override - @Transactional(rollbackFor = Exception.class) - public DesignLikeVO like(DesignLikeDTO designLikeDTO) { - Long userGroupId = designLikeDTO.getUserGroupId();; - Long groupDetailId; - AuthPrincipalVo userInfo = UserContext.getUserHolder(); - DesignItem designItem = designItemService.getById(designLikeDTO.getDesignItemId()); - if (Objects.isNull(designItem)) { - throw new BusinessException("designItem.not.found"); - } - String pictureName = null; - UserLike userLike; - if (Objects.nonNull(userGroupId)) { - UserLikeGroup userLikeGroup = userLikeGroupService.getById(userGroupId); - if (Objects.isNull(userLikeGroup)) { - throw new BusinessException("userLikeGroup.not.found"); - } -// if(designItem.getCollectionId().equals(userLikeGroup.getCollectionId())){ -// //相同collection直接跳过 不需要往element加元素 -// return new DesignLikeVO(); -// } - List oldElements = collectionElementService.getByCollectionId(userLikeGroup.getCollectionId()); - if (CollectionUtil.isEmpty(oldElements)) { - throw new BusinessException("old.elements.not.found"); - } - List designItemDetails = designItemDetailService.selectByDesignItemId(designLikeDTO.getDesignItemId()); - if (CollectionUtil.isEmpty(designItemDetails)) { - throw new BusinessException("new.designItemDetails.not.found"); - } - //判断老的element合并到新的是否满足 数量不超过15 - List newElementIds = validateMergeElement(oldElements, designItemDetails); - //合并,关联新的element到collection - collectionElementService.relationCollection(newElementIds, userLikeGroup.getCollectionId()); - //处理关联关系,修复element覆盖得情况 - handleCollectionElementRelation(userLikeGroup.getCollectionId(), false, newElementIds); - - QueryWrapper qw = new QueryWrapper<>(); - qw.lambda().eq(TDesignPythonOutfit::getDesignItemId, designLikeDTO.getDesignItemId()); - List tDesignPythonOutfits = designPythonOutfitMapper.selectList(qw); - if (CollectionUtils.isEmpty(tDesignPythonOutfits)) { - throw new BusinessException("DesignItemId not found elements for ax elements to like! [" + designLikeDTO.getDesignItemId()); - } - userLike = resolveUserLike(userGroupId, designItem.getDesignId(), - designLikeDTO.getDesignItemId(), designLikeDTO.getDesignPythonOutfitId(), tDesignPythonOutfits.get(0).getDesignUrl(), designLikeDTO.getTimeZone()); - - } else { - //第一次like - userGroupId = userLikeGroupService.insertUserGroup(userInfo.getId(), designItem.getCollectionId(), designLikeDTO.getTimeZone()); - QueryWrapper qw = new QueryWrapper<>(); - qw.lambda().eq(TDesignPythonOutfit::getDesignItemId, designLikeDTO.getDesignItemId()); - List tDesignPythonOutfits = designPythonOutfitMapper.selectList(qw); - if (CollectionUtils.isEmpty(tDesignPythonOutfits)) { - throw new BusinessException("DesignItemId not found elements for ax elements to like! [" + designLikeDTO.getDesignItemId()); - } - userLike = resolveUserLike(userGroupId, - designItem.getDesignId(), designLikeDTO.getDesignItemId(), designLikeDTO.getDesignPythonOutfitId(), tDesignPythonOutfits.get(0).getDesignUrl(), designLikeDTO.getTimeZone()); - } - userLikeService.save(userLike); - groupDetailId = userLike.getId(); - String designUrl = designPythonOutfitMapper.selectById(userLike.getDesignOutfitId()).getDesignUrl(); - if (designUrl.contains("/")) { - int i = designUrl.lastIndexOf("/"); - pictureName = designUrl.substring(i + 1); - } - //修改designItem为like状态 - designItemService.updateLikeStatus(designLikeDTO.getDesignItemId(), (byte) 1); - return new DesignLikeVO(userGroupId, groupDetailId, pictureName); - } - - private List validateMergeElement(List oldElements, List designItemDetails) { - List hasCollections = designItemDetails.stream() - .filter(f -> Objects.nonNull(f.getCollectionElementId())) - .collect(Collectors.toList()); - if (CollectionUtils.isEmpty(hasCollections)) { - return null; - } - List oldIds = oldElements.stream().map(CollectionElement::getId).collect(Collectors.toList()); - List elementIds = hasCollections.stream().map(DesignItemDetail::getCollectionElementId).collect(Collectors.toList()); - //本次新增collection个数 - List adds = elementIds.stream().filter(id -> !oldIds.contains(id)).collect(Collectors.toList()); - if (CollectionUtils.isEmpty(adds)) { - return null; - } - //校验15次 - Map> group = oldElements.stream() - .collect(Collectors.groupingBy(CollectionElement::getLevel1Type)); - - group.forEach((k, v) -> { - List thisElement = group.get(k); - int groupNum = calculateGroupNum(thisElement, adds); - if (groupNum > 15) { - throw new BusinessException("The size of element type" + k + "exceeds 15"); - } - }); - return adds; - } - - private int calculateGroupNum(List thisElement, List adds) { - int num = 0; - List groupOldIds = thisElement.stream().map(CollectionElement::getId).collect(Collectors.toList()); - for (Long add : adds) { - if (groupOldIds.contains(add)) { - num++; - } - } - return num + thisElement.size(); - } - - private UserLike resolveUserLike(Long userGroupId, Long designId, Long designItemId, Long designPythonOutfitId, String designUrl, String timeZone) { - UserLike userLike = new UserLike(); - userLike.setCreateDate(DateUtil.getByTimeZone(timeZone)); - userLike.setDesignId(designId); - userLike.setUserLikeGroupId(userGroupId); - userLike.setDesignItemId(designItemId); - userLike.setDesignOutfitId(designPythonOutfitId); - userLike.setUrl(designUrl); - return userLike; - } - - @Override - public Boolean dislike(DisDesignLikeDTO disDesignLikeDTO) { - AuthPrincipalVo userInfo = UserContext.getUserHolder(); - UserLike userLike = userLikeService.getById(disDesignLikeDTO.getGroupDetailId()); - if (Objects.isNull(userLike)) { - throw new BusinessException("history.detail.not.found"); - } - Design design = getById(disDesignLikeDTO.getDesignId()); - if (Objects.isNull(design)) { - throw new BusinessException("design.detail.not.found"); - } - if (!userLike.getDesignId().equals(disDesignLikeDTO.getDesignId())) { - //不是相同的design不会合并 - return Boolean.TRUE; - } - //修改designItem为dislike状态 - designItemService.updateLikeStatus(userLike.getDesignItemId(), (byte) 0); - //删除关联的collection,先不做 - - //删除对应的history - userLikeService.removeById(disDesignLikeDTO.getGroupDetailId()); - List userLikeVOS = userLikeService.getGroupDetail(userLike.getUserLikeGroupId()); - if (CollectionUtils.isEmpty(userLikeVOS)) { - //group 下面没有元素时候 直接删除 - userLikeGroupService.removeById(userLike.getUserLikeGroupId()); - } - return Boolean.TRUE; - } - - @Override - public String generateHighDesign(GenerateHighDesignDTO generateHighDesignDTO) { - DesignItem designItem = designItemService.getById(generateHighDesignDTO.getDesignItemId()); - if (Objects.isNull(designItem)){ - throw new BusinessException("design.item.does.not.exist"); - } - String highUrl = pythonService.generateHighDesign(designItem.getDesignUrl()); - //存储 - designItemService.updateDesignHighUrl(designItem.getId(), highUrl, generateHighDesignDTO.getTimeZone()); - return highUrl; - } - - @Override - public Boolean deleteHighDesign(GenerateHighDesignDTO generateHighDesignDTO) { - DesignItem designItem = designItemService.getById(generateHighDesignDTO.getDesignItemId()); - if (Objects.isNull(designItem)){ - throw new BusinessException("design.item.does.not.exist"); - } - if (StringUtils.isEmpty(designItem.getHighDesignUrl())) { - //并发情况 ,不提示 直接返回 - return Boolean.TRUE; - } - //存储 - designItemService.updateDesignHighUrl(designItem.getId(), "", generateHighDesignDTO.getTimeZone()); - FileUtil.delete(designItem.getHighDesignUrl()); - return Boolean.TRUE; - } - - @Override - public DesignItemDetailVO detail(Long designPythonOutfitId, Long designItemId) { - // 1、校验 - DesignItem designItem = designItemService.getById(designItemId); - if (Objects.isNull(designItem)) { - throw new BusinessException("designItem.not.found"); - } - Design design = getById(designItem.getDesignId()); - if (Objects.isNull(design)) { - throw new BusinessException("design.not.found"); - } - List designItemDetails = designItemDetailService.selectByDesignItemId(designItemId); - if (CollectionUtil.isEmpty(designItemDetails)) { - throw new BusinessException("designItemDetails.not.found"); - } - // 添加判断designPythonOutfitId是否存在 - TDesignPythonOutfit designPythonOutfit = new TDesignPythonOutfit(); - Boolean flag = Boolean.FALSE; - if (Objects.nonNull(designPythonOutfitId)) { - designPythonOutfit = designPythonOutfitService.getById(designPythonOutfitId); - if (Objects.isNull(designPythonOutfit)) { - throw new BusinessException("designPythonOutfit.not.found"); - } - flag = Boolean.TRUE; - } - - // 为没有优先级的衣服添加优先级 - designItemDetailService.setDesignItemDetailPriority(designItemDetails); - - // 2、组装返回参数 - DesignItemDetailVO response = new DesignItemDetailVO(); - response.setSingleOverall(design.getSingleOverall()); - response.setSwitchCategory(design.getSwitchCategory()); - response.setDesignItemId(designItemId); -// response.setDesignItemUrl(designItem.getDesignUrl()); - response.setHighDesignUrl(designItem.getHighDesignUrl()); - List filterDetail = designItemDetails.stream() - .filter(f -> OUTWEAR_DRESS_BLOUSE.contains(f.getType()) || SKIRT_TROUSERS.contains(f.getType()) - || TOPS.contains(f.getType()) || BOTTOMS.contains(f.getType())) - .collect(Collectors.toList()); - response.setClothes(CopyUtil.copyList(filterDetail, DesignItemClothesDetailVO.class, (o, d) -> { - d.setId(o.getId()); - d.setPath(minioUtil.getPreSignedUrl(o.getPath(), 24 * 60, true)); - d.setMinIOPath(o.getPath()); - d.setLevel1Type(converTypeToLevel1(o.getType())); - d.setGradient(JSONObject.parseObject(o.getGradientString(), Gradient.class)); - if (!StringUtil.isNullOrEmpty(o.getUndividedLayer())) d.setUndividedLayer(minioUtil.getPreSignedUrl(o.getUndividedLayer(), CommonConstant.MINIO_IMAGE_EXPIRE_TIME)); - // 根据designItemDetailId获取印花 - List prints = designItemDetailPrintService.getByDesignItemDetailId(o.getId(), "print"); - // 判断有无印花 - if (CollectionUtil.isNotEmpty(prints)) { - // 有印花 - d.setPrintObject(convertToDesignSinglePrintDTO(prints)); - } - // 根据designItemDetailId获取design elements - List trims = designItemDetailPrintService.getByDesignItemDetailId(o.getId(), "trims"); - // 判断有无装饰 trims - if (CollectionUtil.isNotEmpty(trims)) { - // 有印花 - d.setTrims(convertToDesignSinglePrintDTO(trims)); - } - })); - //single 和 Models(模特)时候 系统元素为空 - List filterDetail2 = designItemDetails.stream() -// .filter(f -> SYS_HAIRSTYLE_SHOES.contains(f.getType()) ) - .filter(f -> SYS_HAIRSTYLE_SHOES_BODY.contains(f.getType())) - .collect(Collectors.toList()); - response.setOthers(CopyUtil.copyList(filterDetail2, DesignItemOthersDetailVO.class, (o, d) -> { - // todo 不确定businessId的作用,暂时取消传递,查看影响 -// d.setId(o.getBusinessId()); - d.setId(0L); - d.setPath(minioUtil.getPreSignedUrl(o.getPath(), 24 * 60)); - d.setMinIOPath(o.getPath()); - d.setPrintObject(new DesignPythonItemPrint()); - })); - return editDesignItemLayer(flag, designPythonOutfit, - minioUtil.getPreSignedUrl(designPythonOutfit.getDesignUrl(), 24 * 60), - editResponseColor(designItemDetails, response)); - } - - @Override - public Integer designProcess(String processId) { - ProcessIdObject object = new ProcessIdObject(); - object.setProcess_id(processId); - - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS) - .readTimeout(60, TimeUnit.SECONDS) - .writeTimeout(60, TimeUnit.SECONDS) - .build(); - - MediaType mediaType = MediaType.parse("application/json"); - String param = JSON.toJSONString(object, SerializerFeature.DisableCircularReferenceDetect); - log.info("designProcess请求python 参数:####{}", param); - RequestBody body = RequestBody.create(mediaType, param); - - Request request = new Request.Builder() - .url(accessPythonIp + ":" + accessPythonPort + "/api/get_progress") - .method("POST", body) - .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") - .addHeader("Content-Type", "application/json") - .build(); - - try (Response response = client.newCall(request).execute()) { - if (response.isSuccessful()) { - String responseBody = Objects.requireNonNull(response.body()).string(); - JSONObject responseObject = JSON.parseObject(responseBody); - String num = responseObject.getString("data"); - return Integer.valueOf(num); - } - } catch (IOException | JSONException e) { - log.error("PythonService##design进度条异常###{}", ExceptionUtil.getThrowableList(e)); - } - - return 0; - } - - - private String converTypeToLevel1(String type) { - if (StringUtils.isEmpty(type)) { - return null; - } - SysFileLevel2TypeEnum sysFileLevel2TypeEnum = SysFileLevel2TypeEnum.realNameOf(type); - if (Objects.isNull(sysFileLevel2TypeEnum)) { - return null; - } - if (OUTWEAR_DRESS_BLOUSE.contains(type) || SKIRT_TROUSERS.contains(type)) { - return CollectionLevel1TypeEnum.SKETCH_BOARD.getRealName(); - } - return null; - } - - private Design selectByCollectionId(Long collectionId) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("collection_id", collectionId); - return designMapper.selectOne(queryWrapper); - } - - private int deleteByCollectionId(Long collectionId) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("collection_id", collectionId); - Design design = new Design(); - design.setCollectionId(0L); - return designMapper.update(design, queryWrapper); - } - - private Long saveOne(DesignCollectionDTO designDTO, Long collectionId, Long accountId) { - Design design = CopyUtil.copyObject(designDTO, Design.class); - design.setCreateDate(DateUtil.getByTimeZone(designDTO.getTimeZone())); - design.setCollectionId(collectionId); - design.setAccountId(accountId); - if (designMapper.insert(design) <= 0) { - throw new BusinessException("save.design.failed"); - } - return design.getId(); - } - - /** - * 避免多次连接数据,所这里一次查多条颜色并利用designItemDetailId保持颜色与vo的对应关系 - * - * @param designItemDetails - * @param designItemDetailVO - * @return - */ - private DesignItemDetailVO editResponseColor(List designItemDetails, DesignItemDetailVO designItemDetailVO) { - // 使用designItemDetailId rgb(String)做映射 - HashMap designItemDetailIdColor = new HashMap<>(); - designItemDetails.forEach(designItemDetail -> { - if (!StringUtil.isNullOrEmpty(designItemDetail.getColor())) { - designItemDetailIdColor.put(designItemDetail.getId(), designItemDetail.getColor()); - } - }); - - if (!CollectionUtil.isEmpty(designItemDetailIdColor)){ - Map pantoneByRgbBatch = panToneService.getPantoneByRgbBatch(new ArrayList<>(designItemDetailIdColor.values())); - designItemDetailVO.getClothes().forEach(c -> { - PantoneVO pantoneVO = pantoneByRgbBatch.get(designItemDetailIdColor.get(c.getId())); - c.setColor(pantoneVO); - }); - - designItemDetailVO.getOthers().forEach(o -> { - PantoneVO pantoneVO = pantoneByRgbBatch.get(designItemDetailIdColor.get(o.getId())); - o.setColor(pantoneVO); - }); - } - - return designItemDetailVO; - } - - private DesignItemDetailVO editDesignItemLayer(Boolean flag, TDesignPythonOutfit designPythonOutfit, String designItemUrl, DesignItemDetailVO designItemDetailVO) { - ArrayList detailsVO = new ArrayList<>(); - - if (flag) { - // 1、判断designPythonOutfitId查出的图层信息是否为空(不允许为空,系统内部错误) - List details = designPythonOutfitDetailService.getDetailByDesignPythonOutfitId(designPythonOutfit.getId()); - if (Objects.isNull(details)){ - log.error("Layer information is empty! DesignPythonOutfitId is " + designPythonOutfit.getId()); - throw new BusinessException("layer.information.not.found"); - } - - // 为没有优先级的图层添加优先级 - designPythonOutfitDetailService.setDesignPythonOutfitDetailPriority(details); - - details.forEach(detail -> { -// List offset = new ArrayList<>(); -// if (StringUtil.isNullOrEmpty(detail.getOffset()) || detail.getOffset().equals("null")) { -// offset = Arrays.asList(0L, 0L); -// } else { -// offset = Arrays.stream(detail.getOffset().replaceAll("\\[|\\]", "").split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()); -// } - detailsVO.add(designPythonOutfitDetailService.convertToDesignPythonOutfitVO(detail, null)); - }); - - // 2、将查询出的图层信息填充到designItemDetailVO中 - designItemDetailVO.setDesignItemUrl(minioUtil.getPreSignedUrl(designPythonOutfit.getDesignUrl(), 24 * 60)); - // 2.1 填充clothes - designItemDetailVO.getClothes().forEach(c -> { -// String type = c.getType().toLowerCase(); -// List outfitVOS = detailsVO.stream().filter((detail -> detail.getImageCategory().equals(type + "_back") || -// detail.getImageCategory().equals(type + "_front"))).collect(Collectors.toList()); - List outfitVOS = detailsVO.stream().filter(detail -> detail.getPriority().equals(c.getPriority())).collect(Collectors.toList()); - - c.setLayersObject(outfitVOS); - }); - // 2.2 填充others - designItemDetailVO.getOthers().forEach(o -> { - String type = o.getType().toLowerCase(); - List outfitVOS = detailsVO.stream().filter(detail -> detail.getImageCategory().equals(type + "_back") || - detail.getImageCategory().equals(type + "_front") || - detail.getImageCategory().equals(type + "_left") || - detail.getImageCategory().equals(type + "_right") || - detail.getImageCategory().equals(type)).collect(Collectors.toList()); - o.setLayersObject(outfitVOS); - }); - } else { - designItemDetailVO.setDesignItemUrl(designItemUrl); - } - - return designItemDetailVO; - } - - private DesignSinglePrintDTO convertToDesignSinglePrintDTO(List designItemDetailPrints) { - DesignSinglePrintDTO designSinglePrintDTO = new DesignSinglePrintDTO(); - List prints = new ArrayList<>(); - - // 只有一个印花 - if (designItemDetailPrints.size() == 1) { - DesignItemDetailPrint detailPrint = designItemDetailPrints.get(0); - DesignSinglePrint designSinglePrint = new DesignSinglePrint(); -// designSinglePrintDTO.setIfSingle(detailPrint.getSingleOrOverall().equals("single") ? Boolean.TRUE : Boolean.FALSE); - designSinglePrint.setLevel2Type(detailPrint.getLevel2Type()); - designSinglePrint.setLocation(JSONArray.parseArray(detailPrint.getPosition(), Double.class)); - designSinglePrint.setAngle(detailPrint.getAngle()); - designSinglePrint.setPriority(detailPrint.getPriority()); - designSinglePrint.setPath(minioUtil.getPreSignedUrl(detailPrint.getPath(), 24 * 60)); - designSinglePrint.setMinIOPath(detailPrint.getPath()); - designSinglePrint.setScale(detailPrint.getScale()); - designSinglePrint.setIfSingle(detailPrint.getSingleOrOverall().equals("single") ? Boolean.TRUE : Boolean.FALSE); - prints.add(designSinglePrint); - } else { - // single模式下多个印花 -// designSinglePrintDTO.setIfSingle(Boolean.TRUE); - designItemDetailPrints.forEach(print -> { -// if (print.getSingleOrOverall().equals("single")) { - prints.add(new DesignSinglePrint( - print.getLevel2Type(), - minioUtil.getPreSignedUrl(print.getPath(), 24 * 60), - print.getPath(), - JSONArray.parseArray(print.getPosition(), Double.class), - print.getScale(), - print.getAngle(), - print.getPriority(), - print.getSingleOrOverall().equals("single") ? Boolean.TRUE : Boolean.FALSE)); -// } - }); - } - designSinglePrintDTO.setPrints(prints); - return designSinglePrintDTO; - } - - @Override - public List getModel(List designItemIdList){ - ArrayList models = new ArrayList<>(); - List designIdById = designItemService.selectDesignIdById(designItemIdList); - if (CollectionUtil.isEmpty(designIdById)){ - log.info("according to the designItemIdList cannot find the designIdList"); - throw new BusinessException("design.not.found"); - } - List designIdList = designIdById.stream().map(DesignItem::getDesignId).collect(Collectors.toList()); - List designs = selectList(designIdList); - if (CollectionUtil.isEmpty(designIdList)){ - log.info("according to the designIdList cannot find the design"); - throw new BusinessException("design.not.found"); - } - List modelFromLibIds = designs.stream().filter(design -> design.getModelType().equals("Library")).map(Design::getTemplateId).collect(Collectors.toList()); - if (!CollectionUtil.isEmpty(modelFromLibIds)){ - models.addAll(libraryService.getByIds(modelFromLibIds).stream() - .map(d -> minioUtil.getPreSignedUrl(d.getUrl(), 24 * 60)) - .collect(Collectors.toList())); - } - List modelFromSysIds = designs.stream().filter(design -> design.getModelType().equals("System")).map(Design::getTemplateId).collect(Collectors.toList()); - if (!CollectionUtil.isEmpty(modelFromSysIds)){ - models.addAll(sysFileService.getByIds(modelFromSysIds).stream() - .map(d -> minioUtil.getPreSignedUrl(d.getUrl(), 24 * 60)) - .collect(Collectors.toList())); - } - - return models; - } - - private List selectList(List designIdList){ - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.in("id",designIdList); - - return designMapper.selectList(queryWrapper); - } -} +package com.ai.da.service.impl; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.exceptions.ExceptionUtil; +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.utils.*; +import com.ai.da.mapper.primary.DesignMapper; +import com.ai.da.mapper.primary.GenerateDetailMapper; +import com.ai.da.mapper.primary.TDesignPythonOutfitMapper; +import com.ai.da.mapper.primary.entity.*; +import com.ai.da.mapper.primary.entity.Collection; +import com.ai.da.model.dto.*; +import com.ai.da.model.vo.*; +import com.ai.da.python.PythonService; +import com.ai.da.python.vo.*; +import com.ai.da.service.*; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +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 okhttp3.*; +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.io.IOException; +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.*; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import static com.ai.da.python.vo.DesignPythonItem.*; + +/** + * 服务实现类 + * + * @author yanglei + * @since 2022-09-30 + */ +@Slf4j +@Service +public class DesignServiceImpl extends ServiceImpl implements DesignService { + @Resource + private DesignMapper designMapper; + @Resource + private CollectionElementService collectionElementService; + @Resource + private CollectionService collectionService; + @Resource + private PythonService pythonService; + @Resource + private LibraryService libraryService; + @Resource + private GenerateDetailMapper generateDetailMapper; + @Resource + private DesignItemService designItemService; + @Resource + private DesignItemDetailService designItemDetailService; + @Resource + private FileProperties fileProperties; + @Resource + private UserLikeGroupService userLikeGroupService; + @Resource + private UserLikeService userLikeService; + @Resource + private SysFileService sysFileService; + @Resource + private TCollectionElementRelationService tCollectionElementRelationService; + @Resource + private ITDesignPythonOutfitService designPythonOutfitService; + @Resource + private ITDesignPythonOutfitDetailService designPythonOutfitDetailService; + @Resource + private PanToneService panToneService; + @Resource + private PythonTAllInfoService pythonTAllInfoService; + @Resource + private DesignItemDetailPrintService designItemDetailPrintService; + + @Resource + private TDesignPythonOutfitMapper designPythonOutfitMapper; + + @Value("${minio.endpoint}") + private String endpoint; + @Value("${minio.bucketName.results}") + private String bucketName; + + @Value("${access.python.ip:''}") + private String accessPythonIp; + + @Value("${access.python.port:''}") + private String accessPythonPort; + + @Override + public DesignCollectionVO designCollection(DesignCollectionDTO designDTO) { + AuthPrincipalVo userInfo = UserContext.getUserHolder(); + //校验collection element + ValidateElementVO elementVO = collectionElementService.validateElement(designDTO); + //design + return designOrRedesignOperateNew(designDTO, userInfo, null, elementVO); + } + + private void calculateLibraryAndSysFile(DesignCollectionDTO designDTO, ValidateElementVO elementVO, AuthPrincipalVo userInfo) { + //查询用户 sketch library + List libraryVos; + if (CollectionUtil.isNotEmpty(designDTO.getSketchBoards())) { + List sketchUrlList = elementVO.getSketchBoardElements() + .stream() + .map(CollectionElement::getUrl) + .collect(Collectors.toList()); + DesignAttributeRetrievalDTO designAttributeRetrievalDTO = + pythonService.generateAttributeRetrieval(sketchUrlList, userInfo.getId(), elementVO.getModelSex()); + if (CollectionUtils.isEmpty(designAttributeRetrievalDTO.getLibraryUrls())) { + libraryVos = null; + } else { + libraryVos = libraryService.getByUrlList(designAttributeRetrievalDTO.getLibraryUrls(), userInfo.getId()); + } + List sysFileVOS = sysFileService.getByUrlList(designAttributeRetrievalDTO.getSysFileUrlS()); + elementVO.setSysFileVo(sysFileVOS); + } else { + libraryVos = libraryService.selectByAccountIdAnd1TypeList(userInfo.getId(), + Collections.singletonList(CollectionLevel1TypeEnum.SKETCH_BOARD.getRealName())); + } + elementVO.setLibraryVos(libraryVos); + //校验比列 + validateRatio(designDTO, libraryVos); + } + + private void validateRatio(DesignCollectionDTO designDTO, List libraryVos) { + //校验系统比列,先去掉 考虑到程序已经进入比较后面了,该校验不重要,且会产生脏数据 +// BigDecimal bigDecimal = designDTO.getSystemScale(); +// //池子是包括三部分 = 本次用户上传的sketch + library的sketch +系统的sketch,systemScale计算的是 library和sysFile的比列 +// if (/*CollectionUtil.isEmpty(designDTO.getSketchBoards()) +// && */CollectionUtils.isEmpty(libraryVos) +// && bigDecimal.compareTo(BigDecimal.ZERO) <= 0) { +// throw new BusinessException("No sketch, please increase the system rate"); +// } + } + + private void saveCollectionElemntsByLibrarys(ValidateElementVO elementVO, Long collectionId) { + if (CollectionUtils.isEmpty(elementVO.getLibraryCollectionElements())) { + return; + } + elementVO.getLibraryCollectionElements() + .forEach(element -> { + element.setCollectionId(collectionId); + Byte hasPin = element.getHasPin(); + if (Objects.isNull(hasPin)) { + element.setHasPin((byte) 0); + } + element.setId(null); + }); + List saveElements = elementVO.getLibraryCollectionElements(); + collectionElementService.saveBatch(saveElements); + elementVO.getUsedElementIds().addAll(saveElements.stream().map(CollectionElement::getId).collect(Collectors.toList())); + //sketch + List newSketchAboard = saveElements.stream() + .filter(f -> f.getLevel1Type().equals(CollectionLevel1TypeEnum.SKETCH_BOARD.getRealName())) + .collect(Collectors.toList()); + if (!CollectionUtils.isEmpty(newSketchAboard)) { + elementVO.getSketchBoardElements().addAll(newSketchAboard); + } + //print + List newPrintboard = saveElements.stream() + .filter(f -> f.getLevel1Type().equals(CollectionLevel1TypeEnum.PRINT_BOARD.getRealName())) + .collect(Collectors.toList()); + if (!CollectionUtils.isEmpty(newPrintboard)) { + elementVO.getPrintBoardElements().addAll(newPrintboard); + } + //mood + List newMoodboard = saveElements.stream() + .filter(f -> f.getLevel1Type().equals(CollectionLevel1TypeEnum.MOOD_BOARD.getRealName())) + .collect(Collectors.toList()); + if (!CollectionUtils.isEmpty(newMoodboard)) { + if (CollectionUtils.isEmpty(elementVO.getMoodBoardElements())) { + elementVO.setMoodBoardElements(new ArrayList<>()); + } + elementVO.getMoodBoardElements().addAll(newMoodboard); + } + } + + private void saveCollectionElemntsByGenerates(ValidateElementVO elementVO, Long collectionId) { + if (CollectionUtils.isEmpty(elementVO.getGenerateCollectionElements())) { + return; + } + elementVO.getGenerateCollectionElements() + .forEach(element -> { + element.setCollectionId(collectionId); + Byte hasPin = element.getHasPin(); + if (Objects.isNull(hasPin)) { + element.setHasPin((byte) 0); + } + element.setId(null); +// element.setType(DesignTypeEnum.GENERATE.getRealName()); + }); + List saveElements = elementVO.getGenerateCollectionElements(); + collectionElementService.saveBatch(saveElements); + elementVO.getUsedElementIds().addAll(saveElements.stream().map(CollectionElement::getId).collect(Collectors.toList())); + //sketch + List newSketchAboard = saveElements.stream() + .filter(f -> f.getLevel1Type().equals(CollectionLevel1TypeEnum.SKETCH_BOARD.getRealName())) + .collect(Collectors.toList()); + if (!CollectionUtils.isEmpty(newSketchAboard)) { + elementVO.getSketchBoardElements().addAll(newSketchAboard); + } + //print + List newPrintboard = saveElements.stream() + .filter(f -> f.getLevel1Type().equals(CollectionLevel1TypeEnum.PRINT_BOARD.getRealName())) + .collect(Collectors.toList()); + if (!CollectionUtils.isEmpty(newPrintboard)) { + elementVO.getPrintBoardElements().addAll(newPrintboard); + } + //mood + List newMoodboard = saveElements.stream() + .filter(f -> f.getLevel1Type().equals(CollectionLevel1TypeEnum.MOOD_BOARD.getRealName())) + .collect(Collectors.toList()); + if (!CollectionUtils.isEmpty(newMoodboard)) { + if (CollectionUtils.isEmpty(elementVO.getMoodBoardElements())) { + elementVO.setMoodBoardElements(new ArrayList<>()); + } + elementVO.getMoodBoardElements().addAll(newMoodboard); + } + } + +// private DesignCollectionVO designOrRedesignOperate(DesignCollectionDTO designDTO, AuthPrincipalVo userInfo, +// Long collectionIdParam, ValidateElementVO elementVO) { +// if (CollectionUtil.isNotEmpty(designDTO.getSketchBoards())) { +// //编辑sketchBoard +// collectionElementService.editSketchBoardsElement(elementVO, designDTO.getSketchBoards()); +// } +// if (CollectionUtil.isNotEmpty(designDTO.getPrintBoards())) { +// //编辑printBoard +// collectionElementService.editPrintBoardsElement(elementVO, designDTO.getPrintBoards()); +// } +// //保存collection +// Long collectionId = (null == collectionIdParam) ? +// collectionService.saveCollection(userInfo.getId(), designDTO.getTimeZone(), designDTO.getMoodTemplateId()) : collectionIdParam; +// List elementIds = getElementId(elementVO); +// //批量关联element 到 collection +// collectionElementService.relationCollection(elementIds, collectionId); +// //library转化为collection(生成) +// saveCollectionElemntsByLibrarys(elementVO, collectionId); +// //保存颜色版 +// List colorElementList = collectionElementService.saveColorBoard(designDTO.getColorBoards(), collectionId, designDTO.getTimeZone()); +// //保存design +// Long designId = saveOne(designDTO, collectionId, userInfo.getId()); +// //计算library +// calculateLibraryAndSysFile(designDTO, elementVO, userInfo); +// //组装design入参 +// DesignPythonObjects pythonObjects = pythonService.covertDesignParam(designDTO.getSystemScale(), +// designDTO.getSingleOverall(), designDTO.getSwitchCategory(), elementVO, designDTO.getProcessId()); +// //缓存保存的文件 方便后面处理进度问题 采用新的进度条获取方式 根据processId获取 +//// setDesignProcess(userInfo.getId(), pythonObjects); +// //design +// pythonService.design(pythonObjects); +// //生成library +// generateLibrary(elementVO, designDTO.getTimeZone()); +// //处理关联关系,修复element覆盖得情况 +// List reLationelements = collectionElementService.getByOnlyCollectionId(collectionId); +// List reLationelementIds = reLationelements.stream().map(CollectionElement::getId).collect(Collectors.toList()); +// handleCollectionElementRelation(collectionId, (null == collectionIdParam) ? false : true, reLationelementIds); +// //保存python返回信息 +//// return savePythonDesignItemAndDetail(pythonObjects,designId,collectionId,userInfo,designDTO.getTimeZone(),responseJSONObject); +// //保存designItem 和detail +// return saveDesignItemAndDetail(pythonObjects, designId, collectionId, userInfo, designDTO.getTimeZone()); +// } + + private DesignCollectionVO designOrRedesignOperateNew(DesignCollectionDTO designDTO, AuthPrincipalVo userInfo, + Long collectionIdParam, ValidateElementVO elementVO) { + if (CollectionUtil.isNotEmpty(designDTO.getSketchBoards())) { + //编辑sketchBoard + collectionElementService.editSketchBoardsElement(elementVO, designDTO.getSketchBoards()); + } + if (CollectionUtil.isNotEmpty(designDTO.getPrintBoards())) { + //编辑printBoard + collectionElementService.editPrintBoardsElement(elementVO, designDTO.getPrintBoards()); + } + //保存collection + Long collectionId = (null == collectionIdParam) ? + collectionService.saveCollection(userInfo.getId(), designDTO.getTimeZone(), designDTO.getMoodTemplateId()) : collectionIdParam; + List elementIds = getElementId(elementVO); + //批量关联element 到 collection + collectionElementService.relationCollection(elementIds, collectionId); + //library转化为collection(生成) + saveCollectionElemntsByLibrarys(elementVO, collectionId); + //generate转化为collection(生成) + saveCollectionElemntsByGenerates(elementVO, collectionId); + //保存颜色版 + collectionElementService.saveColorBoard(designDTO.getColorBoards(), collectionId, designDTO.getTimeZone()); + //保存design + Long designId = saveOne(designDTO, collectionId, userInfo.getId()); + //计算library +// calculateLibraryAndSysFile(designDTO, elementVO, userInfo); + //组装design入参 + long startTime = System.currentTimeMillis(); + DesignPythonObjects pythonObjects = pythonService.covertDesignParam(designDTO.getSystemScale(), + designDTO.getSingleOverall(), designDTO.getSwitchCategory(), elementVO, designDTO.getProcessId()); + long endTime = System.currentTimeMillis(); + long totalTimeInSeconds = (endTime - startTime) / 1000; + log.info("组装入参运行时间:" + totalTimeInSeconds + " 秒"); + // pythonObjects增加image_id关联 + startTime = System.currentTimeMillis(); + List imageIds = relationImageIds(pythonObjects); + endTime = System.currentTimeMillis(); + totalTimeInSeconds = (endTime - startTime) / 1000; + log.info("增加image_id关联运行时间:" + totalTimeInSeconds + " 秒"); + //design + startTime = System.currentTimeMillis(); + JSONObject responseJSONObject = pythonService.designNew(pythonObjects); + endTime = System.currentTimeMillis(); + totalTimeInSeconds = (endTime - startTime) / 1000; + log.info("design python端运行时间:" + totalTimeInSeconds + " 秒"); + //生成library + startTime = System.currentTimeMillis(); + generateLibrary(elementVO, designDTO.getTimeZone()); + //处理关联关系,修复element覆盖得情况 + List relationElements = collectionElementService.getByOnlyCollectionId(collectionId); + List relationElementIds = relationElements.stream().map(CollectionElement::getId).collect(Collectors.toList()); + handleCollectionElementRelation(collectionId, null != collectionIdParam, relationElementIds); + endTime = System.currentTimeMillis(); + totalTimeInSeconds = (endTime - startTime) / 1000; + log.info("处理关联关系运行时间:" + totalTimeInSeconds + " 秒"); + //保存python返回信息;保存designItem和detail + return savePythonDesignItemAndDetail(pythonObjects, designId, collectionId, userInfo, designDTO.getTimeZone(), responseJSONObject, designDTO.getSingleOverall()); + } + + @Override + public void relationImageId(DesignPythonObjects pythonObjects) { + if (Objects.isNull(pythonObjects)) { + return; + } + pythonObjects.getObjects().forEach( + o -> { + for (DesignPythonItem item : o.getItems()) { + List list = new ArrayList<>(); + list.add(1L); + list.add(1L); + item.setOffset(list); + item.setResize_scale(new Float[]{1.0f,1.0f}); + String path = item.getPath(); + if (StringUtils.isEmpty(path)) { + String bodyPath = item.getBody_path(); + Long imageId = pythonTAllInfoService.getImageIdByPath(bodyPath); + item.setImage_id(imageId); + } else { + Long imageId = pythonTAllInfoService.getImageIdByPath(path); + item.setImage_id(imageId); + } + } + } + ); + } + + @Override + public List sketchesBoundingBox(SketchesBoundingBoxDTO sketchesBoundingBoxDTO) { + List sketchBoards = sketchesBoundingBoxDTO.getSketchBoards(); + if (CollectionUtil.isNotEmpty(sketchBoards)) { + List result = new ArrayList<>(); + List collect = sketchBoards.stream() + .filter(o -> !o.getDesignType().equals(DesignTypeEnum.LIBRARY.getRealName())) + .collect(Collectors.toList()); + if (CollectionUtil.isNotEmpty(collect)) { + for (CollectionSketchDTO collectionSketchDTO : collect) { + CollectionSketchVO vo = CopyUtil.copyObject(collectionSketchDTO, CollectionSketchVO.class); + if (collectionSketchDTO.getDesignType().equals(DesignTypeEnum.COLLECTION.getRealName())) { + CollectionElement byId = collectionElementService.getById(collectionSketchDTO.getSketchBoardId()); + libraryService.processSketchBoards(byId.getUrl(), collectionSketchDTO.getLevel2Type()); + String url = byId.getUrl(); + if (url.contains(".")) { + String[] split = url.split("\\."); + vo.setUrlWithWhiteSide(minioUtil.getPreSignedUrl(split[0] + "-show." + split[1], 24 * 60)); + }else { + vo.setUrlWithWhiteSide(minioUtil.getPreSignedUrl(url + "-show", 24 * 60)); + } + result.add(vo); + }else if (collectionSketchDTO.getDesignType().equals(DesignTypeEnum.GENERATE.getRealName())) { + GenerateDetail generateDetail = generateDetailMapper.selectById(collectionSketchDTO.getSketchBoardId()); + libraryService.processSketchBoards(generateDetail.getUrl(), collectionSketchDTO.getLevel2Type()); + String url = generateDetail.getUrl(); + if (url.contains(".")) { + String[] split = url.split("\\."); + vo.setUrlWithWhiteSide(minioUtil.getPreSignedUrl(split[0] + "-show." + split[1], 24 * 60)); + }else { + vo.setUrlWithWhiteSide(minioUtil.getPreSignedUrl(url + "-show", 24 * 60)); + } + result.add(vo); + } + } + } + List libraryList = sketchBoards.stream() + .filter(o -> o.getDesignType().equals(DesignTypeEnum.LIBRARY.getRealName())) + .collect(Collectors.toList()); + for (CollectionSketchDTO collectionSketchDTO : libraryList) { + Library byId = libraryService.getById(collectionSketchDTO.getSketchBoardId()); + libraryService.processSketchBoards(byId.getUrl(), collectionSketchDTO.getLevel2Type()); + CollectionSketchVO vo = CopyUtil.copyObject(collectionSketchDTO, CollectionSketchVO.class); + String url = byId.getUrl(); + if (url.contains(".")) { + String[] split = url.split("\\."); + vo.setUrlWithWhiteSide(minioUtil.getPreSignedUrl(split[0] + "-show." + split[1], 24 * 60)); + }else { + vo.setUrlWithWhiteSide(minioUtil.getPreSignedUrl(url + "-show", 24 * 60)); + } + result.add(vo); + } + return result; + } + return new ArrayList<>(); + } + + public List relationImageIds(DesignPythonObjects pythonObjects) { + List imageIds = new ArrayList<>(); + if (Objects.isNull(pythonObjects)) { + return imageIds; + } + pythonObjects.getObjects().forEach( + o -> { + for (DesignPythonItem item : o.getItems()) { + List list = new ArrayList<>(); + list.add(1L); + list.add(1L); + item.setOffset(list); + item.setResize_scale(new Float[]{1.0f,1.0f}); + String path = item.getPath(); + if (StringUtils.isEmpty(path)) { + String bodyPath = item.getBody_path(); + Long imageId = pythonTAllInfoService.getImageIdByPath(bodyPath); + imageIds.add(imageId); + item.setImage_id(imageId); + } else { + Long imageId = pythonTAllInfoService.getImageIdByPath(path); + imageIds.add(imageId); + item.setImage_id(imageId); + } + } + } + ); + return imageIds; + } + + private void handleCollectionElementRelation(Long collectionId, Boolean isEdit, List elementIds) { + if (CollectionUtils.isEmpty(elementIds) || collectionId == null) { + return; + } + if (isEdit) { + //删除 + tCollectionElementRelationService.deleteByCollectionId(collectionId); + } + //新增 + tCollectionElementRelationService.saveBatch(elementIds.stream().map(elementId -> + TCollectionElementRelation.builder() + .collectionId(collectionId) + .elementId(elementId) + .createDate(new Date()) + .build() + ).collect(Collectors.toList())); + } + + private void generateLibrary(ValidateElementVO elementVO, String timeZone) { + List elements = Lists.newArrayList(); + if (!CollectionUtils.isEmpty(elementVO.getMoodBoardElements())) { + elements.addAll(elementVO.getMoodBoardElements()); + } + if (!CollectionUtils.isEmpty(elementVO.getPrintBoardElements())) { + elements.addAll(elementVO.getPrintBoardElements()); + } + if (!CollectionUtils.isEmpty(elementVO.getSketchBoardElements())) { + elements.addAll(elementVO.getSketchBoardElements()); + } + if (!CollectionUtils.isEmpty(elementVO.getMarketingSketchElements())) { + elements.addAll(elementVO.getMarketingSketchElements()); + } + collectionElementService.saveLibraryByCollectionElement(elements, timeZone, elementVO.getModelSex()); + } + + @Override + public BigDecimal countDesignProcess() { + AuthPrincipalVo userInfo = UserContext.getUserHolder(); + List saveNames = LocalCacheUtils.getDesignProcessCache(userInfo.getId()); + if (CollectionUtils.isEmpty(saveNames)) { + return BigDecimal.ZERO; + } + int totalProcess = 0; + log.info("design 统计进度###totalProcess1{}", totalProcess); + //转成本地文件先 + for (String saveName : saveNames) { + String localFileUrl = saveName; + String linuxDomain = fileProperties.getLinuxDomain(); + if (!StringUtils.isEmpty(linuxDomain)) { + //linux 系统 + String oldPath = fileProperties.getSys().getPath(); + localFileUrl = saveName.replace(linuxDomain, oldPath); + } + File file = new File(localFileUrl); + if (file.exists()) { + totalProcess++; + log.info("design 统计进度++###totalProcess+++{}", totalProcess); + } + } + log.info("design 统计进度###totalProcess2{}", totalProcess); + BigDecimal result = BigDecimal.valueOf(totalProcess).divide(BigDecimal.valueOf(8)).setScale(3, BigDecimal.ROUND_HALF_UP); + if (result.compareTo(BigDecimal.ONE) == 0) { + LocalCacheUtils.delDesignProcessCache(userInfo.getId()); + } + return result; + } + + private void setDesignProcess(Long userId, DesignPythonObjects pythonObjects) { + List saveNames = pythonObjects.getObjects().stream().map(object -> { + return object.getBasic().getSave_name(); + }).collect(Collectors.toList()); + LocalCacheUtils.setDesignProcessCache(userId, saveNames); + } + + @Resource + private MinioUtil minioUtil; + + private DesignCollectionVO savePythonDesignItemAndDetail(DesignPythonObjects pythonObjects + , Long designId, Long collectionId, AuthPrincipalVo userInfo, String timeZone, JSONObject responseJSONObject, String singleOverall) { + DesignCollectionVO response = new DesignCollectionVO(); + response.setDesignId(designId); + response.setCollectionId(collectionId); + List designCollectionItems = Lists.newArrayList(); + response.setDesignCollectionItems(designCollectionItems); + JSONObject data = responseJSONObject.getJSONObject("data"); + if (data == null) { + throw new BusinessException("design.interface.exception"); + } + for (int i = 0; i < pythonObjects.getObjects().size(); i++) { + DesignPythonObject item = pythonObjects.getObjects().get(i); + DesignItem designItem = new DesignItem(); + designItem.setAccountId(userInfo.getId()); + designItem.setCollectionId(collectionId); + designItem.setDesignId(designId); + designItem.setCreateDate(DateUtil.getByTimeZone(timeZone)); + //生成的八张图片 + designItem.setDesignUrl(item.getBasic().getSave_name()); + designItem.setHasLike((byte) 0); + //生成designItem + Long designItemId = designItemService.saveOne(designItem); + // python design返回入库及封装 + JSONObject outfit = data.getJSONObject(i + ""); + if (null == outfit) { + continue; + } + TDesignPythonOutfit designPythonOutfit = new TDesignPythonOutfit(); + designPythonOutfit.setDesignItemId(designItemId); + designPythonOutfit.setUserId(userInfo.getId()); + designPythonOutfit.setDesignId(designId); + designPythonOutfit.setCollectionId(collectionId); + String synthesisUrl = outfit.getString("synthesis_url"); + if (!StringUtils.isEmpty(synthesisUrl)) { + designPythonOutfit.setDesignUrl(synthesisUrl); + } else { + throw new BusinessException("design.interface.exception"); + } + designPythonOutfitService.save(designPythonOutfit); + JSONArray layers = outfit.getJSONArray("layers"); + List list = new ArrayList<>(); + DesignCollectionItemVO designCollectionItemVO = new DesignCollectionItemVO(); + for (int i1 = 0; i1 < layers.size(); i1++) { + JSONObject jsonObject = layers.getJSONObject(i1); + TDesignPythonOutfitDetail designPythonOutfitDetail = new TDesignPythonOutfitDetail(); + designPythonOutfitDetail.setDesignId(designId); + designPythonOutfitDetail.setDesignPythonOutfitId(designPythonOutfit.getId()); + designPythonOutfitDetail.setPosition(jsonObject.getString("position")); + designPythonOutfitDetail.setImageSize(jsonObject.getString("image_size")); + designPythonOutfitDetail.setImageUrl(jsonObject.getString("image_url")); + if (singleOverall.equals(SingleOverallEnum.SINGLE.getRealName())) { + designCollectionItemVO.setDesignItemUrl(designItem.getDesignUrl()); + } + designPythonOutfitDetail.setImageCategory(jsonObject.getString("image_category")); + designPythonOutfitDetail.setMaskUrl(jsonObject.getString("mask_url")); + designPythonOutfitDetail.setUserId(userInfo.getId()); + designPythonOutfitDetail.setPriority(Integer.parseInt(jsonObject.getString("priority"))); + designPythonOutfitDetail.setCreateDate(LocalDateTime.now()); + list.add(designPythonOutfitDetail); + } + designPythonOutfitDetailService.saveBatch(list); + designCollectionItemVO.setDesignItemId(designItemId); + designCollectionItemVO.setDesignItemUrl(designItem.getDesignUrl()); + designCollectionItemVO.setDesignOutfitId(designPythonOutfit.getId()); + String designUrl = designPythonOutfit.getDesignUrl(); + if (!StringUtils.isEmpty(designUrl) && designUrl.contains("/")) { + int firstIndex = designUrl.indexOf("/"); + designCollectionItemVO.setDesignOutfitUrl(minioUtil.getPreSignedUrl(designUrl.substring(0, firstIndex) + "/" + designUrl.substring(firstIndex + 1), 24 * 60)); + } + //response + designCollectionItems.add(designCollectionItemVO); + + List designItemDetails = Lists.newArrayList(); + Map typePriority = list.stream().collect(Collectors.toMap(d -> d.getImageCategory().split("_")[0], + d -> Math.abs(d.getPriority()), + (existing, replacement) -> replacement)); + Map typeAndUndividedLayer = designItemService.setTypeAndUndividedLayer(layers); + for (DesignPythonItem detail : item.getItems()) { + if (null == detail) { + continue; + } + DesignItemDetail designItemDetail = CopyUtil.copyObject(detail, DesignItemDetail.class); + designItemDetail.setAccountId(userInfo.getId()); + designItemDetail.setDesignId(designId); + designItemDetail.setDesignItemId(designItemId); + designItemDetail.setCollectionElementId(detail.getElementId()); + designItemDetail.setCreateDate(DateUtil.getByTimeZone(timeZone)); + designItemDetail.setUndividedLayer(typeAndUndividedLayer.get(designItemDetail.getType().toLowerCase())); + if (SysFileLevel2TypeEnum.BODY.getRealName().equals(detail.getType())) { + designItemDetail.setPath(detail.getBody_path()); + //BODY不关联businessId + designItemDetail.setBusinessId(0L); + } + designItemDetail.setIconPath(detail.getIcon()); + designItemDetail.setPriority(typePriority.get(detail.getType().toLowerCase())); + if (!detail.getType().equals("Body")){ + DesignPythonItemPrint printObject = detail.getPrint().getOverall(); +// designItemDetail.setPrintPath(Objects.isNull(printObject) ? "" : printObject.getPath()); + designItemDetail.setPrintPath(CollectionUtils.isEmpty(printObject.getPrint_path_list()) ? "" : printObject.getPrint_path_list().get(0)); + } + designItemDetailService.save(designItemDetail); + if (!SysFileLevel2TypeEnum.BODY.getRealName().equals(detail.getType()) && !StringUtil.isNullOrEmpty(designItemDetail.getPrintPath())) { + DesignItemDetailPrint print = new DesignItemDetailPrint(); + print.setDesignItemDetailId(designItemDetail.getId()); + print.setPrintType("print"); + print.setPath(designItemDetail.getPrintPath()); + print.setSingleOrOverall("overall"); + print.setPosition("[0.0,0.0]"); +// print.setScale(1d); + // todo mark 将print默认scale置为0.3 + print.setScale(0.3d); + print.setAngle(0.0); + print.setPriority(1); + QueryWrapper getPrintboardLevel2TypeQw = new QueryWrapper<>(); + getPrintboardLevel2TypeQw.lambda().eq(CollectionElement::getUrl, print.getPath()); + getPrintboardLevel2TypeQw.lambda().orderByDesc(CollectionElement::getCreateDate); + getPrintboardLevel2TypeQw.last("limit 1"); + CollectionElement one = collectionElementService.getOne(getPrintboardLevel2TypeQw); + print.setLevel2Type(one.getLevel2Type()); + print.setCreateDate(LocalDateTime.now()); + designItemDetailPrintService.save(print); + } + } + } + response.setProcessId(pythonObjects.getProcess_id()); + return response; + } + + private DesignCollectionVO saveDesignItemAndDetail(DesignPythonObjects pythonObjects + , Long designId, Long collectionId, AuthPrincipalVo userInfo, String timeZone) { + DesignCollectionVO response = new DesignCollectionVO(); + response.setDesignId(designId); + response.setCollectionId(collectionId); + List designCollectionItems = Lists.newArrayList(); + response.setDesignCollectionItems(designCollectionItems); + + pythonObjects.getObjects().forEach(item -> { + DesignItem designItem = new DesignItem(); + designItem.setAccountId(userInfo.getId()); + designItem.setCollectionId(collectionId); + designItem.setDesignId(designId); + designItem.setCreateDate(DateUtil.getByTimeZone(timeZone)); + //生成的八张图片 + designItem.setDesignUrl(item.getBasic().getSave_name()); + designItem.setHasLike((byte) 0); + //生成designItem + Long designItemId = designItemService.saveOne(designItem); + //response + designCollectionItems.add(new DesignCollectionItemVO(designItemId, designItem.getDesignUrl(), null, null)); + + List designItemDetails = Lists.newArrayList(); + item.getItems().forEach(detail -> { + if (null == detail) { + return; + } + DesignItemDetail designItemDetail = CopyUtil.copyObject(detail, DesignItemDetail.class); + designItemDetail.setAccountId(userInfo.getId()); + designItemDetail.setDesignId(designId); + designItemDetail.setDesignItemId(designItemId); + designItemDetail.setCollectionElementId(detail.getElementId()); + designItemDetail.setCreateDate(DateUtil.getByTimeZone(timeZone)); + if (SysFileLevel2TypeEnum.BODY.getRealName().equals(detail.getType())) { + designItemDetail.setPath(detail.getBody_path()); + //BODY不关联businessId + designItemDetail.setBusinessId(0L); + } + designItemDetail.setIconPath(detail.getIcon()); + DesignPythonItemPrint printObject = detail.getPrint().getOverall(); + designItemDetail.setPrintPath(Objects.isNull(printObject) ? "" : printObject.getPath()); + designItemDetails.add(designItemDetail); + }); + designItemDetailService.saveBatch(designItemDetails); + }); + return response; + } + + private List getElementId(ValidateElementVO elementVO) { + List elementIds = Lists.newArrayList(); + // collection type + if (CollectionUtil.isNotEmpty(elementVO.getSketchBoardElements())) { + elementIds.addAll(elementVO.getSketchBoardElements().stream().map(CollectionElement::getId).collect(Collectors.toList())); + } + if (CollectionUtil.isNotEmpty(elementVO.getMoodBoardElements())) { + elementIds.addAll(elementVO.getMoodBoardElements().stream().map(CollectionElement::getId).collect(Collectors.toList())); + } + if (CollectionUtil.isNotEmpty(elementVO.getPrintBoardElements())) { + elementIds.addAll(elementVO.getPrintBoardElements().stream().map(CollectionElement::getId).collect(Collectors.toList())); + } +// if(CollectionUtil.isNotEmpty(elementVO.getMarketingSketchElements())){ +// elementIds.addAll(elementVO.getMarketingSketchElements().stream().map(CollectionElement::getId).collect(Collectors.toList())); +// } + return elementIds; + } + + @Override + public DesignCollectionVO reDesignCollection(ReDesignCollectionDTO reDesignDTO) { + //校验collection + Collection collection = collectionService.getById(reDesignDTO.getCollectionId()); + if (Objects.isNull(collection)) { + throw new BusinessException("collection.not.found"); + } + AuthPrincipalVo userInfo = UserContext.getUserHolder(); +// //查询用户 sketch library +// List libraryVos = libraryService.selectByAccountIdAnd1TypeList(userInfo.getId(), +// Arrays.asList(CollectionLevel1TypeEnum.PRINT_BOARD.getRealName(), +// CollectionLevel1TypeEnum.SKETCH_BOARD.getRealName())); + //校验collection element + DesignCollectionDTO designCollectionDTO = CopyUtil.copyObject(reDesignDTO, DesignCollectionDTO.class); + ValidateElementVO elementVO = collectionElementService.validateElement(designCollectionDTO); + //计算并删除对应的未关联的element + List longs = calculateNoRelationElement(reDesignDTO.getCollectionId(), elementVO.getUsedElementIds()); + if (!CollectionUtils.isEmpty(longs)) { + collectionElementService.batchDelete(longs); + } + Design oldDesign = selectByCollectionId(reDesignDTO.getCollectionId()); + //删除老的关联的design + deleteByCollectionId(reDesignDTO.getCollectionId()); + designItemService.deleteByCollectionId(reDesignDTO.getCollectionId()); + designItemDetailService.deleteByDesignId(oldDesign.getId()); + //redesign + return designOrRedesignOperateNew(CopyUtil.copyObject( + reDesignDTO, DesignCollectionDTO.class), userInfo, reDesignDTO.getCollectionId(), elementVO); + } + + private List calculateNoRelationElement(Long collectionId, List usedElementIds) { + List collectionElements = collectionElementService.getByCollectionId(collectionId); + if (CollectionUtils.isEmpty(collectionElements)) { +// throw new BusinessException("get collection elements cannot be empty"); + return new ArrayList<>(); + } + if (CollectionUtils.isEmpty(usedElementIds)) { + return collectionElements.stream().map(CollectionElement::getId).collect(Collectors.toList()); + } + return collectionElements.stream() + .filter(filter -> !usedElementIds.contains(filter.getId())) + .map(CollectionElement::getId) + .collect(Collectors.toList()); + } + + @Override + public DesignCollectionVO designItemList(Long designId) { + Design design = baseMapper.selectById(designId); + if (Objects.isNull(design)) { + throw new BusinessException("design.not.found"); + } + List designItems = designItemService.getByDesignId(designId); + if (CollectionUtils.isEmpty(designItems)) { + return new DesignCollectionVO(designId, design.getCollectionId(), null, null); + } + return new DesignCollectionVO(designId, design.getCollectionId(), coverDesignItemToVO(designItems), null); + } + + private List coverDesignItemToVO(List designItems) { + List response = Lists.newArrayList(); + designItems.forEach(designItem -> { + response.add(new DesignCollectionItemVO(designItem.getId(), designItem.getDesignUrl(), null, null)); + }); + return response; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public DesignLikeVO like(DesignLikeDTO designLikeDTO) { + Long userGroupId = designLikeDTO.getUserGroupId();; + Long groupDetailId; + AuthPrincipalVo userInfo = UserContext.getUserHolder(); + DesignItem designItem = designItemService.getById(designLikeDTO.getDesignItemId()); + if (Objects.isNull(designItem)) { + throw new BusinessException("designItem.not.found"); + } + String pictureName = null; + UserLike userLike; + if (Objects.nonNull(userGroupId)) { + UserLikeGroup userLikeGroup = userLikeGroupService.getById(userGroupId); + if (Objects.isNull(userLikeGroup)) { + throw new BusinessException("userLikeGroup.not.found"); + } +// if(designItem.getCollectionId().equals(userLikeGroup.getCollectionId())){ +// //相同collection直接跳过 不需要往element加元素 +// return new DesignLikeVO(); +// } + List oldElements = collectionElementService.getByCollectionId(userLikeGroup.getCollectionId()); + if (CollectionUtil.isEmpty(oldElements)) { + throw new BusinessException("old.elements.not.found"); + } + List designItemDetails = designItemDetailService.selectByDesignItemId(designLikeDTO.getDesignItemId()); + if (CollectionUtil.isEmpty(designItemDetails)) { + throw new BusinessException("new.designItemDetails.not.found"); + } + //判断老的element合并到新的是否满足 数量不超过15 + List newElementIds = validateMergeElement(oldElements, designItemDetails); + //合并,关联新的element到collection + collectionElementService.relationCollection(newElementIds, userLikeGroup.getCollectionId()); + //处理关联关系,修复element覆盖得情况 + handleCollectionElementRelation(userLikeGroup.getCollectionId(), false, newElementIds); + + QueryWrapper qw = new QueryWrapper<>(); + qw.lambda().eq(TDesignPythonOutfit::getDesignItemId, designLikeDTO.getDesignItemId()); + List tDesignPythonOutfits = designPythonOutfitMapper.selectList(qw); + if (CollectionUtils.isEmpty(tDesignPythonOutfits)) { + throw new BusinessException("DesignItemId not found elements for ax elements to like! [" + designLikeDTO.getDesignItemId()); + } + userLike = resolveUserLike(userGroupId, designItem.getDesignId(), + designLikeDTO.getDesignItemId(), designLikeDTO.getDesignPythonOutfitId(), tDesignPythonOutfits.get(0).getDesignUrl(), designLikeDTO.getTimeZone()); + + } else { + //第一次like + userGroupId = userLikeGroupService.insertUserGroup(userInfo.getId(), designItem.getCollectionId(), designLikeDTO.getTimeZone()); + QueryWrapper qw = new QueryWrapper<>(); + qw.lambda().eq(TDesignPythonOutfit::getDesignItemId, designLikeDTO.getDesignItemId()); + List tDesignPythonOutfits = designPythonOutfitMapper.selectList(qw); + if (CollectionUtils.isEmpty(tDesignPythonOutfits)) { + throw new BusinessException("DesignItemId not found elements for ax elements to like! [" + designLikeDTO.getDesignItemId()); + } + userLike = resolveUserLike(userGroupId, + designItem.getDesignId(), designLikeDTO.getDesignItemId(), designLikeDTO.getDesignPythonOutfitId(), tDesignPythonOutfits.get(0).getDesignUrl(), designLikeDTO.getTimeZone()); + } + userLikeService.save(userLike); + groupDetailId = userLike.getId(); + String designUrl = designPythonOutfitMapper.selectById(userLike.getDesignOutfitId()).getDesignUrl(); + if (designUrl.contains("/")) { + int i = designUrl.lastIndexOf("/"); + pictureName = designUrl.substring(i + 1); + } + //修改designItem为like状态 + designItemService.updateLikeStatus(designLikeDTO.getDesignItemId(), (byte) 1); + return new DesignLikeVO(userGroupId, groupDetailId, pictureName); + } + + private List validateMergeElement(List oldElements, List designItemDetails) { + List hasCollections = designItemDetails.stream() + .filter(f -> Objects.nonNull(f.getCollectionElementId())) + .collect(Collectors.toList()); + if (CollectionUtils.isEmpty(hasCollections)) { + return null; + } + List oldIds = oldElements.stream().map(CollectionElement::getId).collect(Collectors.toList()); + List elementIds = hasCollections.stream().map(DesignItemDetail::getCollectionElementId).collect(Collectors.toList()); + //本次新增collection个数 + List adds = elementIds.stream().filter(id -> !oldIds.contains(id)).collect(Collectors.toList()); + if (CollectionUtils.isEmpty(adds)) { + return null; + } + //校验15次 + Map> group = oldElements.stream() + .collect(Collectors.groupingBy(CollectionElement::getLevel1Type)); + + group.forEach((k, v) -> { + List thisElement = group.get(k); + int groupNum = calculateGroupNum(thisElement, adds); + if (groupNum > 15) { + throw new BusinessException("The size of element type" + k + "exceeds 15"); + } + }); + return adds; + } + + private int calculateGroupNum(List thisElement, List adds) { + int num = 0; + List groupOldIds = thisElement.stream().map(CollectionElement::getId).collect(Collectors.toList()); + for (Long add : adds) { + if (groupOldIds.contains(add)) { + num++; + } + } + return num + thisElement.size(); + } + + private UserLike resolveUserLike(Long userGroupId, Long designId, Long designItemId, Long designPythonOutfitId, String designUrl, String timeZone) { + UserLike userLike = new UserLike(); + userLike.setCreateDate(DateUtil.getByTimeZone(timeZone)); + userLike.setDesignId(designId); + userLike.setUserLikeGroupId(userGroupId); + userLike.setDesignItemId(designItemId); + userLike.setDesignOutfitId(designPythonOutfitId); + userLike.setUrl(designUrl); + return userLike; + } + + @Override + public Boolean dislike(DisDesignLikeDTO disDesignLikeDTO) { + AuthPrincipalVo userInfo = UserContext.getUserHolder(); + UserLike userLike = userLikeService.getById(disDesignLikeDTO.getGroupDetailId()); + if (Objects.isNull(userLike)) { + throw new BusinessException("history.detail.not.found"); + } + Design design = getById(disDesignLikeDTO.getDesignId()); + if (Objects.isNull(design)) { + throw new BusinessException("design.detail.not.found"); + } + if (!userLike.getDesignId().equals(disDesignLikeDTO.getDesignId())) { + //不是相同的design不会合并 + return Boolean.TRUE; + } + //修改designItem为dislike状态 + designItemService.updateLikeStatus(userLike.getDesignItemId(), (byte) 0); + //删除关联的collection,先不做 + + //删除对应的history + userLikeService.removeById(disDesignLikeDTO.getGroupDetailId()); + List userLikeVOS = userLikeService.getGroupDetail(userLike.getUserLikeGroupId()); + if (CollectionUtils.isEmpty(userLikeVOS)) { + //group 下面没有元素时候 直接删除 + userLikeGroupService.removeById(userLike.getUserLikeGroupId()); + } + return Boolean.TRUE; + } + + @Override + public String generateHighDesign(GenerateHighDesignDTO generateHighDesignDTO) { + DesignItem designItem = designItemService.getById(generateHighDesignDTO.getDesignItemId()); + if (Objects.isNull(designItem)){ + throw new BusinessException("design.item.does.not.exist"); + } + String highUrl = pythonService.generateHighDesign(designItem.getDesignUrl()); + //存储 + designItemService.updateDesignHighUrl(designItem.getId(), highUrl, generateHighDesignDTO.getTimeZone()); + return highUrl; + } + + @Override + public Boolean deleteHighDesign(GenerateHighDesignDTO generateHighDesignDTO) { + DesignItem designItem = designItemService.getById(generateHighDesignDTO.getDesignItemId()); + if (Objects.isNull(designItem)){ + throw new BusinessException("design.item.does.not.exist"); + } + if (StringUtils.isEmpty(designItem.getHighDesignUrl())) { + //并发情况 ,不提示 直接返回 + return Boolean.TRUE; + } + //存储 + designItemService.updateDesignHighUrl(designItem.getId(), "", generateHighDesignDTO.getTimeZone()); + FileUtil.delete(designItem.getHighDesignUrl()); + return Boolean.TRUE; + } + + @Override + public DesignItemDetailVO detail(Long designPythonOutfitId, Long designItemId) { + // 1、校验 + DesignItem designItem = designItemService.getById(designItemId); + if (Objects.isNull(designItem)) { + throw new BusinessException("designItem.not.found"); + } + Design design = getById(designItem.getDesignId()); + if (Objects.isNull(design)) { + throw new BusinessException("design.not.found"); + } + List designItemDetails = designItemDetailService.selectByDesignItemId(designItemId); + if (CollectionUtil.isEmpty(designItemDetails)) { + throw new BusinessException("designItemDetails.not.found"); + } + // 添加判断designPythonOutfitId是否存在 + TDesignPythonOutfit designPythonOutfit = new TDesignPythonOutfit(); + Boolean flag = Boolean.FALSE; + if (Objects.nonNull(designPythonOutfitId)) { + designPythonOutfit = designPythonOutfitService.getById(designPythonOutfitId); + if (Objects.isNull(designPythonOutfit)) { + throw new BusinessException("designPythonOutfit.not.found"); + } + flag = Boolean.TRUE; + } + + // 为没有优先级的衣服添加优先级 + designItemDetailService.setDesignItemDetailPriority(designItemDetails); + + // 2、组装返回参数 + DesignItemDetailVO response = new DesignItemDetailVO(); + response.setSingleOverall(design.getSingleOverall()); + response.setSwitchCategory(design.getSwitchCategory()); + response.setDesignItemId(designItemId); +// response.setDesignItemUrl(designItem.getDesignUrl()); + response.setHighDesignUrl(designItem.getHighDesignUrl()); + List filterDetail = designItemDetails.stream() + .filter(f -> OUTWEAR_DRESS_BLOUSE.contains(f.getType()) || SKIRT_TROUSERS.contains(f.getType()) + || TOPS.contains(f.getType()) || BOTTOMS.contains(f.getType())) + .collect(Collectors.toList()); + response.setClothes(CopyUtil.copyList(filterDetail, DesignItemClothesDetailVO.class, (o, d) -> { + d.setId(o.getId()); + d.setPath(minioUtil.getPreSignedUrl(o.getPath(), 24 * 60, true)); + d.setMinIOPath(o.getPath()); + d.setLevel1Type(converTypeToLevel1(o.getType())); + d.setGradient(JSONObject.parseObject(o.getGradientString(), Gradient.class)); + if (!StringUtil.isNullOrEmpty(o.getUndividedLayer())) d.setUndividedLayer(minioUtil.getPreSignedUrl(o.getUndividedLayer(), CommonConstant.MINIO_IMAGE_EXPIRE_TIME)); + // 根据designItemDetailId获取印花 + List prints = designItemDetailPrintService.getByDesignItemDetailId(o.getId(), "print"); + // 判断有无印花 + if (CollectionUtil.isNotEmpty(prints)) { + // 有印花 + d.setPrintObject(convertToDesignSinglePrintDTO(prints)); + } + // 根据designItemDetailId获取design elements + List trims = designItemDetailPrintService.getByDesignItemDetailId(o.getId(), "trims"); + // 判断有无装饰 trims + if (CollectionUtil.isNotEmpty(trims)) { + // 有印花 + d.setTrims(convertToDesignSinglePrintDTO(trims)); + } + })); + //single 和 Models(模特)时候 系统元素为空 + List filterDetail2 = designItemDetails.stream() +// .filter(f -> SYS_HAIRSTYLE_SHOES.contains(f.getType()) ) + .filter(f -> SYS_HAIRSTYLE_SHOES_BODY.contains(f.getType())) + .collect(Collectors.toList()); + response.setOthers(CopyUtil.copyList(filterDetail2, DesignItemOthersDetailVO.class, (o, d) -> { + // todo 不确定businessId的作用,暂时取消传递,查看影响 +// d.setId(o.getBusinessId()); + d.setId(0L); + d.setPath(minioUtil.getPreSignedUrl(o.getPath(), 24 * 60)); + d.setMinIOPath(o.getPath()); + d.setPrintObject(new DesignPythonItemPrint()); + })); + return editDesignItemLayer(flag, designPythonOutfit, + minioUtil.getPreSignedUrl(designPythonOutfit.getDesignUrl(), 24 * 60), + editResponseColor(designItemDetails, response)); + } + + @Override + public Integer designProcess(String processId) { + ProcessIdObject object = new ProcessIdObject(); + object.setProcess_id(processId); + + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS) + .readTimeout(60, TimeUnit.SECONDS) + .writeTimeout(60, TimeUnit.SECONDS) + .build(); + + MediaType mediaType = MediaType.parse("application/json"); + String param = JSON.toJSONString(object, SerializerFeature.DisableCircularReferenceDetect); + log.info("designProcess请求python 参数:####{}", param); + RequestBody body = RequestBody.create(mediaType, param); + + Request request = new Request.Builder() + .url(accessPythonIp + ":" + accessPythonPort + "/api/get_progress") + .method("POST", body) + .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") + .addHeader("Content-Type", "application/json") + .build(); + + try (Response response = client.newCall(request).execute()) { + if (response.isSuccessful()) { + String responseBody = Objects.requireNonNull(response.body()).string(); + JSONObject responseObject = JSON.parseObject(responseBody); + String num = responseObject.getString("data"); + return Integer.valueOf(num); + } + } catch (IOException | JSONException e) { + log.error("PythonService##design进度条异常###{}", ExceptionUtil.getThrowableList(e)); + } + + return 0; + } + + + private String converTypeToLevel1(String type) { + if (StringUtils.isEmpty(type)) { + return null; + } + SysFileLevel2TypeEnum sysFileLevel2TypeEnum = SysFileLevel2TypeEnum.realNameOf(type); + if (Objects.isNull(sysFileLevel2TypeEnum)) { + return null; + } + if (OUTWEAR_DRESS_BLOUSE.contains(type) || SKIRT_TROUSERS.contains(type)) { + return CollectionLevel1TypeEnum.SKETCH_BOARD.getRealName(); + } + return null; + } + + private Design selectByCollectionId(Long collectionId) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("collection_id", collectionId); + return designMapper.selectOne(queryWrapper); + } + + private int deleteByCollectionId(Long collectionId) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("collection_id", collectionId); + Design design = new Design(); + design.setCollectionId(0L); + return designMapper.update(design, queryWrapper); + } + + private Long saveOne(DesignCollectionDTO designDTO, Long collectionId, Long accountId) { + Design design = CopyUtil.copyObject(designDTO, Design.class); + design.setCreateDate(DateUtil.getByTimeZone(designDTO.getTimeZone())); + design.setCollectionId(collectionId); + design.setAccountId(accountId); + if (designMapper.insert(design) <= 0) { + throw new BusinessException("save.design.failed"); + } + return design.getId(); + } + + /** + * 避免多次连接数据,所这里一次查多条颜色并利用designItemDetailId保持颜色与vo的对应关系 + * + * @param designItemDetails + * @param designItemDetailVO + * @return + */ + private DesignItemDetailVO editResponseColor(List designItemDetails, DesignItemDetailVO designItemDetailVO) { + // 使用designItemDetailId rgb(String)做映射 + HashMap designItemDetailIdColor = new HashMap<>(); + designItemDetails.forEach(designItemDetail -> { + if (!StringUtil.isNullOrEmpty(designItemDetail.getColor())) { + designItemDetailIdColor.put(designItemDetail.getId(), designItemDetail.getColor()); + } + }); + + if (!CollectionUtil.isEmpty(designItemDetailIdColor)){ + Map pantoneByRgbBatch = panToneService.getPantoneByRgbBatch(new ArrayList<>(designItemDetailIdColor.values())); + designItemDetailVO.getClothes().forEach(c -> { + PantoneVO pantoneVO = pantoneByRgbBatch.get(designItemDetailIdColor.get(c.getId())); + c.setColor(pantoneVO); + }); + + designItemDetailVO.getOthers().forEach(o -> { + PantoneVO pantoneVO = pantoneByRgbBatch.get(designItemDetailIdColor.get(o.getId())); + o.setColor(pantoneVO); + }); + } + + return designItemDetailVO; + } + + private DesignItemDetailVO editDesignItemLayer(Boolean flag, TDesignPythonOutfit designPythonOutfit, String designItemUrl, DesignItemDetailVO designItemDetailVO) { + ArrayList detailsVO = new ArrayList<>(); + + if (flag) { + // 1、判断designPythonOutfitId查出的图层信息是否为空(不允许为空,系统内部错误) + List details = designPythonOutfitDetailService.getDetailByDesignPythonOutfitId(designPythonOutfit.getId()); + if (Objects.isNull(details)){ + log.error("Layer information is empty! DesignPythonOutfitId is " + designPythonOutfit.getId()); + throw new BusinessException("layer.information.not.found"); + } + + // 为没有优先级的图层添加优先级 + designPythonOutfitDetailService.setDesignPythonOutfitDetailPriority(details); + + details.forEach(detail -> { +// List offset = new ArrayList<>(); +// if (StringUtil.isNullOrEmpty(detail.getOffset()) || detail.getOffset().equals("null")) { +// offset = Arrays.asList(0L, 0L); +// } else { +// offset = Arrays.stream(detail.getOffset().replaceAll("\\[|\\]", "").split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()); +// } + detailsVO.add(designPythonOutfitDetailService.convertToDesignPythonOutfitVO(detail, null)); + }); + + // 2、将查询出的图层信息填充到designItemDetailVO中 + designItemDetailVO.setDesignItemUrl(minioUtil.getPreSignedUrl(designPythonOutfit.getDesignUrl(), 24 * 60)); + // 2.1 填充clothes + designItemDetailVO.getClothes().forEach(c -> { +// String type = c.getType().toLowerCase(); +// List outfitVOS = detailsVO.stream().filter((detail -> detail.getImageCategory().equals(type + "_back") || +// detail.getImageCategory().equals(type + "_front"))).collect(Collectors.toList()); + List outfitVOS = detailsVO.stream().filter(detail -> detail.getPriority().equals(c.getPriority())).collect(Collectors.toList()); + + c.setLayersObject(outfitVOS); + }); + // 2.2 填充others + designItemDetailVO.getOthers().forEach(o -> { + String type = o.getType().toLowerCase(); + List outfitVOS = detailsVO.stream().filter(detail -> detail.getImageCategory().equals(type + "_back") || + detail.getImageCategory().equals(type + "_front") || + detail.getImageCategory().equals(type + "_left") || + detail.getImageCategory().equals(type + "_right") || + detail.getImageCategory().equals(type)).collect(Collectors.toList()); + o.setLayersObject(outfitVOS); + }); + } else { + designItemDetailVO.setDesignItemUrl(designItemUrl); + } + + return designItemDetailVO; + } + + private DesignSinglePrintDTO convertToDesignSinglePrintDTO(List designItemDetailPrints) { + DesignSinglePrintDTO designSinglePrintDTO = new DesignSinglePrintDTO(); + List prints = new ArrayList<>(); + + // 只有一个印花 + if (designItemDetailPrints.size() == 1) { + DesignItemDetailPrint detailPrint = designItemDetailPrints.get(0); + DesignSinglePrint designSinglePrint = new DesignSinglePrint(); +// designSinglePrintDTO.setIfSingle(detailPrint.getSingleOrOverall().equals("single") ? Boolean.TRUE : Boolean.FALSE); + designSinglePrint.setLevel2Type(detailPrint.getLevel2Type()); + designSinglePrint.setLocation(JSONArray.parseArray(detailPrint.getPosition(), Double.class)); + designSinglePrint.setAngle(detailPrint.getAngle()); + designSinglePrint.setPriority(detailPrint.getPriority()); + designSinglePrint.setPath(minioUtil.getPreSignedUrl(detailPrint.getPath(), 24 * 60)); + designSinglePrint.setMinIOPath(detailPrint.getPath()); + designSinglePrint.setScale(detailPrint.getScale()); + designSinglePrint.setIfSingle(detailPrint.getSingleOrOverall().equals("single") ? Boolean.TRUE : Boolean.FALSE); + prints.add(designSinglePrint); + } else { + // single模式下多个印花 +// designSinglePrintDTO.setIfSingle(Boolean.TRUE); + designItemDetailPrints.forEach(print -> { +// if (print.getSingleOrOverall().equals("single")) { + prints.add(new DesignSinglePrint( + print.getLevel2Type(), + minioUtil.getPreSignedUrl(print.getPath(), 24 * 60), + print.getPath(), + JSONArray.parseArray(print.getPosition(), Double.class), + print.getScale(), + print.getAngle(), + print.getPriority(), + print.getSingleOrOverall().equals("single") ? Boolean.TRUE : Boolean.FALSE)); +// } + }); + } + designSinglePrintDTO.setPrints(prints); + return designSinglePrintDTO; + } + + @Override + public List getModel(List designItemIdList){ + ArrayList models = new ArrayList<>(); + List designIdById = designItemService.selectDesignIdById(designItemIdList); + if (CollectionUtil.isEmpty(designIdById)){ + log.info("according to the designItemIdList cannot find the designIdList"); + throw new BusinessException("design.not.found"); + } + List designIdList = designIdById.stream().map(DesignItem::getDesignId).collect(Collectors.toList()); + List designs = selectList(designIdList); + if (CollectionUtil.isEmpty(designIdList)){ + log.info("according to the designIdList cannot find the design"); + throw new BusinessException("design.not.found"); + } + List modelFromLibIds = designs.stream().filter(design -> design.getModelType().equals("Library")).map(Design::getTemplateId).collect(Collectors.toList()); + if (!CollectionUtil.isEmpty(modelFromLibIds)){ + models.addAll(libraryService.getByIds(modelFromLibIds).stream() + .map(d -> minioUtil.getPreSignedUrl(d.getUrl(), 24 * 60)) + .collect(Collectors.toList())); + } + List modelFromSysIds = designs.stream().filter(design -> design.getModelType().equals("System")).map(Design::getTemplateId).collect(Collectors.toList()); + if (!CollectionUtil.isEmpty(modelFromSysIds)){ + models.addAll(sysFileService.getByIds(modelFromSysIds).stream() + .map(d -> minioUtil.getPreSignedUrl(d.getUrl(), 24 * 60)) + .collect(Collectors.toList())); + } + + return models; + } + + private List selectList(List designIdList){ + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.in("id",designIdList); + + return designMapper.selectList(queryWrapper); + } + + // 查询指定用户在指定时间内使用了多少次design + public Long getCountByUserAndTime(String startTime, String endTime, List accountIds){ + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.gt("create_date", startTime) + .lt("create_date", endTime) + .select("count(id) as count"); + + if (!Objects.isNull(accountIds) && !accountIds.isEmpty() ){ + queryWrapper.in("account_id", accountIds); + } + + List> result = baseMapper.selectMaps(queryWrapper); + if (result != null && !result.isEmpty()) { + Object countObj = result.get(0).get("count"); + return (Long) countObj; + }else { + return 0L; + } + } + +} diff --git a/src/main/java/com/ai/da/service/impl/GenerateServiceImpl.java b/src/main/java/com/ai/da/service/impl/GenerateServiceImpl.java index 528159bc..46e68d41 100644 --- a/src/main/java/com/ai/da/service/impl/GenerateServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/GenerateServiceImpl.java @@ -237,7 +237,7 @@ public class GenerateServiceImpl extends ServiceImpl i // 执行积分扣除 // ** 注:如果生成的图片都是空白 则不扣积分 - if (!status.equals("Invalid")){ + if (!status.equals("Invalid")) { String accountId = taskId.substring(taskId.lastIndexOf("-") + 1); String uuid = taskId.substring(0, taskId.substring(0, taskId.lastIndexOf("-")).lastIndexOf("-")); Boolean flag = creditsService.taskCreditsDeduction(Long.parseLong(accountId), uuid); @@ -270,7 +270,7 @@ public class GenerateServiceImpl extends ServiceImpl i redisUtil.addToString(key, new Gson().toJson(generateResultVO), CommonConstant.GENERATE_RESULT_EXPIRE_TIME); Long accountId = Long.parseLong(taskId.substring(taskId.lastIndexOf("-") + 1)); - if (!status.equals("Invalid")){ + if (!status.equals("Invalid")) { // 4、扣除积分 Boolean b = creditsService.taskCreditsDeduction(accountId, taskId); // 3、记录积分变更 @@ -778,4 +778,11 @@ public class GenerateServiceImpl extends ServiceImpl i return baseMapper.selectList(qw); } + + @Resource + private GenerateMapper generateMapper; + public List> getCountByUserAndTime(String startTime, String endTime, List accountIdList) { + List> byTypeAndTime = generateMapper.getByTypeAndTime(startTime, endTime, accountIdList); + return byTypeAndTime; + } } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 8550475d..974fee23 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -2,7 +2,7 @@ #spring.profiles.active=test #����application-prod�ļ�(��������) -spring.profiles.active=prod +#spring.profiles.active=prod #����application-dev�ļ�(��������) -#spring.profiles.active=dev +spring.profiles.active=dev diff --git a/src/main/resources/mapper/primary/GenerateMapper.xml b/src/main/resources/mapper/primary/GenerateMapper.xml new file mode 100644 index 00000000..73191c06 --- /dev/null +++ b/src/main/resources/mapper/primary/GenerateMapper.xml @@ -0,0 +1,46 @@ + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/primary/ToProductImageResultMapper.xml b/src/main/resources/mapper/primary/ToProductImageResultMapper.xml new file mode 100644 index 00000000..097f125f --- /dev/null +++ b/src/main/resources/mapper/primary/ToProductImageResultMapper.xml @@ -0,0 +1,19 @@ + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/primary/TrialOrderMapper.xml b/src/main/resources/mapper/primary/TrialOrderMapper.xml index 30f62bf0..827aa65d 100644 --- a/src/main/resources/mapper/primary/TrialOrderMapper.xml +++ b/src/main/resources/mapper/primary/TrialOrderMapper.xml @@ -4,18 +4,24 @@ - - - - - - - - - - - + + + + + + + + + + + +