package com.microservices.pms.productLibrary.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.microservices.common.core.constant.SecurityConstants;
import com.microservices.common.core.exception.ServiceException;
import com.microservices.common.core.utils.DateUtils;
import com.microservices.common.core.utils.PageUtils;
import com.microservices.common.core.utils.StringUtils;
import com.microservices.common.core.utils.html.EscapeUtil;
import com.microservices.common.core.web.page.GenericsTableDataInfo;
import com.microservices.common.security.utils.SecurityUtils;
import com.microservices.pms.common.service.IPmsCommonService;
import com.microservices.pms.document.domain.vo.PmsDocumentDetailVo;
import com.microservices.pms.document.domain.vo.PmsDocumentVo;
import com.microservices.pms.document.service.IPmsDocumentService;
import com.microservices.pms.enterprise.domain.PmsEnterprise;
import com.microservices.pms.enterprise.service.IPmsEnterpriseService;
import com.microservices.pms.productLibrary.domain.PmsProductLibraryComponent;
import com.microservices.pms.productLibrary.domain.PmsProductLibraryRepositories;
import com.microservices.pms.productLibrary.domain.ProductLibraryRepositoriesFormatEnum;
import com.microservices.pms.productLibrary.domain.vo.*;
import com.microservices.pms.productLibrary.mapper.PmsProductLibraryComponentMapper;
import com.microservices.pms.productLibrary.mapper.PmsProductLibraryRepositoriesMapper;
import com.microservices.pms.productLibrary.service.IPmsProductLibraryAsyncService;
import com.microservices.pms.productLibrary.service.IPmsProductLibraryComponentService;
import com.microservices.pms.productLibrary.service.IPmsProductLibraryRepositoriesService;
import com.microservices.pms.productLibrary.service.IPmsProductLibraryService;
import com.microservices.pms.utils.NexusRequestHelper;
import com.microservices.pms.utils.NexusRequestUrl;
import com.microservices.pms.utils.PmsUtils;
import com.microservices.system.api.RemoteFileService;
import com.microservices.system.api.domain.SysFileBytes;
import com.microservices.system.api.domain.SysFileInfo;
import com.microservices.system.api.utils.FeignUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author OTTO
 */
@Service
public class PmsProductLibraryServiceImpl implements IPmsProductLibraryService {

    private static final Logger log = LoggerFactory.getLogger(PmsProductLibraryServiceImpl.class);
    @Autowired
    private PmsProductLibraryRepositoriesMapper pmsProductLibraryRepositoriesMapper;
    @Autowired
    private PmsProductLibraryComponentMapper pmsProductLibraryComponentMapper;
    @Autowired
    private NexusRequestHelper nexusRequestHelper;
    @Autowired
    private IPmsEnterpriseService pmsEnterpriseService;
    @Autowired
    private IPmsProductLibraryAsyncService pmsProductLibraryAsyncService;
    @Autowired
    @Lazy
    private IPmsProductLibraryComponentService pmsProductLibraryComponentService;
    @Autowired
    @Lazy
    private IPmsProductLibraryRepositoriesService pmsProductLibraryRepositoriesService;
    @Autowired
    private RemoteFileService remoteFileService;
    @Autowired
    private IPmsDocumentService pmsDocumentService;
    @Autowired
    private IPmsCommonService pmsCommonService;

    @Override
    public GenericsTableDataInfo<PmsProductLibraryComponentDataVo> selectComponentList(PmsProductLibraryComponentSearchVo search) {
        List<PmsProductLibraryComponent> pmsProductLibraryComponentList =
                pmsProductLibraryComponentMapper.selectProductRepoComponentList(search);
        List<Long> repoIdList = pmsProductLibraryComponentList.stream().map(PmsProductLibraryComponent::getRepoId).distinct().collect(Collectors.toList());
        List<PmsProductLibraryRepositories> repoList = repoIdList.stream().map(this::selectPmsProductLibraryRepositoriesById).collect(Collectors.toList());
        return PageUtils.toPage(pmsProductLibraryComponentList, x -> toPmsProductLibraryComponentDataVo(x, repoList));
    }

