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.response.ResultEnum;
import com.ai.da.common.utils.*;
import com.ai.da.mapper.primary.*;
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.enums.*;
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.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import io.netty.util.internal.StringUtil;
import lombok.RequiredArgsConstructor;
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.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
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
@RequiredArgsConstructor
public class DesignServiceImpl extends ServiceImpl<DesignMapper, Design> implements DesignService {
    private final CloudTaskMapper cloudTaskMapper;
    private final CloudTaskService cloudTaskService;
    private final CreditsService creditsService;
    private final CollectionElementService collectionElementService;
    private final CollectionService collectionService;
    private final CollectionSortService collectionSortService;
    private final ColorLoopUpTableService colorLoopUpTableService;
    private final CollectionElementRelModelMapper collectionElementRelModelMapper;
    private final DesignBatchMapper designBatchMapper;
    private final DesignMapper designMapper;
    private final DesignItemService designItemService;
    private final DesignItemDetailMapper designItemDetailMapper;
    private final DesignItemDetailService designItemDetailService;
    private final DesignItemDetailPrintService designItemDetailPrintService;
    private final TDesignPythonOutfitMapper designPythonOutfitMapper;
    private final ITDesignPythonOutfitService designPythonOutfitService;
    private final ITDesignPythonOutfitDetailService designPythonOutfitDetailService;
    private final FileProperties fileProperties;
    private final GenerateDetailMapper generateDetailMapper;
    private final LibraryService libraryService;
    private final MinioUtil minioUtil;
    private final MoodboardPositionMapper moodboardPositionMapper;
    private final ProjectService projectService;
    private final PythonService pythonService;
    private final PanToneMapper panToneMapper;
    private final PanToneService panToneService;
    private final PoseTransformationMapper poseTransformationMapper;
    private final PythonTAllInfoService pythonTAllInfoService;
    private final RedisUtil redisUtil;
    private final SysFileService sysFileService;
    private final TCollectionElementRelationService tCollectionElementRelationService;
    private final ToProductImageResultMapper toProductImageResultMapper;
    private final ToProductElementMapper toProductElementMapper;
    private final ToProductImageRecordMapper toProductImageRecordMapper;
    private final UserLikeGroupService userLikeGroupService;
    private final UserLikeService userLikeService;
    private final UserBehaviorMapper userBehaviorMapper;
    private final UserPreferenceLogMapper userPreferenceLogMapper;
    private final WorkspaceService workspaceService;

    @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;

    private final ConcurrentHashMap<String, Map<String, Object>> designContext = new ConcurrentHashMap<>();


    @Override
    public String designCollection(DesignCollectionDTO designDTO) {
        AuthPrincipalVo userInfo = UserContext.getUserHolder();
        //校验collection element
        ValidateElementVO elementVO = collectionElementService.validateElement(designDTO);
        //design
        return designOrRedesignOperateNew(designDTO, userInfo, designDTO.getCollectionId(), elementVO);
    }

    private void calculateLibraryAndSysFile(DesignCollectionDTO designDTO, ValidateElementVO elementVO, AuthPrincipalVo userInfo) {
        //查询用户 sketch library
        List<LibraryVo> libraryVos;
        if (CollectionUtil.isNotEmpty(designDTO.getSketchBoards())) {
            List<String> 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<SysFileVO> 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<LibraryVo> 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<CollectionElement> saveElements = elementVO.getLibraryCollectionElements();
        collectionElementService.saveBatch(saveElements);
        elementVO.getUsedElementIds().addAll(saveElements.stream().map(CollectionElement::getId).collect(Collectors.toList()));
        //sketch
        List<CollectionElement> 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<CollectionElement> 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<CollectionElement> 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<CollectionElement> saveElements = elementVO.getGenerateCollectionElements();
        collectionElementService.saveBatch(saveElements);
        elementVO.getUsedElementIds().addAll(saveElements.stream().map(CollectionElement::getId).collect(Collectors.toList()));
        //sketch
        List<CollectionElement> 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<CollectionElement> 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<CollectionElement> 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<Long> elementIds = getElementId(elementVO);
//        //批量关联element 到 collection
//        collectionElementService.relationCollection(elementIds, collectionId);
//        //library转化为collection(生成)
//        saveCollectionElemntsByLibrarys(elementVO, collectionId);
//        //保存颜色版
//        List<CollectionElementVO> 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<CollectionElement> reLationelements = collectionElementService.getByOnlyCollectionId(collectionId);
//        List<Long> 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 String 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;
        if (null == collectionIdParam) {
            collectionId = collectionService.saveCollection(userInfo.getId(), designDTO.getTimeZone(), designDTO.getMoodTemplateId(), designDTO.getMoodboardPosition());
        } else {
            collectionId = collectionIdParam;
        }
        List<Long> 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);

        // ========== AI设计生成阶段 ==========

        // 组装design入参 - 将业务参数转换为Python AI服务所需的格式
        long startTime = System.currentTimeMillis();
        DesignPythonObjects pythonObjects = pythonService.covertDesignParam(designDTO.getSystemScale(),
                designDTO.getSingleOverall(), designDTO.getSwitchCategory(), elementVO, designDTO.getProcessId(), collectionIdParam);
        long endTime = System.currentTimeMillis();
        long totalTimeInSeconds = (endTime - startTime) / 1000;
        log.info("组装入参运行时间：" + totalTimeInSeconds + " 秒");

        // pythonObjects增加image_id关联 - 建立设计元素与图片的关联关系
        startTime = System.currentTimeMillis();
        relationImageIds(pythonObjects);
        endTime = System.currentTimeMillis();
        totalTimeInSeconds = (endTime - startTime) / 1000;
        log.info("增加image_id关联运行时间：" + totalTimeInSeconds + " 秒");

        // design - 调用Python AI服务进行设计生成
        startTime = System.currentTimeMillis();
        String requestId = UUID.randomUUID().toString();
        pythonObjects.setRequestId(requestId);
        JSONObject responseJSONObject = pythonService.designStream(pythonObjects);
        endTime = System.currentTimeMillis();
        totalTimeInSeconds = (endTime - startTime) / 1000;
        log.info("design python端运行时间：" + totalTimeInSeconds + " 秒");
        // ========== 后处理阶段 ==========

        // 生成library - 根据设计元素生成设计库信息
        startTime = System.currentTimeMillis();
        String ageGroup = workspaceService.getAgeGroupByProjectOrCollectionId(designDTO.getProjectId(), collectionId);
        generateLibrary(elementVO, designDTO.getTimeZone(), ageGroup);
        //处理关联关系,修复element覆盖得情况
//        List<CollectionElement> relationElements = collectionElementService.getByOnlyCollectionId(collectionId);
//        List<Long> relationElementIds = relationElements.stream().map(CollectionElement::getId).collect(Collectors.toList());
//        handleCollectionElementRelation(collectionId, null != collectionIdParam, relationElementIds);
        endTime = System.currentTimeMillis();
        totalTimeInSeconds = (endTime - startTime) / 1000;
        log.info("处理关联关系运行时间：" + totalTimeInSeconds + " 秒");

        // 构建设计上下文信息 - 保存设计过程中的关键参数和状态
        Map<String, Object> context = new HashMap<>();
        context.put("pythonObjects", pythonObjects); // 转换后的 Python 请求参数
        context.put("designId", designId);           // 设计 ID
        context.put("collectionId", collectionId);   // 集合 ID
        context.put("userInfo", userInfo);           // 用户信息
        context.put("timeZone", designDTO.getTimeZone()); // 时区
        context.put("singleOverall", designDTO.getSingleOverall()); // 其他设计参数
        context.put("requestIdList", elementVO.getRequestIdList());

        // 将上下文存入全局设计上下文中 - 用于后续异步查询和处理
        designContext.put(requestId, context);

        // 保存python返回信息;保存designItem和detail（注释说明）
        // 注意：实际的设计结果保存是通过异步回调方式处理的，这里只是准备阶段
//        return savePythonDesignItemAndDetail(pythonObjects, designId, collectionId, userInfo, designDTO.getTimeZone(), responseJSONObject, designDTO.getSingleOverall());

        // 返回请求ID - 客户端可以使用此ID查询设计进度和结果
        return requestId;
    }