    private PmsProductLibraryRepositories selectPmsProductLibraryRepositoriesById(Long repoId) {
        PmsProductLibraryRepositories pmsProductLibraryRepositories =
                pmsProductLibraryRepositoriesMapper.selectProductRepoById(repoId);
        if (pmsProductLibraryRepositories == null) {
            throw new ServiceException("组织下不存在该产品库(产品库id[%d])", repoId);
        }
        return pmsProductLibraryRepositories;
    }

    private PmsProductLibraryComponentDataVo toPmsProductLibraryComponentDataVo(PmsProductLibraryComponent component, List<PmsProductLibraryRepositories> repoList) {
        PmsProductLibraryComponentDataVo pmsProductLibraryComponentDataVo = component.toPmsProductLibraryComponentDataVo();
        repoList.stream().filter(x -> x.getId().equals(component.getRepoId())).findFirst().ifPresent(repo -> pmsProductLibraryComponentDataVo.setDownloadUrl(
                EscapeUtil.removeExtraSlashOfUrl(
                        String.format("%s/%s", repo.getUrl(), component.getPath()))));
        pmsCommonService.setBaseEntityVo(pmsProductLibraryComponentDataVo, component);
        return pmsProductLibraryComponentDataVo;
    }

    @Override
    public PmsProductLibraryRepositoriesDataVo selectPmsProductLibraryDataByName(String enterpriseIdentifier, String repoName) {
        PmsProductLibraryRepositories pmsProductLibraryRepositories = selectPmsProductLibraryByName(enterpriseIdentifier, repoName);
        return pmsProductLibraryRepositories.toPmsProductLibraryRepositoriesDataVo();
    }


    @Override
    public PmsProductLibraryRepositories selectPmsProductLibraryByName(String enterpriseIdentifier, String name) {
        PmsProductLibraryRepositories pmsProductLibraryRepositories = pmsProductLibraryRepositoriesMapper.selectPmsProductLibraryByName(enterpriseIdentifier, name);
        if (pmsProductLibraryRepositories == null) {
            throw new ServiceException("组织下不存在该产品库(组织标识[%s],产品库标识[%s])", enterpriseIdentifier, name);
        }
        return pmsProductLibraryRepositories;
    }

    @Override
    public GenericsTableDataInfo<PmsProductLibrarySimpleVo> selectPmsProductLibraryPageList(String enterpriseIdentifier, String name) {
        return PageUtils.toPage(pmsProductLibraryRepositoriesMapper.selectPmsProductLibraryList(enterpriseIdentifier, name), this::toPmsProductLibrarySimpleVo);
    }

    private PmsProductLibrarySimpleVo toPmsProductLibrarySimpleVo(PmsProductLibraryRepositories pmsProductLibraryRepositories) {
        PmsProductLibrarySimpleVo pmsProductLibrarySimpleVo = pmsProductLibraryRepositories.toPmsProductLibrarySimpleVo();
        pmsCommonService.setBaseEntityVo(pmsProductLibrarySimpleVo, pmsProductLibraryRepositories);
        return pmsProductLibrarySimpleVo;
    }

    @Override
    public int updatePmsProductLibrary(ProductRepositoriesOperateVo productRepositoriesOperateVo) {
        PmsProductLibraryRepositories oldRepo = selectPmsProductLibraryByName(productRepositoriesOperateVo.getEnterpriseIdentifier(), productRepositoriesOperateVo.getName());

        // 校验制品库别名
        PmsProductLibraryRepositories aliasRepo = pmsProductLibraryRepositoriesMapper.selectPmsProductLibraryByAlias(productRepositoriesOperateVo.getAlias(), productRepositoriesOperateVo.getEnterpriseIdentifier());
        if (aliasRepo != null && !aliasRepo.getId().equals(oldRepo.getId())) {
            throw new ServiceException("该产品库名称在当前组织下已存在(产品库名称[%s])", productRepositoriesOperateVo.getAlias());
        }
        // 构建更新对象
        PmsProductLibraryRepositories pmsProductLibraryRepositories = productRepositoriesOperateVo.toPmsProductLibraryRepositories();
        pmsProductLibraryRepositories.setId(oldRepo.getId());
        NexusHostedRepoInputVo requestBody = productRepositoriesOperateVo.toNexusRepoDataVo();

        // 调用制品库更新接口更新制品库
        nexusRequestHelper.doRequest(NexusRequestUrl.UPDATE_REPOSITORIES(requestBody.getType(), requestBody.getFormat(), requestBody.getName()), JSONObject.from(requestBody));

        return updatePmsProductLibrary(pmsProductLibraryRepositories);
    }

    @Override
    public int updatePmsProductLibrary(PmsProductLibraryRepositories pmsProductLibraryRepositories) {
        pmsProductLibraryRepositories.setUpdateTime(DateUtils.getNowDate());
        pmsProductLibraryRepositories.setUpdateBy(SecurityUtils.getUsername());
        return pmsProductLibraryRepositoriesMapper.updatePmsProductLibraryRepositories(pmsProductLibraryRepositories);
    }

    @Override
    public ProductPackagedResultVo getPackagedProduct(String enterpriseIdentifier, String productRepoName) {
        ProductPackagedResultVo productPackagedResultVo = new ProductPackagedResultVo();
        PmsProductLibraryRepositories productLibraryRepositories = selectPmsProductLibraryByName(enterpriseIdentifier, productRepoName);
        String packagedFileIdentifier = productLibraryRepositories.getPackagedFileIdentifier();
        if (StringUtils.isEmpty(packagedFileIdentifier)) {
            productPackagedResultVo.setIsPackaged(false);
        } else {
            productPackagedResultVo.setIsPackaged(true);
            try {
                SysFileInfo sysFileInfo = FeignUtils.getReturnData(
                        remoteFileService.getFileByFileIdentifier(packagedFileIdentifier, SecurityConstants.INNER)
                );
                if (sysFileInfo != null) {
                    productPackagedResultVo.setDownloadUrl(sysFileInfo.getDownloadUrl());
                    productPackagedResultVo.setFileName(sysFileInfo.getFileOriginName());
                }
            } catch (Exception e) {
                log.error("获取产品库打包文件失败：{}", e.getMessage());
            }
        }
        return productPackagedResultVo;
    }