    @Override
    public List<CollectionSketchVO> sketchesBoundingBox(ReDesignCollectionDTO reDesignDTO) {
        List<CollectionSketchDTO> sketchBoards = new ArrayList<>();
        for (CollectionSketchDTO dto : reDesignDTO.getSketchBoards()) {
            // 这里假设 CollectionSketchDTO 有一个复制构造函数，或者你可以手动复制它的属性
            CollectionSketchDTO newDto = CopyUtil.copyObject(dto, CollectionSketchDTO.class);
            sketchBoards.add(newDto);
        }

        if (null != reDesignDTO.getCollectionId()) {
            //校验collection
            Collection collection = collectionService.getById(reDesignDTO.getCollectionId());
            if (Objects.isNull(collection)) {
                throw new BusinessException("collection.not.found");
            }
            if (!reDesignDTO.getMoodboardPosition().equals(collection.getMoodboardPosition())) {
                collection.setMoodboardPosition(reDesignDTO.getMoodboardPosition());
            }
            if (null != reDesignDTO.getMoodTemplateId() && !reDesignDTO.getMoodTemplateId().equals(collection.getMoodTemplateId())) {
                collection.setMoodTemplateId(reDesignDTO.getMoodTemplateId());
            }
            collectionService.updateById(collection);
            //校验collection element
            DesignCollectionDTO designCollectionDTO = CopyUtil.copyObject(reDesignDTO, DesignCollectionDTO.class);
            ValidateElementVO elementVO = collectionElementService.validateElement(designCollectionDTO);
            //计算并删除对应的未关联的element
            List<Long> longs = calculateNoRelationElement(reDesignDTO.getCollectionId(), elementVO.getUsedElementIds());
            if (!CollectionUtils.isEmpty(longs)) {
                collectionElementService.batchDelete(longs);
            }
            //redesign
            DesignCollectionDTO designDTO = CopyUtil.copyObject(reDesignDTO, DesignCollectionDTO.class);
            Long collectionIdParam = reDesignDTO.getCollectionId();
            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 = collectionIdParam;
            List<Long> 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());

            //处理关联关系,修复element覆盖得情况
            List<CollectionElement> relationElements = collectionElementService.getByOnlyCollectionId(collectionId);
            List<Long> relationElementIds = relationElements.stream().map(CollectionElement::getId).collect(Collectors.toList());
            handleCollectionElementRelation(collectionId, null != collectionIdParam, relationElementIds);
        }
        if (CollectionUtil.isNotEmpty(sketchBoards)) {
            List<CollectionSketchVO> result = new ArrayList<>();
            List<CollectionSketchDTO> 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, true));
                        } else {
                            vo.setUrlWithWhiteSide(minioUtil.getPreSignedUrl(url + "-show", 24 * 60, true));
                        }
                        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, true));
                        } else {
                            vo.setUrlWithWhiteSide(minioUtil.getPreSignedUrl(url + "-show", 24 * 60, true));
                        }
                        result.add(vo);
                    }
                }
            }
            List<CollectionSketchDTO> 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, true));
                } else {
                    vo.setUrlWithWhiteSide(minioUtil.getPreSignedUrl(url + "-show", 24 * 60, true));
                }
                result.add(vo);
            }
            return result;
        }
        return new ArrayList<>();
    }

    @Override
    public List<Long> relationImageIds(DesignPythonObjects pythonObjects) {
        List<Long> imageIds = new ArrayList<>();
        if (Objects.isNull(pythonObjects)) {
            return imageIds;
        }
        pythonObjects.getObjects().forEach(
                o -> {
                    for (DesignPythonItem item : o.getItems()) {
                        List<Long> 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<Long> 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, String ageGroup) {
        List<CollectionElement> 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());
        }
        if (!CollectionUtils.isEmpty(elementVO.getGenerateCollectionElements())) {
            elements.addAll(elementVO.getGenerateCollectionElements());
        }
        collectionElementService.saveLibraryByCollectionElement(elements, timeZone, elementVO.getModelSex(), ageGroup);
    }

    @Override
    public BigDecimal countDesignProcess() {
        AuthPrincipalVo userInfo = UserContext.getUserHolder();
        List<String> 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<String> saveNames = pythonObjects.getObjects().stream().map(object -> {
            return object.getBasic().getSave_name();
        }).collect(Collectors.toList());
        LocalCacheUtils.setDesignProcessCache(userId, saveNames);
    }


    private DesignCollectionVO savePythonDesignItemAndDetailSingle(DesignPythonObjects pythonObjects, Long designId, Long collectionId, AuthPrincipalVo userInfo, String timeZone, JSONObject outfit, String singleOverall, Map<String, Object> context) {
        Object designCollectionVO = context.get("DesignCollectionVO");
        DesignCollectionVO response;
        List<DesignCollectionItemVO> designCollectionItems = Lists.newArrayList();
        if (null == designCollectionVO) {
            response = new DesignCollectionVO();
            response.setDesignId(designId);
            response.setCollectionId(collectionId);
            response.setProcessId(pythonObjects.getProcess_id());
        } else {
            response = (DesignCollectionVO) designCollectionVO;
            designCollectionItems = response.getDesignCollectionItems();
        }

        response.setDesignCollectionItems(designCollectionItems);


        DesignPythonObject item = new DesignPythonObject();
        String objectSign = outfit.getString("objectSign");
//        log.info(objectSign);
        for (DesignPythonObject object : pythonObjects.getObjects()) {
            if (object.getObjectSign().equals(objectSign)) {
                item = object;
                continue;
            }
        }


        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
        Map<String, Object> bodyPointTest = item.getBasic().getBody_point_test();
        // 转换 relation_id (Long)
        Long relationId = Optional.ofNullable(bodyPointTest.get("relation_id"))
                .filter(Number.class::isInstance)
                .map(num -> ((Number) num).longValue())
                .orElse(null);

        // 转换 relation_type (String)
        String relationType = Optional.ofNullable(bodyPointTest.get("relation_type"))
                .filter(String.class::isInstance)
                .map(String.class::cast)
                .orElse(null);
        designItem.setModelId(relationId);
        designItem.setModelType(relationType);
        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<TDesignPythonOutfitDetail> list = new ArrayList<>();
        DesignCollectionItemVO designCollectionItemVO = new DesignCollectionItemVO();
        designCollectionItemVO.setObjectSign(objectSign);
        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<DesignItemDetail> designItemDetails = Lists.newArrayList();
        Map<String, Integer> typePriority = list.stream().collect(Collectors.toMap(d -> d.getImageCategory().split("_")[0],
                d -> Math.abs(d.getPriority()),
                (existing, replacement) -> replacement));
        Map<String, String> typeAndUndividedLayer = designItemService.setTypeAndUndividedLayer(layers);
        log.info("all typeLayers Map:{}", typeAndUndividedLayer);
        Map<String, List<String>> priorityAndUndividedLayer = designItemService.setPriorityAndUndividedLayer(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));
            log.info("detail.getType():{}", detail.getType());
            if (!detail.getType().equals("Body")) {
                log.info("layer : {}", typeAndUndividedLayer.get(designItemDetail.getType()));
                designItemDetail.setUndividedLayer(typeAndUndividedLayer.get(designItemDetail.getType()));
            }
            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));
                designItemDetail.setUndividedLayer(priorityAndUndividedLayer.get(designItemDetail.getPriority().toString()).get(0));
                designItemDetail.setUndividedLayerWithSinglePrint(priorityAndUndividedLayer.get(designItemDetail.getPriority().toString()).get(1));
            }
            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(Arrays.toString(new Float[]{0.3f, 0.3f}));
                print.setAngle(0.0);
                print.setPriority(1);
                QueryWrapper<CollectionElement> 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);
            }
        }
        synchronized (context) {
            context.put("DesignCollectionVO", response);
        }
        return response;
    }

    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<DesignCollectionItemVO> 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<TDesignPythonOutfitDetail> 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<DesignItemDetail> designItemDetails = Lists.newArrayList();
            Map<String, Integer> typePriority = list.stream().collect(Collectors.toMap(d -> d.getImageCategory().split("_")[0],
                    d -> Math.abs(d.getPriority()),
                    (existing, replacement) -> replacement));
            Map<String, String> 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));
                if (!detail.getType().equals("Body")) {
                    designItemDetail.setUndividedLayer(typeAndUndividedLayer.get(designItemDetail.getType()));
                }

                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(Arrays.toString(new Float[]{0.3f, 0.3f}));
                    print.setAngle(0.0);
                    print.setPriority(1);
                    QueryWrapper<CollectionElement> 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<DesignCollectionItemVO> 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, null, null));

            List<DesignItemDetail> 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<Long> getElementId(ValidateElementVO elementVO) {
        List<Long> 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 String 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<LibraryVo> 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<Long> 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<Long> calculateNoRelationElement(Long collectionId, List<Long> usedElementIds) {
        List<CollectionElement> 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<DesignItem> designItems = designItemService.getByDesignId(designId);
        if (CollectionUtils.isEmpty(designItems)) {
            return new DesignCollectionVO(designId, design.getCollectionId(), null, null, null);
        }
        return new DesignCollectionVO(designId, design.getCollectionId(), coverDesignItemToVO(designItems), null, null);
    }

    private List<DesignCollectionItemVO> coverDesignItemToVO(List<DesignItem> designItems) {
        List<DesignCollectionItemVO> response = Lists.newArrayList();
        designItems.forEach(designItem -> {
            response.add(new DesignCollectionItemVO(designItem.getId(), designItem.getDesignUrl(), null, null, 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<CollectionElement> oldElements = collectionElementService.getByCollectionId(userLikeGroup.getCollectionId());
//            if (CollectionUtil.isEmpty(oldElements)) {
//                throw new BusinessException("old.elements.not.found");
//            }
//            List<DesignItemDetail> designItemDetails = designItemDetailService.selectByDesignItemId(designLikeDTO.getDesignItemId());
//            if (CollectionUtil.isEmpty(designItemDetails)) {
//                throw new BusinessException("new.designItemDetails.not.found");
//            }
            //判断老的element合并到新的是否满足 数量不超过15
//            List<Long> newElementIds = validateMergeElement(oldElements, designItemDetails);
            //合并,关联新的element到collection
//            collectionElementService.relationCollection(newElementIds, userLikeGroup.getCollectionId());
            //处理关联关系,修复element覆盖得情况
//            handleCollectionElementRelation(userLikeGroup.getCollectionId(), false, newElementIds);

            QueryWrapper<TDesignPythonOutfit> qw = new QueryWrapper<>();
            qw.lambda().eq(TDesignPythonOutfit::getDesignItemId, designLikeDTO.getDesignItemId());
            List<TDesignPythonOutfit> 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(), designLikeDTO.getProjectId());
            QueryWrapper<TDesignPythonOutfit> qw = new QueryWrapper<>();
            qw.lambda().eq(TDesignPythonOutfit::getDesignItemId, designLikeDTO.getDesignItemId());
            List<TDesignPythonOutfit> 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);
        Long userLikeSortId;
        CollectionSort userLikeSort = collectionSortService.addCollectionSort(userLike.getId(), CollectionType.DESIGN.getValue(), designLikeDTO.getProjectId(), null);
        userLikeSortId = userLikeSort.getId();
        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);
        // 记录喜欢的系统sketch
        addSystemLikeSketch(designItem);
        // 更新项目更新时间
        projectService.modifyProjectUpdateTime(designLikeDTO.getProjectId());
        return new DesignLikeVO(userLikeSortId, userGroupId, groupDetailId, pictureName, userLike.getId(), userLikeSort.getSort());
    }

    private void addSystemLikeSketch(DesignItem designItem) {
        AuthPrincipalVo userHolder = UserContext.getUserHolder();
        QueryWrapper<DesignItemDetail> qw = new QueryWrapper<>();
        qw.lambda().eq(DesignItemDetail::getDesignItemId, designItem.getId());
        qw.lambda().ne(DesignItemDetail::getType, "Body");
        List<DesignItemDetail> designItemDetails = designItemDetailMapper.selectList(qw);
        for (DesignItemDetail designItemDetail : designItemDetails) {
            if (designItemDetail.getPath().startsWith("aida-sys-image")) {
                String[] split = designItemDetail.getPath().split("/");
                UserBehavior userBehavior = new UserBehavior();
                userBehavior.setAccountId(userHolder.getId());
                userBehavior.setBehaviorType(UserBehaviorType.SKETCH_LIKE.getValue());
                userBehavior.setGender(split[2]);
                userBehavior.setCategory(split[3]);
                userBehavior.setUrl(designItemDetail.getPath());
                userBehavior.setCreateTime(LocalDateTime.now());
                userBehaviorMapper.insert(userBehavior);

                UserPreferenceLogTest userPreferenceLogTest = new UserPreferenceLogTest();
                userPreferenceLogTest.setPath(designItemDetail.getPath());
                userPreferenceLogTest.setAccountId(userHolder.getId());
//                userPreferenceLogTest.setUserLikeGroupId(userLike.getUserLikeGroupId());
                userPreferenceLogTest.setDataTime(designItemDetail.getCreateDate().toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDateTime());
                userPreferenceLogMapper.insert(userPreferenceLogTest);
            }
        }
    }

    private List<Long> validateMergeElement(List<CollectionElement> oldElements, List<DesignItemDetail> designItemDetails) {
        List<DesignItemDetail> hasCollections = designItemDetails.stream()
                .filter(f -> Objects.nonNull(f.getCollectionElementId()))
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(hasCollections)) {
            return null;
        }
        List<Long> elementIds = hasCollections.stream().map(DesignItemDetail::getCollectionElementId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(oldElements)) {
            return elementIds;
        }
        List<Long> oldIds = oldElements.stream().map(CollectionElement::getId).collect(Collectors.toList());
        //本次新增collection个数
        List<Long> adds = elementIds.stream().filter(id -> !oldIds.contains(id)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(adds)) {
            return null;
        }
        //校验15次
        Map<String, List<CollectionElement>> group = oldElements.stream()
                .collect(Collectors.groupingBy(CollectionElement::getLevel1Type));

        group.forEach((k, v) -> {
            List<CollectionElement> 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<CollectionElement> thisElement, List<Long> adds) {
        int num = 0;
        List<Long> 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);
        userLike.setConverted(1);
        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,先不做
        List<UserLikeVO> userLikeVOS = userLikeService.getGroupDetail(userLike.getUserLikeGroupId());
        if (CollectionUtils.isEmpty(userLikeVOS)) {
            //group 下面没有元素时候 直接删除
//            userLikeGroupService.removeById(userLike.getUserLikeGroupId());
        }

        collectionSortService.deleteCollectionSort(userLike.getId(), CollectionType.DESIGN.getValue(), disDesignLikeDTO.getProjectId(), null);
        //删除对应的history
        userLikeService.removeById(disDesignLikeDTO.getGroupDetailId());
        // 更新项目更新时间
        projectService.modifyProjectUpdateTime(disDesignLikeDTO.getProjectId());
        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) {
        log.info("获取design detail -> 【designPythonOutfitId : {}, designItemId : {}】 ", designPythonOutfitId, 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<DesignItemDetail> designItemDetails = designItemDetailService.selectByDesignItemId(designItemId);
        designItemDetails.removeIf(designItemDetail -> !minioUtil.doesObjectExist(designItemDetail.getPath()));
        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;
        }

        // 为没有优先级的衣服添加优先级
        if (!StringUtil.isNullOrEmpty(design.getSingleOverall()) && design.getSingleOverall().equals("overall")) {
            designItemDetailService.setDesignItemDetailPriority(designItemDetails);
        }

        // 2、组装返回参数
        DesignItemDetailVO response = new DesignItemDetailVO();
        response.setSingleOverall(design.getSingleOverall());
        response.setSwitchCategory(design.getSwitchCategory());
        response.setDesignItemId(designItemId);
        response.setHighDesignUrl(designItem.getHighDesignUrl());
        List<DesignItemDetail> filterDetail = designItemDetails.stream()
                .filter(f -> OUTWEAR_DRESS_BLOUSE.contains(f.getType()) || SKIRT_TROUSERS.contains(f.getType())
                        || TOPS.contains(f.getType()) || BOTTOMS.contains(f.getType()) || OTHERS.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.setScope(o.getPath().startsWith("aida-sys-image") ? "sys" : "user");
            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));
            }
            if (!StringUtil.isNullOrEmpty(o.getUndividedLayerWithSinglePrint())) {
                d.setUndividedLayerWithSinglePrint(minioUtil.getPreSignedUrl(o.getUndividedLayerWithSinglePrint(), CommonConstant.MINIO_IMAGE_EXPIRE_TIME));
            }
            // 根据designItemDetailId获取印花
            List<DesignItemDetailPrint> prints = designItemDetailPrintService.getByDesignItemDetailId(o.getId(), "print");
            prints.removeIf(print -> !minioUtil.doesObjectExist(print.getPath()));
            // 判断有无印花
            if (CollectionUtil.isNotEmpty(prints)) {
                // 有印花
                d.setPrintObject(convertToDesignSinglePrintDTO(prints, o.getPath()));
            }
            // 根据designItemDetailId获取design elements
            List<DesignItemDetailPrint> trims = designItemDetailPrintService.getByDesignItemDetailId(o.getId(), "trims");
            // 判断有无装饰 trims
            if (CollectionUtil.isNotEmpty(trims)) {
                // 有印花
                d.setTrims(convertToDesignSinglePrintDTO(trims, o.getPath()));
            }
            String preSigned = StringUtil.isNullOrEmpty(o.getPartialDesign()) ? null : minioUtil.getPreSignedUrl(o.getPartialDesign(), CommonConstant.MINIO_IMAGE_EXPIRE_TIME);
            d.setPartialDesign(new PartialDesignDTO(o.getPartialDesign(), preSigned));
            DesignItemDetailCanvas designItemDetailCanvas = designItemDetailService.getDIDCByDesignItemDetailId(o.getId());
            if (Objects.nonNull(designItemDetailCanvas)) {
                d.setCanvasId(designItemDetailCanvas.getExportFileId());
            }
        }));
        //single 和 Models(模特)时候 系统元素为空
        List<DesignItemDetail> 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) -> {
            d.setId(0L);
            d.setPath(minioUtil.getPreSignedUrl(o.getPath(), 24 * 60));
            d.setMinIOPath(o.getPath());
            d.setPrintObject(new DesignPythonItemPrint());
        }));
        response.getOthers().removeIf(o -> !minioUtil.doesObjectExist(o.getMinIOPath()));
        return editDesignItemLayer(flag, designPythonOutfit,
                minioUtil.getPreSignedUrl(designPythonOutfit.getDesignUrl(), 24 * 60),
                editResponseColor(designItemDetails, response), design);
    }

    @Override
    public Integer designProcess(String processId) {
        // 假设 Redis 中存储的最大进度为 8，分配前 50%
        int redisMaxProgress = 8;
        int totalProgress = 100;
        int redisWeight = 50; // Redis 进度占 50%
        int pythonWeight = 50; // Python 接口进度占 50%

        // 先从 Redis 中查询当前进度
        String redisKey = "process:progress:" + processId;
        String redisProgressString = redisUtil.getFromString(redisKey);
        int redisProgress = redisProgressString != null ? Integer.parseInt(redisProgressString) : 0;

        // 如果 Redis 进度未达到最大值，则返回前 50% 的部分
        if (redisProgress < redisMaxProgress) {
            int progressPercentage = (redisProgress * redisWeight) / redisMaxProgress;
            return progressPercentage;
        }

        // Redis 进度已经达到 8，查询 Python 接口获取后 50% 的进度
        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");
                int pythonProgress = Integer.parseInt(num);

                // Redis 进度占前 50%，Python 进度占后 50%
                int combinedProgress = redisWeight + (pythonProgress * pythonWeight) / totalProgress;
                return combinedProgress;
            }
        } catch (IOException | JSONException e) {
            log.error("PythonService##design进度条异常###{}", ExceptionUtil.getThrowableList(e));
        }

        // 如果 Python 请求失败，仍然返回前 50% 的 Redis 进度
        return redisWeight;
    }


    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<Design> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("collection_id", collectionId);
        return designMapper.selectOne(queryWrapper);
    }

    private int deleteByCollectionId(Long collectionId) {
        QueryWrapper<Design> 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<DesignItemDetail> designItemDetails, DesignItemDetailVO designItemDetailVO) {
        // 使用designItemDetailId rgb(String)做映射
        HashMap<Long, String> designItemDetailIdColor = new HashMap<>();
        designItemDetails.forEach(designItemDetail -> {
            if (!StringUtil.isNullOrEmpty(designItemDetail.getColor())) {
                designItemDetailIdColor.put(designItemDetail.getId(), designItemDetail.getColor());
            }
        });

        if (!CollectionUtil.isEmpty(designItemDetailIdColor)) {
            Map<String, PantoneVO> 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, Design design) {
        ArrayList<DesignPythonOutfitVO> detailsVO = new ArrayList<>();

        if (flag) {
            // 1、判断designPythonOutfitId查出的图层信息是否为空（不允许为空，系统内部错误）
            List<TDesignPythonOutfitDetail> 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");
            }

            // 为没有优先级的图层添加优先级
            if (!StringUtil.isNullOrEmpty(design.getSingleOverall()) && design.getSingleOverall().equals("overall")) {
                designPythonOutfitDetailService.setDesignPythonOutfitDetailPriority(details);
            }

            details.forEach(detail -> {
                detailsVO.add(designPythonOutfitDetailService.convertToDesignPythonOutfitVO(detail, null));
            });

            // 2、将查询出的图层信息填充到designItemDetailVO中
            designItemDetailVO.setDesignItemUrl(minioUtil.getPreSignedUrl(designPythonOutfit.getDesignUrl(), 24 * 60));
            // 2.1 填充clothes
            designItemDetailVO.getClothes().forEach(c -> {
                List<DesignPythonOutfitVO> 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<DesignPythonOutfitVO> 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);
        }

        log.info("获取DesignDetail, response: {}", JSONObject.toJSONString(designItemDetailVO));
        return designItemDetailVO;
    }

    private DesignSinglePrintDTO convertToDesignSinglePrintDTO(List<DesignItemDetailPrint> designItemDetailPrints, String sketchPath) {
        DesignSinglePrintDTO designSinglePrintDTO = new DesignSinglePrintDTO();
        List<DesignSinglePrint> 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(), Float.class));
            designSinglePrint.setAngle(detailPrint.getAngle());
            designSinglePrint.setPriority(detailPrint.getPriority());
            designSinglePrint.setPath(minioUtil.getPreSignedUrl(detailPrint.getPath(), 24 * 60));
            designSinglePrint.setMinIOPath(detailPrint.getPath());
            designSinglePrint.setIfSingle(detailPrint.getSingleOrOverall().equals("single") ? Boolean.TRUE : Boolean.FALSE);
            List<Float> scales;
            try {
                scales = JSONArray.parseArray(detailPrint.getScale(), Float.class);
            } catch (JSONException e) {
                Float scale = Float.valueOf(detailPrint.getScale());
                if (designSinglePrint.getIfSingle()) {
                    List<Integer> printWAndH = minioUtil.getImagesWidthAndHeight(detailPrint.getPath());
                    List<Integer> sketchWAndH = minioUtil.getImagesWidthAndHeight(sketchPath);

                    scales = Arrays.asList(scale * printWAndH.get(0) / sketchWAndH.get(0), scale * printWAndH.get(1) / sketchWAndH.get(1));
                } else {
                    scales = Arrays.asList(scale, scale);
                }
            }
            designSinglePrint.setScale(scales);
            prints.add(designSinglePrint);
        } else {
            // 多个印花
//            designSinglePrintDTO.setIfSingle(Boolean.TRUE);
            designItemDetailPrints.forEach(print -> {
//                if (print.getSingleOrOverall().equals("single")) {
                List<Float> scales;
                Boolean ifSingle = print.getSingleOrOverall().equals("single") ? Boolean.TRUE : Boolean.FALSE;
                try {
                    scales = JSONArray.parseArray(print.getScale(), Float.class);
                } catch (JSONException e) {
                    Float scale = Float.valueOf(print.getScale());
                    if (ifSingle) {
                        List<Integer> printWAndH = minioUtil.getImagesWidthAndHeight(print.getPath());
                        List<Integer> sketchWAndH = minioUtil.getImagesWidthAndHeight(sketchPath);
                        scales = Arrays.asList(scale * printWAndH.get(0) / sketchWAndH.get(0), scale * printWAndH.get(1) / sketchWAndH.get(1));
                    } else {
                        scales = Arrays.asList(scale, scale);
                    }
                }
                prints.add(new DesignSinglePrint(
                        print.getLevel2Type(),
                        minioUtil.getPreSignedUrl(print.getPath(), 24 * 60),
                        print.getPath(),
                        JSONArray.parseArray(print.getPosition(), Float.class),
                        scales,
                        print.getAngle(),
                        print.getPriority(),
                        ifSingle));
//                }
            });
        }
        designSinglePrintDTO.setPrints(prints);
        return designSinglePrintDTO;
    }

    @Override
    public List<String> getModel(List<Long> designItemIdList) {
        ArrayList<String> models = new ArrayList<>();
        List<DesignItem> 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<Long> designIdList = designIdById.stream().map(DesignItem::getDesignId).collect(Collectors.toList());
        List<Design> designs = selectList(designIdList);
        if (CollectionUtil.isEmpty(designIdList)) {
            log.info("according to the designIdList cannot find the design");
            throw new BusinessException("design.not.found");
        }
        List<Long> 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<Long> 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<Design> selectList(List<Long> designIdList) {
        QueryWrapper<Design> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", designIdList);

        return designMapper.selectList(queryWrapper);
    }

    // 查询指定用户在指定时间内使用了多少次design
    public Long getCountByUserAndTime(String startTime, String endTime, List<Long> accountIds) {
        QueryWrapper<Design> 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<Map<String, Object>> result = baseMapper.selectMaps(queryWrapper);
        if (result != null && !result.isEmpty()) {
            Object countObj = result.get(0).get("count");
            return (Long) countObj;
        } else {
            return 0L;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean receiveDesignResults(JSONObject responseJSONObject) {
//        String requestId = "UUID.randomUUID().toString()";
        System.out.println(responseJSONObject.toJSONString());
        String requestId = responseJSONObject.getString("requestId");
        Map<String, Object> context;
        synchronized (designContext) {
            context = designContext.get(requestId);
            if (context == null) {
                log.error("上下文数据缺失，无法完成操作");
                return false;
            }

            DesignPythonObjects pythonObjects = (DesignPythonObjects) context.get("pythonObjects");
            Long designId = (Long) context.get("designId");
            Long collectionId = (Long) context.get("collectionId");
            AuthPrincipalVo userInfo = (AuthPrincipalVo) context.get("userInfo");
            String timeZone = (String) context.get("timeZone");
            String singleOverall = (String) context.get("singleOverall");

            DesignCollectionVO designCollectionVO = savePythonDesignItemAndDetailSingle(pythonObjects, designId, collectionId, userInfo, timeZone, responseJSONObject, singleOverall, context);

//            log.info(designContext.toString());
            designContext.put(requestId, context);
        }

        return Boolean.TRUE;
    }

    @Override
    public DesignCollectionVO getDesignResult(String requestId, List<String> objectSignList) {
//        Map<String, Object> stringObjectMap = designContext.get("UUID.randomUUID().toString()");
        Map<String, Object> stringObjectMap = designContext.get(requestId);
//        log.info(stringObjectMap.toString());
        DesignCollectionVO result = (DesignCollectionVO) stringObjectMap.get("DesignCollectionVO");
        if (Objects.isNull(result)) {
            DesignCollectionVO noneResult = new DesignCollectionVO();
            noneResult.setUnfinishedList(objectSignList);
            return noneResult;
        }
        for (DesignCollectionItemVO designCollectionItem : result.getDesignCollectionItems()) {
            String objectSign = designCollectionItem.getObjectSign();
            designCollectionItem.setResultType(CollectionType.DESIGN.getValue());
            objectSignList.remove(objectSign);
        }
        result.setUnfinishedList(objectSignList);
        return result;
    }

    public static BigDecimal getRandomFromRange(BigDecimal min, BigDecimal max) {
        if (min == null || max == null || min.compareTo(max) > 0) {
            throw new IllegalArgumentException("Invalid imageStrength range.");
        }

        double random = ThreadLocalRandom.current().nextDouble(min.doubleValue(), max.doubleValue() + 0.0001);
        return new BigDecimal(random).setScale(2, RoundingMode.HALF_UP);
    }

    @Override
    public String designCloud(CloudTaskDTO cloudTaskDTO) {
        AuthPrincipalVo userInfo = UserContext.getUserHolder();
        if (cloudTaskDTO.getBuildType().equals(BuildType.DESIGN.getValue())) {
            Long projectId = cloudTaskDTO.getProjectId();
            DesignCollectionDTO designDTO = transDesignParam(projectId);
            designDTO.setDesignNum(cloudTaskDTO.getNums());

            //校验collection element
            ValidateElementVO elementVO = collectionElementService.validateElement(designDTO);

            //design
            String taskId = designBatch(designDTO, userInfo, null, elementVO, cloudTaskDTO, projectId);
            return taskId;
        } else if (cloudTaskDTO.getBuildType().equals(BuildType.TO_PRODUCT_IMAGE.getValue())) {
            ToProductImageDTO toProductImageDTO = cloudTaskDTO.getToProductImage();
            // 判断用户当前积分是否够本次生成消耗
            Boolean preDeduction = creditsService.creditsPreDeduction(CreditsEventsEnum.TO_PRODUCT_IMAGE, cloudTaskDTO.getNums());
            if (!preDeduction) {
                throw new BusinessException("remaining.credits.insufficient", ResultEnum.WARNING.getCode());
            }
            AuthPrincipalVo userHolder = UserContext.getUserHolder();

            String batchTaskId = UUID.randomUUID() + "-" + userHolder.getId();

            Long projectId = cloudTaskDTO.getProjectId();
            if (null == projectId) {
                Project project = new Project();
                project.setName(DesignProcess.TO_PRODUCT_IMAGE.getValue() + "_" + cloudTaskDTO.getName());
                project.setProcess(DesignProcess.TO_PRODUCT_IMAGE.name());
                project.setOriginal(1);
                project.setAccountId(userHolder.getId());
                LocalDateTime now = LocalDateTime.now();
                project.setCreateTime(now);
                project.setUpdateTime(now);
                projectService.save(project);
                projectId = project.getId();
                for (ToProductImageVO toProductImageVO : toProductImageDTO.getToProductImageVOList()) {
                    if (toProductImageVO.getElementType().equals("ProductElement")) {
                        ToProductElement toProductElement = toProductElementMapper.selectById(toProductImageVO.getElementId());
                        toProductElement.setProjectId(projectId);
                        toProductElementMapper.updateById(toProductElement);
                    }
                }
            }
            CloudTask cloudTask = CopyUtil.copyObject(cloudTaskDTO, CloudTask.class);
            cloudTask.setProjectId(projectId);
            cloudTask.setTaskId(batchTaskId);
            LocalDateTime now = LocalDateTime.now();
            cloudTask.setCreateTime(now);
            cloudTask.setUpdateTime(now);
            cloudTask.setStatus(0);
            cloudTask.setAccountId(userInfo.getId());
            cloudTaskMapper.insert(cloudTask);
            // 解除锁后可以获取下一个序号
            projectService.clearLockedSequence(userHolder.getId());

            UserLikeGroup userLikeGroup = userLikeGroupService.getByProjectId(projectId);
            Long userLikeGroupId = null;
            ToProductImageRecord toProductImageRecord = new ToProductImageRecord();
            toProductImageRecord.setProjectId(projectId);
            if (Objects.nonNull(userLikeGroup)) {
                userLikeGroupId = userLikeGroup.getId();
                toProductImageRecord.setUserLikeGroupId(userLikeGroupId);
            }

            toProductImageRecord.setCreateTime(LocalDateTime.now());
            if (!StringUtils.isEmpty(toProductImageDTO.getPrompt())) {
                toProductImageRecord.setPrompt(toProductImageDTO.getPrompt());
            }
            toProductImageRecordMapper.insert(toProductImageRecord);

            List<ToProductImageResult> result = new ArrayList<>();

            int i = 0;
            // 翻译
            String prompt = toProductImageDTO.getPrompt();
            StringBuilder sb = new StringBuilder("The best quality, masterpiece, real image.");
            if (!StringUtil.isNullOrEmpty(prompt)) {
                prompt = pythonService.promptTranslate(prompt);
            }

            Map<String, Integer> toProductImageVOIntegerMap = allocateElements(toProductImageDTO.getToProductImageVOList(), cloudTaskDTO.getNums());

            for (ToProductImageVO toProductImageVO : toProductImageDTO.getToProductImageVOList()) {
                String taskId;
                String key = toProductImageVO.getElementId() + "_" + toProductImageVO.getElementType();
                if (toProductImageVO.getElementType().equals("DesignOutfit")) {
                    TDesignPythonOutfit tDesignPythonOutfit = designPythonOutfitMapper.selectById(toProductImageVO.getElementId());

                    Long designItemId = tDesignPythonOutfit.getDesignItemId();
                    QueryWrapper<DesignItemDetail> designItemDetailQueryWrapper = new QueryWrapper<>();
                    designItemDetailQueryWrapper.lambda().eq(DesignItemDetail::getDesignItemId, designItemId);
                    designItemDetailQueryWrapper.lambda().ne(DesignItemDetail::getType, "Body");
                    List<DesignItemDetail> designItemDetails = designItemDetailMapper.selectList(designItemDetailQueryWrapper);
                    String collect = designItemDetails.stream().map(DesignItemDetail::getType).collect(Collectors.joining(","));

                    Long designId = tDesignPythonOutfit.getDesignId();
                    Design design = designMapper.selectById(designId);
                    String productType = "overall";
                    if (design.getSingleOverall().equals("single")) {
                        productType = "single";
                        sb.append(collect);
                    } else {
                        if (collect.contains("Tops")) {
                            sb.append("a handsome man,");
                        } else {
                            sb.append("a beautiful women,");
                        }
                        sb.append("wearing ").append(collect);
                    }
                    if (StringUtils.isEmpty(prompt)) {
                        sb.append(",high quality clothing details,8K realistic,HDR");
                    } else {
                        sb.append(",high quality clothing details,").append(prompt).append(",8K realistic,HDR");
                    }
                    // 走模型
                    List<BatchParamDTO> paramList = new ArrayList<>();
                    List<String> promptList = pythonService.getPrompt(sb.toString(), toProductImageVOIntegerMap.get(key));
                    for (int i1 = 0; i1 < toProductImageVOIntegerMap.get(key); i1++) {
                        BatchParamDTO batchParamDTO = new BatchParamDTO();
                        taskId = UUID.randomUUID() + "-" + i + "-" + userHolder.getId();
                        batchParamDTO.setTasks_id(taskId);
                        batchParamDTO.setPrompt(promptList.get(i1));
                        BigDecimal randomFromRange = getRandomFromRange(toProductImageDTO.getImageStrengthMin(), toProductImageDTO.getImageStrengthMax());
                        batchParamDTO.setImage_strength(randomFromRange);
                        batchParamDTO.setImage_url(tDesignPythonOutfit.getDesignUrl());
                        batchParamDTO.setProduct_type(productType);
                        paramList.add(batchParamDTO);

                        ToProductImageResult toProductImageResult = new ToProductImageResult();
                        toProductImageResult.setElementId(tDesignPythonOutfit.getId());
                        toProductImageResult.setElementType("DesignOutfit");
                        toProductImageResult.setCreateTime(LocalDateTime.now());
                        toProductImageResult.setToProductImageRecordId(toProductImageRecord.getId());
                        toProductImageResult.setIsLike(0);
                        toProductImageResult.setTaskId(taskId);
                        toProductImageResult.setResultType("ToProductImage");
                        toProductImageResult.setProjectId(projectId);
                        toProductImageResult.setTaskIdBatch(batchTaskId);
                        if (userLikeGroupId != null) {
                            toProductImageResult.setUserLikeGroupId(userLikeGroupId);
                        }
                        toProductImageResult.setImageStrength(randomFromRange);
                        toProductImageResultMapper.insert(toProductImageResult);
                        result.add(toProductImageResult);
                        i++;
                    }
                    pythonService.toProductImageBatch(batchTaskId, paramList, userHolder.getId().toString());
                    // 添加需要扣除的积分到预扣除区
                    creditsService.addRecordToCreditsDeduction(userHolder.getId(), batchTaskId, CreditsEventsEnum.TO_PRODUCT_IMAGE, cloudTaskDTO.getNums());
                    // 预插入数据到积分变更表
                    creditsService.preInsert(userHolder.getId(), CreditsEventsEnum.TO_PRODUCT_IMAGE.getName(), batchTaskId, true, null, cloudTaskDTO.getNums());
                } else {
                    if (StringUtils.isEmpty(prompt)) {
                        sb.append(",high quality clothing details,8K realistic,HDR");
                    } else {
                        sb.append(",high quality clothing details,").append(prompt).append(",8K realistic,HDR");
                    }
                    ToProductElement toProductElement = toProductElementMapper.selectById(toProductImageVO.getElementId());
                    // 走模型
                    List<BatchParamDTO> paramList = new ArrayList<>();
                    List<String> promptList = pythonService.getPrompt(sb.toString(), toProductImageVOIntegerMap.get(key));
                    for (int i1 = 0; i1 < toProductImageVOIntegerMap.get(key); i1++) {
                        BatchParamDTO batchParamDTO = new BatchParamDTO();
                        taskId = UUID.randomUUID() + "-" + i + "-" + userHolder.getId();
                        batchParamDTO.setTasks_id(taskId);
                        batchParamDTO.setPrompt(promptList.get(i1));
                        BigDecimal randomFromRange = getRandomFromRange(toProductImageDTO.getImageStrengthMin(), toProductImageDTO.getImageStrengthMax());
                        batchParamDTO.setImage_strength(randomFromRange);
                        batchParamDTO.setImage_url(toProductElement.getUrl());
                        batchParamDTO.setProduct_type("overall");
                        paramList.add(batchParamDTO);

                        ToProductImageResult toProductImageResult = new ToProductImageResult();
                        toProductImageResult.setElementId(toProductElement.getId());
                        toProductImageResult.setElementType("ProductElement");
                        toProductImageResult.setCreateTime(LocalDateTime.now());
                        toProductImageResult.setToProductImageRecordId(toProductImageRecord.getId());
                        toProductImageResult.setIsLike(0);
                        toProductImageResult.setTaskId(taskId);
                        toProductImageResult.setResultType("ToProductImage");
                        toProductImageResult.setProjectId(projectId);
                        toProductImageResult.setTaskIdBatch(batchTaskId);
                        if (userLikeGroupId != null) {
                            toProductImageResult.setUserLikeGroupId(userLikeGroupId);
                        }
                        toProductImageResult.setImageStrength(randomFromRange);
                        toProductImageResultMapper.insert(toProductImageResult);
                        result.add(toProductImageResult);
                        i++;
                    }
                    pythonService.toProductImageBatch(batchTaskId, paramList, userHolder.getId().toString());
                    // 添加需要扣除的积分到预扣除区
                    creditsService.addRecordToCreditsDeduction(userHolder.getId(), batchTaskId, CreditsEventsEnum.TO_PRODUCT_IMAGE, cloudTaskDTO.getNums());
                    // 预插入数据到积分变更表
                    creditsService.preInsert(userHolder.getId(), CreditsEventsEnum.TO_PRODUCT_IMAGE.getName(), batchTaskId, true, null, cloudTaskDTO.getNums());

                }
                sb = new StringBuilder("The best quality, masterpiece, real image.");
            }
            return batchTaskId;
        } else if (cloudTaskDTO.getBuildType().equals(BuildType.RELIGHT.getValue())) {
            ToProductImageDTO toProductImageDTO = cloudTaskDTO.getToProductImage();
            // 判断用户当前积分是否够本次生成消耗
            Boolean preDeduction = creditsService.creditsPreDeduction(CreditsEventsEnum.RELIGHT, cloudTaskDTO.getNums());
            if (!preDeduction) {
                throw new BusinessException("remaining.credits.insufficient", ResultEnum.WARNING.getCode());
            }

            AuthPrincipalVo userHolder = UserContext.getUserHolder();
            String batchTaskId = UUID.randomUUID() + "-" + userHolder.getId();
            Long projectId = cloudTaskDTO.getProjectId();
            if (null == projectId) {
                Project project = new Project();
                project.setName(DesignProcess.RELIGHT.getValue() + "_" + cloudTaskDTO.getName());
                project.setProcess(DesignProcess.RELIGHT.name());
                project.setOriginal(1);
                project.setAccountId(userHolder.getId());
                LocalDateTime now = LocalDateTime.now();
                project.setCreateTime(now);
                project.setUpdateTime(now);
                projectService.save(project);
                projectId = project.getId();
                for (ToProductImageVO toProductImageVO : toProductImageDTO.getToProductImageVOList()) {
                    if (toProductImageVO.getElementType().equals("ProductElement")) {
                        ToProductElement toProductElement = toProductElementMapper.selectById(toProductImageVO.getElementId());
                        toProductElement.setProjectId(projectId);
                        toProductElementMapper.updateById(toProductElement);
                    }
                }
            }

            CloudTask cloudTask = CopyUtil.copyObject(cloudTaskDTO, CloudTask.class);
            cloudTask.setProjectId(projectId);
            cloudTask.setTaskId(batchTaskId);
            LocalDateTime now = LocalDateTime.now();
            cloudTask.setCreateTime(now);
            cloudTask.setUpdateTime(now);
            cloudTask.setStatus(0);
            cloudTask.setAccountId(userInfo.getId());
            cloudTaskMapper.insert(cloudTask);
            // 解除锁后可以获取下一个序号
            projectService.clearLockedSequence(userHolder.getId());

            UserLikeGroup userLikeGroup = userLikeGroupService.getByProjectId(projectId);
            Long userLikeGroupId = null;

            ToProductImageRecord toProductImageRecord = new ToProductImageRecord();
            toProductImageRecord.setProjectId(projectId);
            if (Objects.nonNull(userLikeGroup)) {
                userLikeGroupId = userLikeGroup.getId();
                toProductImageRecord.setUserLikeGroupId(userLikeGroupId);
            }

            toProductImageRecord.setCreateTime(LocalDateTime.now());
            if (!StringUtils.isEmpty(toProductImageDTO.getPrompt())) {
                toProductImageRecord.setPrompt(toProductImageDTO.getPrompt());
            }
            toProductImageRecordMapper.insert(toProductImageRecord);

            List<ToProductImageResult> result = new ArrayList<>();

            int i = 0;
            // 翻译
            String prompt = toProductImageDTO.getPrompt();
            String s = "";
            if (!StringUtil.isNullOrEmpty(prompt)) {
                s = pythonService.promptTranslate(prompt);
            } else {
                s = "Snow moutain, snowy day, natural light";
            }
            Map<String, Integer> toProductImageVOIntegerMap = allocateElements(toProductImageDTO.getToProductImageVOList(), cloudTaskDTO.getNums());
            for (ToProductImageVO toProductImageVO : toProductImageDTO.getToProductImageVOList()) {
                String taskId;
                String key = toProductImageVO.getElementId() + "_" + toProductImageVO.getElementType();
                if (toProductImageVO.getElementType().equals("ToProductImage")) {
                    ToProductImageResult toProductImageResult1 = toProductImageResultMapper.selectById(toProductImageVO.getElementId());
                    String relightType = "overall";
                    if (toProductImageResult1.getElementType().equals("DesignOutfit")) {
                        TDesignPythonOutfit tDesignPythonOutfit = designPythonOutfitMapper.selectById(toProductImageResult1.getElementId());
                        Long designId = tDesignPythonOutfit.getDesignId();
                        Design design = designMapper.selectById(designId);
                        if (design.getSingleOverall().equals("single")) {
                            relightType = "single";
                        }
                        List<BatchParamDTO> paramList = new ArrayList<>();
                        List<String> promptList = pythonService.getPrompt(s, toProductImageVOIntegerMap.get(key));
                        for (int i1 = 0; i1 < toProductImageVOIntegerMap.get(key); i1++) {
                            BatchParamDTO batchParamDTO = new BatchParamDTO();
                            taskId = UUID.randomUUID() + "-" + i + "-" + userHolder.getId();
                            batchParamDTO.setTasks_id(taskId);
                            batchParamDTO.setPrompt(promptList.get(i1));
                            batchParamDTO.setImage_url(toProductImageResult1.getUrl());
                            batchParamDTO.setProduct_type(relightType);
                            batchParamDTO.setDirection(toProductImageDTO.getDirection());
                            paramList.add(batchParamDTO);

                            ToProductImageResult toProductImageResult = new ToProductImageResult();
                            toProductImageResult.setElementId(toProductImageResult1.getId());
                            toProductImageResult.setElementType("ToProductImage");
                            toProductImageResult.setCreateTime(LocalDateTime.now());
                            toProductImageResult.setToProductImageRecordId(toProductImageRecord.getId());
                            toProductImageResult.setIsLike(0);
                            toProductImageResult.setTaskId(taskId);
                            toProductImageResult.setResultType("Relight");
                            toProductImageResult.setProjectId(projectId);
                            toProductImageResult.setTaskIdBatch(batchTaskId);
                            if (null != userLikeGroupId) {
                                toProductImageResult.setUserLikeGroupId(userLikeGroupId);
                            }
                            if (toProductImageDTO.getBrightenValue() != null) {
                                toProductImageResult.setBrightenValue(toProductImageDTO.getBrightenValue());
                            }
                            toProductImageResult.setDirection(toProductImageDTO.getDirection());
                            toProductImageResultMapper.insert(toProductImageResult);
                            result.add(toProductImageResult);
                            i++;
                        }
                        // 走模型
                        pythonService.relightBatch(batchTaskId, paramList, userHolder.getId().toString());
                        // 添加需要扣除的积分到预扣除区
                        creditsService.addRecordToCreditsDeduction(userHolder.getId(), batchTaskId, CreditsEventsEnum.RELIGHT, cloudTaskDTO.getNums());
                        // 预插入数据到积分变更表
                        creditsService.preInsert(userHolder.getId(), CreditsEventsEnum.RELIGHT.getName(), batchTaskId, true, null, cloudTaskDTO.getNums());

                    }

                } else {
                    ToProductElement toProductElement = toProductElementMapper.selectById(toProductImageVO.getElementId());
                    // 走模型
                    List<BatchParamDTO> paramList = new ArrayList<>();
                    List<String> promptList = pythonService.getPrompt(s, toProductImageVOIntegerMap.get(key));
                    for (int i1 = 0; i1 < toProductImageVOIntegerMap.get(key); i1++) {
                        BatchParamDTO batchParamDTO = new BatchParamDTO();
                        taskId = UUID.randomUUID() + "-" + i + "-" + userHolder.getId();
                        batchParamDTO.setTasks_id(taskId);
                        batchParamDTO.setPrompt(promptList.get(i1));
                        batchParamDTO.setImage_url(toProductElement.getUrl());
                        batchParamDTO.setProduct_type("overall");
                        batchParamDTO.setDirection(toProductImageDTO.getDirection());
                        paramList.add(batchParamDTO);

                        ToProductImageResult toProductImageResult = new ToProductImageResult();
                        toProductImageResult.setElementId(toProductElement.getId());
                        toProductImageResult.setElementType("ProductElement");
                        toProductImageResult.setCreateTime(LocalDateTime.now());
                        toProductImageResult.setToProductImageRecordId(toProductImageRecord.getId());
                        toProductImageResult.setIsLike(0);
                        toProductImageResult.setTaskId(taskId);
                        toProductImageResult.setResultType("Relight");
                        toProductImageResult.setProjectId(projectId);
                        toProductImageResult.setTaskIdBatch(batchTaskId);
                        if (null != userLikeGroupId) {
                            toProductImageResult.setUserLikeGroupId(userLikeGroupId);
                        }
                        if (toProductImageDTO.getBrightenValue() != null) {
                            toProductImageResult.setBrightenValue(toProductImageDTO.getBrightenValue());
                        }
                        toProductImageResult.setDirection(toProductImageDTO.getDirection());
                        toProductImageResultMapper.insert(toProductImageResult);
                        result.add(toProductImageResult);
                        i++;
                    }
                    // 走模型
                    pythonService.relightBatch(batchTaskId, paramList, userHolder.getId().toString());
                    // 添加需要扣除的积分到预扣除区
                    creditsService.addRecordToCreditsDeduction(userHolder.getId(), batchTaskId, CreditsEventsEnum.RELIGHT, cloudTaskDTO.getNums());
                    // 预插入数据到积分变更表
                    creditsService.preInsert(userHolder.getId(), CreditsEventsEnum.RELIGHT.getName(), batchTaskId, true, null, cloudTaskDTO.getNums());
                }
            }
            return batchTaskId;
        } else if (cloudTaskDTO.getBuildType().equals(BuildType.POSE_TRANSFORM.getValue())) {

            Boolean preDeduction = creditsService.creditsPreDeduction(CreditsEventsEnum.POSE_TRANSFORMATION, cloudTaskDTO.getNums());
            if (!preDeduction) {
                throw new BusinessException("remaining.credits.insufficient", ResultEnum.WARNING.getCode());
            }

            Long projectId = cloudTaskDTO.getProjectId();
            AuthPrincipalVo userHolder = UserContext.getUserHolder();
            if (Objects.isNull(projectId)) {
                Project project = new Project();
                project.setName(DesignProcess.POSE_TRANSFER.getValue() + "_" + cloudTaskDTO.getName());
                project.setProcess(DesignProcess.POSE_TRANSFER.name());
                project.setOriginal(1);
                project.setAccountId(userHolder.getId());
                LocalDateTime now = LocalDateTime.now();
                project.setCreateTime(now);
                project.setUpdateTime(now);
                projectService.save(project);
                projectId = project.getId();
                for (ToProductImageVO toProductImageVO : cloudTaskDTO.getToProductImage().getToProductImageVOList()) {
                    if (toProductImageVO.getElementType().equals("ProductElement")) {
                        ToProductElement toProductElement = toProductElementMapper.selectById(toProductImageVO.getElementId());
                        toProductElement.setProjectId(projectId);
                        toProductElementMapper.updateById(toProductElement);
                    }
                }
            }
            Long accountId = UserContext.getUserHolder().getId();
            String taskBatchId = UUID.randomUUID() + "-" + accountId;

            CloudTask cloudTask = CopyUtil.copyObject(cloudTaskDTO, CloudTask.class);
            cloudTask.setProjectId(cloudTask.getProjectId());
            cloudTask.setTaskId(taskBatchId);
            LocalDateTime now = LocalDateTime.now();
            cloudTask.setProjectId(projectId);
            cloudTask.setCreateTime(now);
            cloudTask.setUpdateTime(now);
            cloudTask.setStatus(0);
            cloudTask.setAccountId(accountId);
            cloudTaskMapper.insert(cloudTask);
            // 解除锁后可以获取下一个序号
            projectService.clearLockedSequence(userHolder.getId());

            List<PoseTransformBatchDTO> poseTransformList = cloudTaskDTO.getPoseTransform();
            if (CollectionUtil.isNotEmpty(poseTransformList)) {
                for (PoseTransformBatchDTO poseTransformBatchDTO : poseTransformList) {
                    // 1、判断用户当前积分是否够本次生成消耗
                    CreditsEventsEnum creditsEventsEnum = CreditsEventsEnum.POSE_TRANSFORMATION;

                    // 3、生成唯一id 使用uuid,由于uuid重复的几率很小，故取消对uuid重复性的校验
                    String uuid = UUID.randomUUID().toString();
                    String taskId = uuid + "-" + accountId;

                    PoseTransformation poseTransformation = new PoseTransformation();
                    poseTransformation.setProjectId(projectId);
                    poseTransformation.setAccountId(accountId);
                    poseTransformation.setUniqueId(taskId);
                    poseTransformation.setProductImage(poseTransformBatchDTO.getProductImage());
                    poseTransformation.setPoseId(poseTransformBatchDTO.getPoseId());
                    poseTransformation.setCreateTime(LocalDateTime.now());
                    poseTransformation.setTaskIdBatch(taskBatchId);
                    poseTransformationMapper.insert(poseTransformation);

                    Boolean b = pythonService.poseTransformationBatch(poseTransformBatchDTO.getProductImage(), poseTransformBatchDTO.getPoseId(), taskId);
                    if (b) {
                        // 6、添加预扣除积分到redis
                        creditsService.addRecordToCreditsDeduction(accountId, taskBatchId, creditsEventsEnum, cloudTaskDTO.getNums());
                        // 6.1 添加积分扣除记录到db
                        creditsService.preInsert(accountId, creditsEventsEnum.getName(), taskBatchId, Boolean.TRUE, null, cloudTaskDTO.getNums());
                    } else {
                        throw new BusinessException("pose transformation error", ResultEnum.ERROR.getCode());
                    }
                }
                return taskBatchId;
            }
        }
        return null;
    }

    public static Map<String, Integer> allocateElements(List<ToProductImageVO> voList, int totalResults) {

        // 计算基础分配值和余数
        int baseAllocation = totalResults / voList.size();
        int remainder = totalResults % voList.size();

        // 初始化分配结果（每个元素先分配基础值）
        Map<String, Integer> allocationMap = new HashMap<>();
        for (ToProductImageVO vo : voList) {
            String key = vo.getElementId() + "_" + vo.getElementType();
            allocationMap.put(key, baseAllocation);
        }

        // 如果有余数，随机分配额外的一个结果
        if (remainder > 0) {
            // 创建元素ID的可变副本并打乱顺序
            List<ToProductImageVO> shuffledIds = new ArrayList<>(voList);
            Collections.shuffle(shuffledIds);

            // 将前N个元素各增加1（N=余数）
            for (int i = 0; i < remainder; i++) {
                ToProductImageVO toProductImageVO = shuffledIds.get(i);
                String key = toProductImageVO.getElementId() + "_" + toProductImageVO.getElementType();
                allocationMap.put(key, allocationMap.get(key) + 1);
            }
        }

        return allocationMap;
    }

    private DesignCollectionDTO transDesignParam(Long projectId) {
        DesignCollectionDTO designCollectionDTO = new DesignCollectionDTO();
        List<CollectionElement> collectionElementList = collectionElementService.getByProjectId(projectId);
        if (CollectionUtil.isNotEmpty(collectionElementList)) {
            Map<String, List<CollectionElement>> groupedMap = collectionElementList.stream().collect(Collectors.groupingBy(CollectionElement::getLevel1Type));
            if (CollectionUtil.isNotEmpty(groupedMap.get("Moodboard"))) {
                List<DesignCollectionElementDTO> moodBoards = new ArrayList<>();
                List<CollectionElement> moodboardList = groupedMap.get("Moodboard");
                for (CollectionElement collectionElement : moodboardList) {
                    if (collectionElement.getIsCompositeImage() != null && collectionElement.getIsCompositeImage() == 1) {
                        designCollectionDTO.setMoodTemplateId(String.valueOf(collectionElement.getId()));
                        designCollectionDTO.setMoodboardPosition(collectionService.getMoodboardPositionString(collectionElement.getId()));
                    } else {
                        DesignCollectionElementDTO dto = new DesignCollectionElementDTO();
                        dto.setId(collectionElement.getId());
                        dto.setDesignType(DesignTypeEnum.COLLECTION.getRealName());
                        moodBoards.add(dto);
                    }
                }
                designCollectionDTO.setMoodBoards(moodBoards);
            } else {
                designCollectionDTO.setMoodBoards(new ArrayList<>());
            }
            if (CollectionUtil.isNotEmpty(groupedMap.get("Printboard"))) {
                List<DesignCollectionPrintElementDTO> printBoards = new ArrayList<>();
                List<CollectionElement> printBoardList = groupedMap.get("Printboard");
                for (CollectionElement collectionElement : printBoardList) {
                    DesignCollectionPrintElementDTO dto = new DesignCollectionPrintElementDTO();
                    dto.setId(collectionElement.getId());
                    dto.setDesignType(DesignTypeEnum.COLLECTION.getRealName());
                    printBoards.add(dto);
                }
                designCollectionDTO.setPrintBoards(printBoards);
            } else {
                designCollectionDTO.setPrintBoards(new ArrayList<>());
            }
            if (CollectionUtil.isNotEmpty(groupedMap.get("Colorboard"))) {
                List<CollectionColorDTO> colorBoards = new ArrayList<>();
                List<CollectionElement> colorBoardList = groupedMap.get("Colorboard");
                for (CollectionElement collectionElement : colorBoardList) {
                    CollectionColorDTO dto = new CollectionColorDTO();
                    String name = collectionElement.getName();
                    if (name.contains("_")) {
                        String[] split = name.split("_");
                        dto.setId(Integer.valueOf(split[0]));
                        dto.setName(split[1]);
                        dto.setTcx(split[2]);
                    }
                    dto.setRgbValue(collectionElement.getColorRgb());
                    if (collectionElement.getGradientString() != null && !collectionElement.getGradientString().equals("null")) {
                        dto.setGradientString(collectionElement.getGradientString());
                    }
                    colorBoards.add(dto);
                }
                designCollectionDTO.setColorBoards(colorBoards);
            } else {
                designCollectionDTO.setColorBoards(new ArrayList<>());
            }
            if (CollectionUtil.isNotEmpty(groupedMap.get("Sketchboard"))) {
                List<CollectionSketchDTO> sketchBoards = new ArrayList<>();
                List<CollectionElement> sketchBoardList = groupedMap.get("Sketchboard");
                for (CollectionElement collectionElement : sketchBoardList) {
                    CollectionSketchDTO dto = new CollectionSketchDTO();
                    dto.setSketchBoardId(collectionElement.getId());
                    dto.setDesignType(DesignTypeEnum.COLLECTION.getRealName());
                    dto.setLevel2Type(collectionElement.getLevel2Type());
                    dto.setIsPin(collectionElement.getHasPin());
                    sketchBoards.add(dto);
                }
                designCollectionDTO.setSketchBoards(sketchBoards);
            } else {
                designCollectionDTO.setSketchBoards(new ArrayList<>());
            }
            if (CollectionUtil.isNotEmpty(groupedMap.get("Models"))) {
                List<MannequinDTO> mannequins = new ArrayList<>();
                List<CollectionElement> modelList = groupedMap.get("Models");
                for (CollectionElement collectionElement : modelList) {
                    MannequinDTO dto = new MannequinDTO();
                    QueryWrapper<CollectionElementRelModel> qw = new QueryWrapper<>();
                    qw.lambda().eq(CollectionElementRelModel::getCollectionElementId, collectionElement.getId());
                    List<CollectionElementRelModel> collectionElementRelModels = collectionElementRelModelMapper.selectList(qw);
                    if (!CollectionUtils.isEmpty(collectionElementRelModels)) {
                        CollectionElementRelModel relModel = collectionElementRelModels.get(0);
                        dto.setId(relModel.getRelationId());
                        dto.setType(relModel.getRelationType());
                    }
                }

            } else {
                designCollectionDTO.setMannequins(new ArrayList<>());
            }
        } else {
            designCollectionDTO.setMoodBoards(new ArrayList<>());
            designCollectionDTO.setPrintBoards(new ArrayList<>());
            designCollectionDTO.setColorBoards(new ArrayList<>());
            designCollectionDTO.setSketchBoards(new ArrayList<>());
            designCollectionDTO.setMannequins(new ArrayList<>());
        }
        Long workspaceId = workspaceService.getByProjectId(projectId);
        Workspace workspace = workspaceService.getById(workspaceId);
        designCollectionDTO.setSystemScale(
                BigDecimal.valueOf(workspace.getSystemDesignerPercentage())
                        .divide(BigDecimal.valueOf(100), 4, RoundingMode.HALF_UP)
        );
        designCollectionDTO.setModelSex(workspace.getSex());
        if (workspace.getSex().equals("Female")) {
            designCollectionDTO.setTemplateId(workspace.getMannequinFemaleId());
            designCollectionDTO.setModelType(workspace.getMannequinFemaleType());
        }
        if (workspace.getPosition().equals("Overall")) {
            designCollectionDTO.setSingleOverall("overall");
        } else {
            designCollectionDTO.setSingleOverall("single");
            designCollectionDTO.setSwitchCategory(workspace.getPosition());
        }
        designCollectionDTO.setTimeZone("Etc/GMT-8");
        return designCollectionDTO;
    }

    private String designBatch(DesignCollectionDTO designDTO, AuthPrincipalVo userInfo, Long collectionIdParam, ValidateElementVO elementVO, CloudTaskDTO cloudTaskDTO, Long projectId) {
        AuthPrincipalVo userHolder = UserContext.getUserHolder();
        //保存collection
        Long collectionId;
        if (null == collectionIdParam) {
            collectionId = collectionService.saveCollection(userInfo.getId(), designDTO.getTimeZone(), designDTO.getMoodTemplateId(), designDTO.getMoodboardPosition());
        } else {
            collectionId = collectionIdParam;
        }
        List<Long> elementIds = getElementId(elementVO);
        //批量关联element 到 collection
        collectionElementService.relationCollection(elementIds, collectionId);
        //保存design
        Long designId = saveOne(designDTO, collectionId, userInfo.getId());
        String requestId = UUID.randomUUID().toString() + "_" + userInfo.getId();

        CloudTask cloudTask = CopyUtil.copyObject(cloudTaskDTO, CloudTask.class);
        cloudTask.setProjectId(projectId);
        cloudTask.setDesignId(designId);
        cloudTask.setCollectionId(collectionId);
        cloudTask.setTaskId(requestId);
        LocalDateTime now = LocalDateTime.now();
        cloudTask.setCreateTime(now);
        cloudTask.setUpdateTime(now);
        cloudTask.setStatus(0);
        cloudTask.setAccountId(userInfo.getId());
        cloudTaskMapper.insert(cloudTask);
        // 解除锁后可以获取下一个序号
        projectService.clearLockedSequence(userHolder.getId());

        //组装design入参
        long startTime = System.currentTimeMillis();
        DesignPythonObjects pythonObjects = pythonService.covertDesignParam(designDTO.getSystemScale(),
                designDTO.getSingleOverall(), designDTO.getSwitchCategory(), elementVO, designDTO.getProcessId(), collectionId);
        long endTime = System.currentTimeMillis();
        long totalTimeInSeconds = (endTime - startTime) / 1000;
        log.info("组装入参运行时间：" + totalTimeInSeconds + " 秒");
        // pythonObjects增加image_id关联
        startTime = System.currentTimeMillis();
        List<Long> imageIds = relationImageIds(pythonObjects);
        endTime = System.currentTimeMillis();
        totalTimeInSeconds = (endTime - startTime) / 1000;
        log.info("增加image_id关联运行时间：" + totalTimeInSeconds + " 秒");
        //design
        startTime = System.currentTimeMillis();
        pythonObjects.setRequestId(requestId);
        String taskId = pythonService.designBatch(pythonObjects, userHolder.getId(), elementVO.getDesignNum(), requestId);

        endTime = System.currentTimeMillis();
        totalTimeInSeconds = (endTime - startTime) / 1000;
        log.info("design python端运行时间：" + totalTimeInSeconds + " 秒");
        //生成library
        startTime = System.currentTimeMillis();
        String ageGroup = workspaceService.getAgeGroupByProjectOrCollectionId(designDTO.getProjectId(), collectionId);
        generateLibrary(elementVO, designDTO.getTimeZone(), ageGroup);
        //处理关联关系,修复element覆盖得情况
//        List<CollectionElement> relationElements = collectionElementService.getByOnlyCollectionId(collectionId);
//        List<Long> relationElementIds = relationElements.stream().map(CollectionElement::getId).collect(Collectors.toList());
//        handleCollectionElementRelation(collectionId, null != collectionIdParam, relationElementIds);
        endTime = System.currentTimeMillis();
        totalTimeInSeconds = (endTime - startTime) / 1000;
        log.info("处理关联关系运行时间：" + totalTimeInSeconds + " 秒");


        Map<String, Object> context = new HashMap<>();
        context.put("pythonObjects", pythonObjects); // 转换后的 Python 请求参数
        context.put("designId", designId);           // 设计 ID
        context.put("collectionId", collectionId);   // 集合 ID
        context.put("userInfo", userInfo);           // 用户信息
        context.put("timeZone", designDTO.getTimeZone()); // 时区
        context.put("singleOverall", designDTO.getSingleOverall()); // 其他设计参数
        context.put("requestIdList", elementVO.getRequestIdList());

        // 将上下文存入全局设计上下文中
        designContext.put(taskId, context);
        return taskId;
    }

    @Override
    @Transactional
    public void processDesignBatch(Map<String, Object> designBatchResult) {
        Object progress = designBatchResult.get("progress");
        if (progress instanceof String) {
            String taskId = (String) designBatchResult.get("task_id");
            QueryWrapper<CloudTask> qw = new QueryWrapper<>();
            qw.lambda().eq(CloudTask::getTaskId, taskId);
            List<CloudTask> cloudTaskList = cloudTaskMapper.selectList(qw);
            if (((String) progress).startsWith("0/")) {
                if (CollectionUtil.isNotEmpty(cloudTaskList) && Objects.isNull(cloudTaskList.get(0).getStartTime())) {
                    CloudTask cloudTask = cloudTaskList.get(0);
                    cloudTask.setStartTime(LocalDateTime.now());
                    cloudTask.setUpdateTime(LocalDateTime.now());
                    cloudTaskMapper.updateById(cloudTask);
                }
                return;
            }
            if (progress.equals("ok")) {
                if (CollectionUtil.isNotEmpty(cloudTaskList)) {
                    CloudTask cloudTask = cloudTaskList.get(0);
                    cloudTask.setCompletedNum(cloudTask.getNums());
                    cloudTask.setStatus(1);
                    cloudTaskMapper.updateById(cloudTask);
                }
            }
        } else {
            String taskId = (String) designBatchResult.get("task_id");
//            QueryWrapper<CloudTask> qw = new QueryWrapper<>();
//            qw.lambda().eq(CloudTask::getTaskId, taskId);
//            List<CloudTask> cloudTaskList = cloudTaskMapper.selectList(qw);
//            if (CollectionUtil.isNotEmpty(cloudTaskList)) {
//                CloudTask cloudTask = cloudTaskList.get(0);
//                if (cloudTask.getCompletedNum() == null) {
//                    cloudTask.setCompletedNum(1);
//                }else {
//                    cloudTask.setCompletedNum(cloudTask.getCompletedNum() + 1);
//                }
//                cloudTaskMapper.updateById(cloudTask);
//            }
            cloudTaskMapper.increaseCompletedNum(taskId);

            Integer i = (Integer) progress;
            Map<String, Object> context;
            synchronized (designContext) {
                context = designContext.get(taskId);
                if (context == null) {
                    log.error("上下文数据缺失，无法完成操作");
                    return;
                }

                DesignPythonObjects pythonObjects = (DesignPythonObjects) context.get("pythonObjects");
                Long designId = (Long) context.get("designId");
                Long collectionId = (Long) context.get("collectionId");
                AuthPrincipalVo userInfo = (AuthPrincipalVo) context.get("userInfo");
                String timeZone = (String) context.get("timeZone");
                String singleOverall = (String) context.get("singleOverall");

                DesignPythonObject item = pythonObjects.getObjects().get(i - 1);
                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 = (JSONObject) designBatchResult.get("result");
                if (null == outfit) {
                    return;
                }
                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<TDesignPythonOutfitDetail> 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<DesignItemDetail> designItemDetails = Lists.newArrayList();
                Map<String, Integer> typePriority = list.stream().collect(Collectors.toMap(d -> d.getImageCategory().split("_")[0],
                        d -> Math.abs(d.getPriority()),
                        (existing, replacement) -> replacement));
                Map<String, String> 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));
                    if (!detail.getType().equals("Body")) {
                        designItemDetail.setUndividedLayer(typeAndUndividedLayer.get(designItemDetail.getType()));
                    }
                    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(Arrays.toString(new Float[]{0.3f, 0.3f}));
                        print.setAngle(0.0);
                        print.setPriority(1);
                        QueryWrapper<CollectionElement> 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);
                    }
                }
            }
        }

    }

    @Override
    public Boolean sort(CollectionSortDTO userLikeSortDTO) {
        return collectionSortService.sort(userLikeSortDTO);
    }

    @Override
    public IPage<CloudTaskVO> cloudPage(CloudPageDTO cloudPageDTO) {
        // 分页数据
//        Set<Long> childProjectIdSet = projectService.getChildProjectIdSet(cloudPageDTO.getProjectId());
//        childProjectIdSet.add(cloudPageDTO.getProjectId());
        QueryWrapper<CloudTask> queryWrapper = new QueryWrapper<>();
        AuthPrincipalVo userHolder = UserContext.getUserHolder();
        queryWrapper.lambda().eq(CloudTask::getAccountId, userHolder.getId());
        if (null != cloudPageDTO.getProjectId()) {
            queryWrapper.lambda().eq(CloudTask::getProjectId, cloudPageDTO.getProjectId());
        }
        queryWrapper.lambda().orderByDesc(CloudTask::getUpdateTime);
        IPage<CloudTask> page = cloudTaskMapper.selectPage(
                new Page<>(cloudPageDTO.getPage(), cloudPageDTO.getSize()), queryWrapper);
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return new Page<>();
        }

        IPage<CloudTaskVO> convert = page.convert((Function<CloudTask, CloudTaskVO>) cloudTask -> {
            if (cloudTask != null) {
                CloudTaskVO cloudTaskVO = CopyUtil.copyObject(cloudTask, CloudTaskVO.class);
                if (cloudTaskVO.getCompletedNum() == null) {
                    cloudTaskVO.setProcess("0%");
                } else {
                    BigDecimal completed = BigDecimal.valueOf(cloudTaskVO.getCompletedNum());
                    BigDecimal total = BigDecimal.valueOf(cloudTaskVO.getNums());

                    BigDecimal percent = completed
                            .divide(total, 4, RoundingMode.HALF_UP)  // 先计算小数百分比，保留4位防止精度问题
                            .multiply(BigDecimal.valueOf(100))       // 乘以100变成百分比
                            .setScale(2, RoundingMode.HALF_UP);      // 最终保留2位小数
                    String percentage = percent.compareTo(new BigDecimal("100")) > 0 ? "100.00" : percent.toPlainString();
                    cloudTaskVO.setProcess(percentage + "%");
                }
                return cloudTaskVO;
            }
            return null;
        });
        return convert;
    }

    @Value("${redis.key.toProductImageResultKey}")
    private String toProductImageResultKey;
    @Value("${redis.key.relightResultKey}")
    private String relightResultKey;

    @Override
    public CloudTaskResultVO getDesignCloudResult(DesignCloudResultQuery query) {
        CloudTaskResultVO result = new CloudTaskResultVO();
        if (query.getBuildType().equals(BuildType.DESIGN.getValue())) {
            CloudTask cloudTask = cloudTaskService.getByTaskId(query.getTaskId());
            if (Objects.nonNull(cloudTask)) {
                Long collectionId = cloudTask.getCollectionId();
                if (null != collectionId) {
                    QueryWrapper<TDesignPythonOutfit> qw = new QueryWrapper<>();
                    qw.lambda().eq(TDesignPythonOutfit::getCollectionId, collectionId);
                    List<TDesignPythonOutfit> list = designPythonOutfitMapper.selectList(qw);
                    List<DesignCollectionItemVO> voList = new ArrayList<>();
                    for (TDesignPythonOutfit tDesignPythonOutfit : list) {
                        DesignCollectionItemVO vo = new DesignCollectionItemVO();
                        vo.setDesignOutfitId(tDesignPythonOutfit.getId());
                        vo.setDesignOutfitUrl(minioUtil.getPreSignedUrl(tDesignPythonOutfit.getDesignUrl(), 24 * 60));
                        vo.setDesignItemId(tDesignPythonOutfit.getDesignItemId());
                        vo.setResultType(CollectionType.DESIGN.getValue());
                        voList.add(vo);
                    }
                    result.setDesign(voList);
//                    IPage<DesignCollectionItemVO> convert = page.convert((Function<TDesignPythonOutfit, DesignCollectionItemVO>) outfit -> {
//                        if (outfit != null) {
//                            DesignCollectionItemVO vo = new DesignCollectionItemVO();
//                            vo.setDesignOutfitId(outfit.getId());
//                            vo.setDesignOutfitUrl(minioUtil.getPreSignedUrl(outfit.getDesignUrl(), 24 * 60));
//                            vo.setDesignItemId(outfit.getDesignItemId());
//                            return vo;
//                        }
//                        return null;
//                    });
//                    result.setDesign(PageBaseResponse.success(convert));
                    return result;
                } else {
                    result.setDesign(new ArrayList<>());
                    return result;
                }
            }
            result.setDesign(new ArrayList<>());
            return result;
        } else if (query.getBuildType().equals(BuildType.TO_PRODUCT_IMAGE.getValue())) {
            List<MagicToolResultVO> results = new ArrayList<>();
            QueryWrapper<ToProductImageResult> toProductImageResultQueryWrapper = new QueryWrapper<>();
            toProductImageResultQueryWrapper.lambda().eq(ToProductImageResult::getTaskIdBatch, query.getTaskId());
            List<ToProductImageResult> toProductImageResultList = toProductImageResultMapper.selectList(toProductImageResultQueryWrapper);
            for (ToProductImageResult toProductImageResult : toProductImageResultList) {
                if (StringUtil.isNullOrEmpty(toProductImageResult.getUrl())) continue;
                MagicToolResultVO magicToolResultVO = new MagicToolResultVO();
                magicToolResultVO.setId(toProductImageResult.getId());
                magicToolResultVO.setTaskId(toProductImageResult.getTaskId());
                magicToolResultVO.setStatus("Success");
                magicToolResultVO.setUrl(minioUtil.getPreSignedUrl(toProductImageResult.getUrl(), CommonConstant.MINIO_IMAGE_EXPIRE_TIME));
                magicToolResultVO.setResultType(toProductImageResult.getResultType());
                magicToolResultVO.setElementId(toProductImageResult.getElementId());
                magicToolResultVO.setElementType(toProductImageResult.getElementType());
                if (toProductImageResult.getElementType().equals("ProductElement")) {
                    ToProductElement toProductElement = toProductElementMapper.selectById(toProductImageResult.getElementId());
                    magicToolResultVO.setSourceUrl(minioUtil.getPreSignedUrl(toProductElement.getUrl(), 24 * 60));
                } else {
                    TDesignPythonOutfit tDesignPythonOutfit = designPythonOutfitMapper.selectById(toProductImageResult.getElementId());
                    magicToolResultVO.setSourceUrl(minioUtil.getPreSignedUrl(tDesignPythonOutfit.getDesignUrl(), 24 * 60));
                }
                results.add(magicToolResultVO);
            }
            result.setToProductImage(results);
            return result;
        } else if (query.getBuildType().equals(BuildType.RELIGHT.getValue())) {
            List<MagicToolResultVO> results = new ArrayList<>();
            QueryWrapper<ToProductImageResult> toProductImageResultQueryWrapper = new QueryWrapper<>();
            toProductImageResultQueryWrapper.lambda().eq(ToProductImageResult::getTaskIdBatch, query.getTaskId());
            List<ToProductImageResult> toProductImageResultList = toProductImageResultMapper.selectList(toProductImageResultQueryWrapper);
            for (ToProductImageResult toProductImageResult : toProductImageResultList) {
                if (StringUtil.isNullOrEmpty(toProductImageResult.getUrl())) continue;
                MagicToolResultVO magicToolResultVO = new MagicToolResultVO();
                magicToolResultVO.setId(toProductImageResult.getId());
                magicToolResultVO.setTaskId(toProductImageResult.getTaskId());
                magicToolResultVO.setStatus("Success");
                magicToolResultVO.setUrl(minioUtil.getPreSignedUrl(toProductImageResult.getUrl(), CommonConstant.MINIO_IMAGE_EXPIRE_TIME));
                magicToolResultVO.setResultType(toProductImageResult.getResultType());
                magicToolResultVO.setElementId(toProductImageResult.getElementId());
                magicToolResultVO.setElementType(toProductImageResult.getElementType());
                if (toProductImageResult.getElementType().equals("ProductElement")) {
                    ToProductElement toProductElement = toProductElementMapper.selectById(toProductImageResult.getElementId());
                    magicToolResultVO.setSourceUrl(minioUtil.getPreSignedUrl(toProductElement.getUrl(), 24 * 60));
                } else {
                    ToProductImageResult toProductImageResult1 = toProductImageResultMapper.selectById(toProductImageResult.getElementId());
                    magicToolResultVO.setSourceUrl(minioUtil.getPreSignedUrl(toProductImageResult1.getUrl(), 24 * 60));
                }
                results.add(magicToolResultVO);
            }
            result.setRelight(results);
            return result;
        } else if (query.getBuildType().equals(BuildType.POSE_TRANSFORM.getValue())) {
            String taskId = query.getTaskId();
            QueryWrapper<PoseTransformation> poseTransformationQueryWrapper = new QueryWrapper<>();
            poseTransformationQueryWrapper.lambda().eq(PoseTransformation::getTaskIdBatch, taskId);
            List<PoseTransformation> poseTransformationList = poseTransformationMapper.selectList(poseTransformationQueryWrapper);
            List<PoseTransformationVO> voList = new ArrayList<>();
            for (PoseTransformation poseTransformation : poseTransformationList) {
                PoseTransformationVO poseTransformationVO = new PoseTransformationVO();
                poseTransformationVO.setId(poseTransformation.getId());
                poseTransformationVO.setIsLiked(poseTransformation.getIsLiked());
                poseTransformationVO.setStatus("Success");
                poseTransformationVO.setTaskId(poseTransformation.getUniqueId());
                poseTransformationVO.setProductImage(minioUtil.getPreSignedUrl(poseTransformation.getProductImage(), CommonConstant.MINIO_IMAGE_EXPIRE_TIME));
                if (null != poseTransformation.getGifUrl()) {
                    poseTransformationVO.setGifUrl(minioUtil.getPreSignedUrl(poseTransformation.getGifUrl(), CommonConstant.MINIO_IMAGE_EXPIRE_TIME));
                }
                if (null != poseTransformation.getVideoUrl()) {
                    poseTransformationVO.setVideoUrl(minioUtil.getPreSignedUrl(poseTransformation.getVideoUrl(), CommonConstant.MINIO_IMAGE_EXPIRE_TIME));
                }
                if (null != poseTransformation.getFirstFrameUrl()) {
                    poseTransformationVO.setFirstFrameUrl(minioUtil.getPreSignedUrl(poseTransformation.getFirstFrameUrl(), CommonConstant.MINIO_IMAGE_EXPIRE_TIME));
                }
                voList.add(poseTransformationVO);
            }
            result.setPoseTransfer(voList);
            return result;
        }
        return result;
    }

    @Override
    public Boolean receiveDesignParams(ReceiveDesignParam receiveDesignParam) {
        List<ReceiveCollectionElement> receiveCollectionElementList = receiveDesignParam.getReceiveCollectionElementList();
        if (!CollectionUtils.isEmpty(receiveCollectionElementList)) {
            Project project = projectService.getById(receiveDesignParam.getProjectId());
//            Project project = projectService.getById(1750L);
            List<CollectionElement> collectionElementList = new ArrayList<>();
            Date date = new Date();
            for (ReceiveCollectionElement receiveCollectionElement : receiveCollectionElementList) {
                CollectionElement collectionElement = new CollectionElement();
                if (receiveCollectionElement.getLevel1Type().equals(CollectionLevel1TypeEnum.PRINT_BOARD.getRealName())) {
                    String url = receiveCollectionElement.getUrl();
                    String[] split = url.split("/");
                    String pictureName = split[split.length - 1];
                    String[] split1 = pictureName.split("\\.");
                    collectionElement.setLevel1Type(receiveCollectionElement.getLevel1Type());
                    collectionElement.setAccountId(project.getAccountId());
                    collectionElement.setProjectId(project.getId());
                    collectionElement.setLevel2Type(receiveCollectionElement.getLevel2Type());
                    collectionElement.setName(split1[0]);
                    collectionElement.setUrl(url);
                    collectionElement.setHasPin((byte) 0);
                    collectionElement.setCreateDate(date);
                } else if (receiveCollectionElement.getLevel1Type().equals(CollectionLevel1TypeEnum.MOOD_BOARD.getRealName())) {
                    String url = receiveCollectionElement.getUrl();
                    String[] split = url.split("/");
                    String pictureName = split[split.length - 1];
                    String[] split1 = pictureName.split("\\.");
                    collectionElement.setLevel1Type(receiveCollectionElement.getLevel1Type());
                    collectionElement.setAccountId(project.getAccountId());
                    collectionElement.setProjectId(project.getId());
                    collectionElement.setName(split1[0]);
                    collectionElement.setUrl(url);
                    collectionElement.setHasPin((byte) 0);
                    collectionElement.setCreateDate(date);
                } else if (receiveCollectionElement.getLevel1Type().equals(CollectionLevel1TypeEnum.SKETCH_BOARD.getRealName())) {
                    String url = receiveCollectionElement.getUrl();
                    String[] split = url.split("/");
                    String pictureName = split[split.length - 1];
                    String[] split1 = pictureName.split("\\.");
                    collectionElement.setLevel1Type(receiveCollectionElement.getLevel1Type());
                    collectionElement.setAccountId(project.getAccountId());
                    collectionElement.setProjectId(project.getId());
                    collectionElement.setLevel2Type(receiveCollectionElement.getLevel2Type());
                    collectionElement.setLevel3Type(workspaceService.getProjectSexById(project.getId()));
                    collectionElement.setName(split1[0]);
                    collectionElement.setUrl(url);
                    collectionElement.setHasPin((byte) 0);
                    collectionElement.setCreateDate(date);
                    libraryService.processSketchBoards(url, collectionElement.getLevel2Type());
                } else if (receiveCollectionElement.getLevel1Type().equals(CollectionLevel1TypeEnum.COLOR_BOARD.getRealName())) {
                    /*String color = receiveCollectionElement.getHsv();
                    String[] parts = color.split("\\s+");
                    int h = Math.round(Float.parseFloat(parts[0]));
                    int s = Math.round(Float.parseFloat(parts[1])); // 关键修改
                    int v = Math.round(Float.parseFloat(parts[2]));
                    int[] hsv = {h, s, v};*/
                    String rgbStr = receiveCollectionElement.getRgb();
                    int[] rgb = Arrays.stream(rgbStr.split("\\s+"))
                            .mapToInt(Integer::parseInt)
                            .toArray();
                    int[] hsv = PantoneUtils.rgbToHsv(rgb);
//                    int[] hsv = Arrays.stream(color.split("\\s+")).mapToInt(Integer::parseInt).toArray();
                    int value = (hsv[0] * 101 * 101) + (hsv[1] * 101) + hsv[2];
                    ColorLookupTable colorLookupTable = colorLoopUpTableService.getByColorValue(value);
                    if (Objects.isNull(colorLookupTable)) {
                        throw new BusinessException("Unknown pantone.");
                    }
                    QueryWrapper<PanTone> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("pantone_index", colorLookupTable.getColorIndex());
                    PanTone panTone = panToneMapper.selectOne(queryWrapper);

                    if (Objects.nonNull(panTone)) {
                        collectionElement.setLevel1Type(receiveCollectionElement.getLevel1Type());
                        collectionElement.setAccountId(project.getAccountId());
                        collectionElement.setProjectId(project.getId());
                        collectionElement.setName(panTone.getPantoneIndex() + "_" + panTone.getName() + "_" + panTone.getTcx());
                        collectionElement.setHasPin((byte) 0);
                        collectionElement.setColorRgb(rgbStr);
                        collectionElement.setCreateDate(date);
                    }
                }
                collectionElement.setMd5("0");
                collectionElementList.add(collectionElement);
            }

            collectionElementService.saveBatch(collectionElementList);
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean cloudTaskNameUpdate(CloudTaskDTO cloudTaskDTO) {
        cloudTaskMapper.updateById(cloudTaskDTO);
        return Boolean.TRUE;
    }

    @Override
    public Boolean cloudTaskDelete(CloudTaskDTO cloudTaskDTO) {
        cloudTaskMapper.deleteById(cloudTaskDTO.getId());
        return Boolean.TRUE;
    }

}