    @Override
    public Boolean uploadProductAsset(ProductComponentInputVo productComponentInputVo) {
        PmsProductLibraryRepositories repo =
                selectPmsProductLibraryByName(productComponentInputVo.getEnterpriseIdentifier(), productComponentInputVo.getProductRepoName());

        List<AssetRawInputVo> assetList = new ArrayList<>();
        PmsEnterprise pmsEnterprise = pmsEnterpriseService.selectPmsEnterpriseByIdentifier(productComponentInputVo.getEnterpriseIdentifier());
        for (Long docId : productComponentInputVo.getDocList()) {
            PmsDocumentDetailVo pmsDocument = pmsDocumentService.selectPmsDocumentDetailVoByIdAndEnterpriseId(docId, pmsEnterprise.getId());
            if (!Objects.equals(pmsDocument.getDocType(), 2) && !Objects.equals(pmsDocument.getDocType(), 3)) {
                throw new ServiceException("产品库文档类型仅允许为文档类型或附件类型(文档Id[%s])", pmsDocument.getId());
            }
            PmsProductLibraryComponent pmsProductLibraryComponent =
                    pmsProductLibraryComponentMapper.selectPmsProductLibraryComponentByIdentifier(repo.getId(), String.valueOf(docId));
            if (pmsProductLibraryComponent != null) {
                throw new ServiceException("产品库已存在该文档，请勿重复上传(文档文件名称[%s])", pmsDocument.getName());
            }
            AssetRawInputVo assetRawInputVo = new AssetRawInputVo();
            assetRawInputVo.setAssetIdentifier(String.valueOf(pmsDocument.getId()));
            if (Objects.equals(pmsDocument.getDocType(), 3)) {
                assetRawInputVo.setFilename(pmsDocument.getName());
                assetRawInputVo.setFileIdentifier(pmsDocument.getAttachmentIdentifier());
            } else if (Objects.equals(pmsDocument.getDocType(), 2)) {
                Path tempFilePath = null;
                try {
                    String docFileName = pmsDocument.getName() + ".md";
                    assetRawInputVo.setFilename(docFileName);
                    // 创建临时文件
                    tempFilePath = Files.createTempFile(pmsDocument.getName(), ".md");
                    Files.write(tempFilePath, pmsDocument.getContent().getBytes(StandardCharsets.UTF_8));
                    SysFileBytes sysFileBytes = new SysFileBytes();
                    sysFileBytes.setFileName(docFileName);
                    sysFileBytes.setFileInputStream(Files.newInputStream(tempFilePath));
                    assetRawInputVo.setFileBytes(sysFileBytes);
                } catch (IOException e) {
                    log.error("文档上传失败：{}", e.getMessage());
                    throw new ServiceException("文档上传失败");
                } finally {
                    if (tempFilePath != null) {
                        try {
                            Files.deleteIfExists(tempFilePath);
                        } catch (IOException e) {
                            log.error("删除临时文件失败：{}", e.getMessage());
                        }
                    }
                }
            }

            assetList.add(assetRawInputVo);
        }
        return pmsProductLibraryComponentService.insertRawComponent(productComponentInputVo.toComponentRawInputVo(assetList));
    }

    @Override
    public GenericsTableDataInfo<DocResultVo> selectDocList(DocSearchVo docSearchVo) {
        PmsEnterprise pmsEnterprise = pmsEnterpriseService.selectPmsEnterpriseByIdentifier(docSearchVo.getEnterpriseIdentifier());
        GenericsTableDataInfo<DocResultVo> docTableList = new GenericsTableDataInfo<>();
        GenericsTableDataInfo<PmsDocumentVo> pmsDocList = pmsDocumentService.selectPmsDocumentVoList(docSearchVo.toPmsDocumentSearchVo(pmsEnterprise.getId()));
        if (pmsDocList.getRows() != null && !pmsDocList.getRows().isEmpty()) {
            PmsProductLibraryRepositories productRepo =
                    pmsProductLibraryRepositoriesService.getPmsProductLibraryRepositories(true, docSearchVo.getEnterpriseIdentifier(), docSearchVo.getProductRepoName(), null);
            PmsProductLibraryComponent productComponentSearch = new PmsProductLibraryComponent();
            productComponentSearch.setRepoId(productRepo.getId());
            List<PmsProductLibraryComponent> productComponentList = pmsProductLibraryComponentMapper.selectPmsProductLibraryComponentList(productComponentSearch);
            List<DocResultVo> docList = pmsDocList.getRows().stream().map(pmsDoc -> {
                DocResultVo doc = new DocResultVo(pmsDoc);
                boolean isChoose = productComponentList.stream().anyMatch(x -> String.valueOf(pmsDoc.getId()).equals(x.getIdentifier()));
                doc.setIsChoose(isChoose);
                return doc;
            }).collect(Collectors.toList());
            docTableList.setRows(docList);
            docTableList.setTotal(docList.size());
        }
        return docTableList;
    }


    @Override
    public int insertPmsProductLibrary(ProductRepositoriesInputVo productRepositoriesInputVo) {
        PmsEnterprise pmsEnterprise = pmsEnterpriseService.selectPmsEnterpriseByIdentifier(productRepositoriesInputVo.getEnterpriseIdentifier());
        // 校验制品库标识
        Integer count = pmsProductLibraryRepositoriesMapper.selectPmsProductLibraryRepositoriesByNameCount(productRepositoriesInputVo.getName(), productRepositoriesInputVo.getEnterpriseIdentifier(), productRepositoriesInputVo.getFormat());
        if (count > 0) {
            throw new ServiceException("该产品库标识在当前组织下已存在(产品库标识[%s])", productRepositoriesInputVo.getName());
        }
        // 校验制品库别名
        PmsProductLibraryRepositories aliasRepo =
                pmsProductLibraryRepositoriesMapper.selectPmsProductLibraryByAlias(
                        productRepositoriesInputVo.getAlias(),
                        productRepositoriesInputVo.getEnterpriseIdentifier());
        if (aliasRepo != null) {
            throw new ServiceException("该产品库名称在当前组织下已存在(产品库名称[%s])", productRepositoriesInputVo.getAlias());
        }
        NexusHostedRepoInputVo requestBody = productRepositoriesInputVo.toNexusRepoDataVo();

        // 调用制品库创建接口创建产品库
        nexusRequestHelper.doRequest(NexusRequestUrl.ADD_REPOSITORIES(requestBody.getType(), requestBody.getFormat()), JSONObject.from(requestBody));
        // 调用Nexus制品库详情接口获取制品库详情
        NexusHostedRepoInputVo nexusDataVo = pmsProductLibraryRepositoriesService.getNexusRepo(
                productRepositoriesInputVo.getType(),
                productRepositoriesInputVo.getFormat(),
                PmsProductLibraryRepositories.getNexusProductRepositoriesName(
                        productRepositoriesInputVo.getEnterpriseIdentifier(),
                        productRepositoriesInputVo.getName()
                ));
        // 数据库添加该制品库
        PmsProductLibraryRepositories pmsProductLibraryRepositories = productRepositoriesInputVo.toPmsProductLibraryRepositories();
        pmsProductLibraryRepositories.setUrl(nexusDataVo.getUrl());
        pmsProductLibraryRepositories.setPmsEnterpriseId(pmsEnterprise.getId());
        pmsProductLibraryRepositories.setDeptId(pmsEnterprise.getDeptId());
        pmsProductLibraryRepositories.setCreateTime(DateUtils.getNowDate());
        pmsProductLibraryRepositories.setCreateBy(SecurityUtils.getUsername());
        return pmsProductLibraryRepositoriesMapper.insertPmsProductLibraryRepositories(pmsProductLibraryRepositories);
    }

    @Override
    public int deletePmsProductLibraryByName(String enterpriseIdentifier, String name) {
        PmsProductLibraryRepositories oldRepo = selectPmsProductLibraryByName(enterpriseIdentifier, name);
        // 调用制品库删除接口删除制品库
        nexusRequestHelper.doRequest(NexusRequestUrl.DELETE_REPOSITORIES(PmsProductLibraryRepositories.getNexusProductRepositoriesName(enterpriseIdentifier, name)));
        return pmsProductLibraryRepositoriesMapper.deletePmsProductLibraryRepositoriesById(oldRepo.getId());
    }

    @Override
    public boolean addCommonAssetToProductRepo(CommonAssetAddToProductRepoVo commonAssetAddToProductRepoVo) {
        // 先校验产品库、制品库、制品库下制品Id列表是否存在，再进行异步处理
        PmsProductLibraryRepositories productRepo = selectPmsProductLibraryByName(commonAssetAddToProductRepoVo.getEnterpriseIdentifier(), commonAssetAddToProductRepoVo.getProductRepoName());
        PmsProductLibraryRepositories repo = pmsProductLibraryRepositoriesService.selectPmsProductLibraryRepositoriesByName(commonAssetAddToProductRepoVo.getEnterpriseIdentifier(), commonAssetAddToProductRepoVo.getRepoName());
        if (ProductLibraryRepositoriesFormatEnum.DOCKER.getKey().equals(repo.getFormat())) {
            throw new ServiceException("Docker制品移入不能使用该接口");
        }
        List<NexusAssetResultDataVo> nexusAssetResultDataVoList = new ArrayList<>();
        for (String assetId : commonAssetAddToProductRepoVo.getAssetIdList()) {
            NexusComponentResultVo<NexusAssetResultDataVo> nexusAssetResultVo = pmsProductLibraryComponentService.getAssetDetailByAssetId(commonAssetAddToProductRepoVo.getEnterpriseIdentifier(), commonAssetAddToProductRepoVo.getRepoName(), null, assetId, false);
            if (nexusAssetResultVo == null || nexusAssetResultVo.getResult() == null || !nexusAssetResultVo.getResult().getSuccess()) {
                throw new ServiceException("该制品不存在(制品库[%s],制品Id[%s])", commonAssetAddToProductRepoVo.getRepoName(), assetId);
            } else {
                NexusAssetResultDataVo data = nexusAssetResultVo.getResult().getData();
                if (pmsProductLibraryComponentService.getLockComponentStatus(productRepo.getId(), assetId)) {
                    throw new ServiceException("制品锁定中，无法被移入产品库(制品名称[%s],产品库名称[%s])", data.getName(), productRepo.getName());
                }
                PmsProductLibraryComponent pmsProductLibraryComponent = pmsProductLibraryComponentMapper.selectPmsProductLibraryComponentByIdentifier(productRepo.getId(), assetId);
                if (pmsProductLibraryComponent != null) {
                    throw new ServiceException("制品已被移入产品库中，无法重复移入(制品名称[%s],产品库名称[%s])", data.getName(), productRepo.getName());
                }
                nexusAssetResultDataVoList.add(data);
            }
        }
        pmsProductLibraryAsyncService.asyncAddCommonAssetToProductRepo(productRepo, repo, nexusAssetResultDataVoList, commonAssetAddToProductRepoVo.getDirectory());
        return true;
    }

    @Override
    public NexusComponentResultVo<List<NexusResultDataVo>> selectPmsProductLibraryKeyComponentList(String enterpriseIdentifier, ComponentSearchVo componentSearchVo) {
        PmsProductLibraryRepositories productRepo = pmsProductLibraryRepositoriesService.getPmsProductLibraryRepositories(true, enterpriseIdentifier, componentSearchVo.getProductRepoName(), null);
        PmsProductLibraryComponent productComponentSearch = new PmsProductLibraryComponent();
        productComponentSearch.setRepoId(productRepo.getId());
        List<PmsProductLibraryComponent> productComponentList = pmsProductLibraryComponentMapper.selectPmsProductLibraryComponentList(productComponentSearch);
        PmsProductLibraryRepositories repo = pmsProductLibraryRepositoriesService.getPmsProductLibraryRepositories(false, enterpriseIdentifier, componentSearchVo.getRepositoryName(), null);
        componentSearchVo.setRepositoryName(repo.getNexusRepositoriesName());
        // Docker类型调用Nexus获取制品列表接口获取
        if (ProductLibraryRepositoriesFormatEnum.DOCKER.getKey().equals(repo.getFormat())) {
            List<NexusResultDataVo> keyNexusResultDataVoList = new ArrayList<>();
            // 需循环遍历获取所有镜像列表
            boolean isAll = false;
            // Nexus分页Token
            String continuationToken = null;
            while (!isAll) {
                NexusComponentAndAssetListVo<NexusDockerComponentVo> assetListVo = nexusRequestHelper.doRequestToJavaObject(NexusRequestUrl.GET_COMPONENTS(repo.getNexusRepositoriesName(), continuationToken), NexusComponentAndAssetListVo.class, NexusDockerComponentVo.class);
                if (assetListVo != null) {
                    if (StringUtils.isEmpty(assetListVo.getContinuationToken())) {
                        isAll = true;
                    } else {
                        continuationToken = assetListVo.getContinuationToken();
                    }
                    for (NexusDockerComponentVo nexusDockerComponentVo : assetListVo.getItems()) {
                        NexusResultDataVo nexusResultDataVo = nexusDockerComponentVo.toNexusResultDataVo();
                        keyNexusResultDataVoList.add(nexusResultDataVo);
                    }
                } else {
                    isAll = true;
                }

            }
            setNexusResultDataVoChoose(productRepo, productComponentList, keyNexusResultDataVoList, true);
            setNexusResultDataVoPath(repo, keyNexusResultDataVoList);
            return buildDockerResultVo(keyNexusResultDataVoList);
        } else {
            NexusComponentSearchVo<ComponentSearchVo> nexusComponentSearchVo = NexusComponentSearchVo.toRead(componentSearchVo, nexusRequestHelper.getNexusTid());
            NexusComponentResultVo<List<NexusResultDataVo>> assetResultDataVo = nexusRequestHelper.doRequestToJavaObjectList(NexusRequestUrl.DO_OPERATION(), JSONObject.from(nexusComponentSearchVo), NexusComponentResultVo.class, NexusResultDataVo.class);
            if (assetResultDataVo != null && assetResultDataVo.getResult() != null) {
                NexusComponentResultStateVo<List<NexusResultDataVo>> nexusComponentResultStateVo = assetResultDataVo.getResult();
                if (nexusComponentResultStateVo.getSuccess()) {
                    List<NexusResultDataVo> nexusResultDataVoList = nexusComponentResultStateVo.getData();
                    setNexusResultDataVoChoose(productRepo, productComponentList, nexusResultDataVoList, false);
                    setNexusResultDataVoPath(repo, nexusResultDataVoList);
                    // 当制品库为Maven时，需排除自动生成的制品数据
                    if (ProductLibraryRepositoriesFormatEnum.MAVEN.getKey().equals(repo.getFormat())) {
                        List<NexusResultDataVo> keyNexusResultDataVoList = new ArrayList<>();
                        for (NexusResultDataVo nexusResultDataVo : nexusResultDataVoList) {
                            // 当类型为asset时，需检查数据库是否存在记录，若存在则返回
                            if ("asset".equals(nexusResultDataVo.getType())) {
                                PmsProductLibraryComponent pmsProductLibraryComponent = pmsProductLibraryComponentMapper.selectPmsProductLibraryComponentByPath(nexusResultDataVo.getId(), repo.getId(), repo.getPmsEnterpriseId());
                                if (pmsProductLibraryComponent != null) {
                                    keyNexusResultDataVoList.add(nexusResultDataVo);
                                }
                            } else {
                                keyNexusResultDataVoList.add(nexusResultDataVo);
                            }
                        }
                        nexusComponentResultStateVo.setData(keyNexusResultDataVoList);
                        assetResultDataVo.setResult(nexusComponentResultStateVo);
                    }
                }
            }
            return assetResultDataVo;
        }
    }

    @Override
    public boolean addDockerComponentToProductRepo(DockerComponentAddToProductRepoVo dockerComponentAddToProductRepoVo) {
        // 先校验产品库、制品库、制品库下制品Id列表是否存在，再进行异步处理
        PmsProductLibraryRepositories productRepo = selectPmsProductLibraryByName(dockerComponentAddToProductRepoVo.getEnterpriseIdentifier(), dockerComponentAddToProductRepoVo.getProductRepoName());
        PmsProductLibraryRepositories repo = pmsProductLibraryRepositoriesService.selectPmsProductLibraryRepositoriesByName(dockerComponentAddToProductRepoVo.getEnterpriseIdentifier(), dockerComponentAddToProductRepoVo.getRepoName());
        if (!ProductLibraryRepositoriesFormatEnum.DOCKER.getKey().equals(repo.getFormat())) {
            throw new ServiceException("当前接口仅允许进行Docker移入产品库操作");
        }
        List<NexusComponentResultDataVo> nexusComponentResultDataVoList = new ArrayList<>();
        for (String componentId : dockerComponentAddToProductRepoVo.getComponentIdList()) {
            NexusComponentResultVo<NexusComponentResultDataVo> nexusAssetResultVo = pmsProductLibraryComponentService.getComponentDetailByComponentId(dockerComponentAddToProductRepoVo.getEnterpriseIdentifier(), dockerComponentAddToProductRepoVo.getRepoName(), null, componentId, false);
            if (nexusAssetResultVo == null || nexusAssetResultVo.getResult() == null || !nexusAssetResultVo.getResult().getSuccess()) {
                throw new ServiceException("该制品不存在(制品库[%s],制品Id[%s])", dockerComponentAddToProductRepoVo.getRepoName(), componentId);
            } else {
                NexusComponentResultDataVo data = nexusAssetResultVo.getResult().getData();
                if (pmsProductLibraryComponentService.getLockComponentStatus(productRepo.getId(), componentId)) {
                    throw new ServiceException("制品锁定中，无法被移入产品库(制品名称[%s],产品库名称[%s])", data.getName(), productRepo.getName());
                }
                PmsProductLibraryComponent pmsProductLibraryComponent = pmsProductLibraryComponentMapper.selectPmsProductLibraryComponentByIdentifier(productRepo.getId(), componentId);
                if (pmsProductLibraryComponent != null) {
                    throw new ServiceException("制品已被移入产品库中，无法重复移入(制品名称[%s],产品库名称[%s])", data.getName(), productRepo.getName());
                }
                nexusComponentResultDataVoList.add(data);
            }
        }
        pmsProductLibraryAsyncService.asyncAddDockerComponentToProductRepo(productRepo, repo, nexusComponentResultDataVoList, dockerComponentAddToProductRepoVo.getDirectory());
        return true;
    }

    private void setNexusResultDataVoChoose(PmsProductLibraryRepositories productRepo, List<PmsProductLibraryComponent> productComponentList, List<NexusResultDataVo> nexusResultDataVoList, boolean isDocker) {
        for (PmsProductLibraryComponent component : productComponentList) {
            nexusResultDataVoList.forEach(x -> {
                if (pmsProductLibraryComponentService.getLockComponentStatus(productRepo.getId(), x.getComponentId())) {
                    x.setIsChoose(true);
                } else if (isDocker && StringUtils.isNotEmpty(x.getComponentId())) {
                    if (x.getComponentId().equals(component.getIdentifier())) {
                        x.setIsChoose(true);
                    }
                } else if (StringUtils.isNotEmpty(x.getAssetId()) && x.getAssetId().equals(component.getIdentifier())) {
                    x.setIsChoose(true);
                }
            });
        }
    }

    private void setNexusResultDataVoPath(PmsProductLibraryRepositories repo, List<NexusResultDataVo> nexusResultDataVoList) {
        nexusResultDataVoList.forEach(x -> {
            if (ProductLibraryRepositoriesFormatEnum.DOCKER.getKey().equals(repo.getFormat())) {
                x.setDefaultDir(EscapeUtil.removeExtraSlashOfUrl(String.format("/%s/", repo.getAlias())));
            } else {
                x.setDefaultDir(EscapeUtil.removeExtraSlashOfUrl(String.format("/%s/%s", repo.getAlias(), PmsUtils.parseDirectory(x.getId()))));
            }
        });
    }

    private NexusComponentResultVo<List<NexusResultDataVo>> buildDockerResultVo(List<NexusResultDataVo> data) {
        NexusComponentResultVo<List<NexusResultDataVo>> target = new NexusComponentResultVo<>();
        target.setAction("coreui_Browse");
        target.setMethod("read");
        target.setTid(1);
        target.setType("rpc");
        NexusComponentResultStateVo<List<NexusResultDataVo>> nexusComponentResultStateVo = new NexusComponentResultStateVo<>();
        nexusComponentResultStateVo.setData(data);
        nexusComponentResultStateVo.setSuccess(true);
        target.setResult(nexusComponentResultStateVo);
        return target;
    }


    @Override
    public boolean packagedProduct(String enterpriseIdentifier, String productRepoName) {
        PmsProductLibraryRepositories productRepo = selectPmsProductLibraryByName(enterpriseIdentifier, productRepoName);
        pmsProductLibraryAsyncService.packagedProduct(productRepo);
        return true;
    }
}
