/*
* Copyright (c) 京北方信息技术股份有限公司 Corporation 2022 . All rights reserved.
*
*/
package net.northking.cctp.scriptcase.api.component.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hzbank.testteam.autotest.dependencies.authDependency.utils.RequestUtil;
import com.hzbank.testteam.autotest.dependencies.baseDefineDependency.exception.InvalidException;
import com.hzbank.testteam.autotest.dependencies.monsterDependency.dto.UserDTO;
import net.northking.cctp.common.cache.EntityNameCache;
import net.northking.cctp.common.cache.EntityNameCatalog;
import net.northking.cctp.common.db.Pagination;
import net.northking.cctp.common.db.annotation.DatabaseReadOnly;
import net.northking.cctp.common.dto.AdvancedQueryOptions;
import net.northking.cctp.common.dto.AssociatedFilesDto;
import net.northking.cctp.common.dto.UserOptions;
import net.northking.cctp.common.enums.FileBusinessTypeEnum;
import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.common.feign.MonsterCommonFeignClient;
import net.northking.cctp.common.http.QueryByPage;
import net.northking.cctp.common.http.QueryOrderBy;
import net.northking.cctp.common.http.ResultWrapper;
import net.northking.cctp.common.s3.SimpleStorageService;
import net.northking.cctp.common.security.authentication.NKSecurityContext;
import net.northking.cctp.common.util.DateUtil;
import net.northking.cctp.common.util.UUIDUtil;
import net.northking.cctp.scriptcase.api.atuScript.service.AtuScriptInfoApiService;
import net.northking.cctp.scriptcase.api.comLib.service.LibraryBusComInfoApiService;
import net.northking.cctp.scriptcase.bus.NoticePublisher;
import net.northking.cctp.scriptcase.constants.ScriptConstant;
import net.northking.cctp.scriptcase.db.entity.*;
import net.northking.cctp.scriptcase.db.service.*;
import net.northking.cctp.scriptcase.dto.atuScript.UserQueryDto;
import net.northking.cctp.scriptcase.dto.comLib.LibraryBusComInfoAddDto;
import net.northking.cctp.scriptcase.dto.component.*;
import net.northking.cctp.scriptcase.enums.ScriptCaseAppError;
import net.northking.cctp.scriptcase.feign.AttachmentFeignClient;
import net.northking.cctp.scriptcase.feign.PlatformFeignClient;
import net.northking.cctp.scriptcase.tools.MinioPathUtils;
import net.northking.cctp.scriptcase.tools.RuleDefinitionTool;
import net.northking.cctp.scriptcase.tools.ScriptCaseUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 业务组件表_编辑服务实现类
 *
 * @author maven-cctp-plugin
 * @since 1.0
 */

@Service
@ConditionalOnMissingBean(name = "MdBusComponentInfoApiServiceImpl")
public class MdBusComponentInfoApiServiceImpl implements MdBusComponentInfoApiService
{
  /**
   * 日志
   */
  private final static Logger logger = LoggerFactory.getLogger(MdBusComponentInfoApiServiceImpl.class);

  @Autowired
  private MdBusComponentInfoService mdBusComponentInfoService;
  @Autowired
  private BusComponentTreeService busComponentTreeService;
  @Autowired
  private PlatformFeignClient platformFeignClient;
  @Autowired
  private EntityNameCache entityNameCache;
  @Autowired
  private MdComponentParamService mdComponentParamService;
  @Autowired
  private NoticePublisher noticeRabbitMQPublisher;
  @Autowired
  private LibraryBusComInfoApiService libraryBusComInfoApiService;
  @Autowired
  private LibraryBusComInfoService libraryBusComInfoService;
  @Autowired
  private ScriptCaseUtils scriptCaseUtils;
  @Autowired
  private AttachmentFeignClient attachmentFeignClient;
  @Autowired
  MonsterCommonFeignClient monsterCommonFeignClient;
  @Autowired
  private SimpleStorageService simpleStorageService;
 @Autowired
  private AtuScriptInfoApiService atuScriptInfoApiService;
  @Override
  @DatabaseReadOnly
  public Pagination<MdBusComponentInfoDetailDto> pagingQuery(QueryByPage<MdBusComponentInfoQueryDto> queryByPage)
  {
    MdBusComponentInfoQueryDto query = queryByPage.getQuery();
    query.setTenantId(NKSecurityContext.getTenantId());
    // 处理树目录
    if (!StringUtils.isEmpty(query.getTreeId())) {
      if (!ScriptConstant.DATA_FIRST_NODE.equals(query.getTreeId())) {
        List<String> treeIds = busComponentTreeService.getChildTreeIds(query.getTreeId());
        query.setTreeIds(treeIds);
      } else {
        query.setTreeId(null);
      }
    }
    if (!StringUtils.isEmpty(query.getCreatedBy())) {
      // 根据执行人名称查询用户id
      List<String> userIds = getUserIds(query.getCreatedBy());
      if (userIds.isEmpty()) {
        userIds.add(ScriptConstant.STR_ZERO);
      }
      query.setUserIds(userIds);
    }
    buildQueryPage(query);
    //处理排序问题
    List<QueryOrderBy> orderList = queryByPage.getOrderByList();
    if (orderList == null || orderList.isEmpty()) {
      orderList = new ArrayList<>();
      QueryOrderBy orderBy = new QueryOrderBy();
      orderBy.desc(ScriptConstant.CREATED_TIME);
      orderList.add(orderBy);
      queryByPage.setOrderByList(orderList);
    }

    if (query.isMultiItem()) {
      query.setProjectId(null);
    }else{
      query.setProjectList(null);
    }
    Pagination<MdBusComponentInfoDetailDto> pagination = mdBusComponentInfoService.pagingQueryNew(queryByPage);
    long c = System.currentTimeMillis();
    if (pagination.getRecords().size() > 0) {
      List<MdBusComponentInfoDetailDto> records = pagination.getRecords();
      for (MdBusComponentInfoDetailDto record : records) {
        record.setUpdatedBy(entityNameCache.translateById(EntityNameCatalog.MONSTER_USER.name(), record.getUpdatedBy()));
        record.setCreatedBy(entityNameCache.translateById(EntityNameCatalog.MONSTER_USER.name(), record.getCreatedBy()));
        record.setPrincipalId(entityNameCache.translateById(EntityNameCatalog.MONSTER_USER.name(), record.getPrincipalId()));
        if(record.getSharedFlag()==1){
          LibraryBusComInfo share = libraryBusComInfoService.findByPrimaryKey(record.getId());
          if(share!=null){
            record.setSharedBy(entityNameCache.translateById(EntityNameCatalog.MONSTER_USER.name(), share.getCreatedBy()));
            record.setSharedTime(share.getCreatedTime());
          }
        }
      }
    }
    return pagination;
  }

  private void buildQueryPage(MdBusComponentInfoQueryDto query) {
    // 负责人 修改人
    if (!StringUtils.isEmpty(query.getPrincipal())) {
      List<String> principalIds = getUserIds(query.getPrincipal());
      if (!CollectionUtil.isEmpty(principalIds)) {
        query.setPrincipalIds(principalIds);
      } else {
        principalIds.add(ScriptConstant.STR_ZERO);
        query.setPrincipalIds(principalIds);
      }
    }
    if (!StringUtils.isEmpty(query.getUpdatedName())) {
      List<String> updateBys = getUserIds(query.getUpdatedName());
      if (!CollectionUtils.isEmpty(updateBys)) {
        query.setUpdatedBys(updateBys);
      } else {
        updateBys.add(ScriptConstant.STR_ZERO);
        query.setUpdatedBys(updateBys);
      }
    }
    //创建时间--时间区间  修改时间--时间区间
    String createdTimeStart = query.getCreatedTimeStart();
    if (!StringUtils.isEmpty(createdTimeStart)) {
      Date startCreatedTime = null;
      try {
        startCreatedTime = DateUtil.parse(createdTimeStart +ScriptConstant.BEGIN_TIME,ScriptConstant.TIME_PATTERN);

      } catch (ParseException e) {
        logger.error("时间转换异常，createdTimeStart，{}，e,{}",createdTimeStart,e.getMessage());
        throw new PlatformRuntimeException(ScriptCaseAppError.PARSE_DATE_ERROR);
      }
      query.setStartCreatedTime(startCreatedTime);
    }
    String createdTimeEnd = query.getCreatedTimeEnd();
    if (!StringUtils.isEmpty(createdTimeEnd)) {
      Date endCreatedTime = null;
      try {
        endCreatedTime = DateUtil.parse(createdTimeEnd + ScriptConstant.END_TIME,ScriptConstant.TIME_PATTERN);

      } catch (ParseException e){
        logger.error("时间转换异常，createdTimeEnd，{}，e,{}",createdTimeEnd,e.getMessage());
        throw new PlatformRuntimeException(ScriptCaseAppError.PARSE_DATE_ERROR);
      }
      query.setEndCreatedTime(endCreatedTime);
    }
    // 更新时间
    String updatedTimeStart = query.getUpdatedTimeStart();
    if (!StringUtils.isEmpty(updatedTimeStart)) {
      Date startUpdatedTime = null;
      try{
        startUpdatedTime = DateUtil.parse(updatedTimeStart+ScriptConstant.BEGIN_TIME,ScriptConstant.TIME_PATTERN);
      }catch (ParseException e){
        logger.error("时间转换异常，updatedTimeStart，{}，e,{}",updatedTimeStart,e.getMessage());
        throw new PlatformRuntimeException(ScriptCaseAppError.PARSE_DATE_ERROR);
      }
      query.setStartUpdatedTime(startUpdatedTime);
    }
    String updatedTimeEnd = query.getUpdatedTimeEnd();
    if (!StringUtils.isEmpty(updatedTimeEnd)) {
      Date endUpdatedTime = null;
      try {
        endUpdatedTime = DateUtil.parse(updatedTimeEnd+ ScriptConstant.END_TIME,ScriptConstant.TIME_PATTERN);
      } catch (ParseException e) {
        logger.error("时间转换异常，updatedTimeEnd，{}，e,{}",updatedTimeEnd,e.getMessage());
        throw new PlatformRuntimeException(ScriptCaseAppError.PARSE_DATE_ERROR);
      }
      query.setEndUpdatedTime(endUpdatedTime);
    }
  }

  @Override
  @Transactional
  public Integer updateByPK(MdBusComponentInfoUpdateDto dto) throws IllegalAccessException
  {
    MdBusComponentInfo old = mdBusComponentInfoService.findByPrimaryKey(dto.getId());
    if(old==null || 1==old.getIsDeleted()){
      throw new PlatformRuntimeException(ScriptCaseAppError.DATA_NOT_EXIT1);
    }
    if(dto.getComName()!=null){
      MdBusComponentInfo check = new MdBusComponentInfo();
      check.setIsDeleted(0);
      check.setTenantId(NKSecurityContext.getTenantId());
      check.setProjectId(old.getProjectId());
      check.setTreeId(old.getTreeId());
      check.setComName(dto.getComName());
      List<MdBusComponentInfo> checkList = mdBusComponentInfoService.query(check);
      if(checkList.size()>1 || (checkList.size()==1 && !dto.getId().equals(checkList.get(0).getId()))){
        throw new PlatformRuntimeException(ScriptCaseAppError.BUS_COM_NAME_EXIT);
      }
      if(libraryBusComInfoService.findByPrimaryKey(old.getId())!=null){
        LibraryBusComInfo update =new LibraryBusComInfo();
        update.setId(old.getId());
        update.setComName(dto.getComName());
        libraryBusComInfoService.updateByPrimaryKey(update);
      }
    }
    MdBusComponentInfo entity = new MdBusComponentInfo();
    BeanUtils.copyProperties(dto, entity);
    if (dto.getComName()==null && entity.getMemo()==null) {
      entity.setMemo("");
    }
    //提升版本
    String oldVer = old.getComVersion();
    boolean flag = StringUtils.isEmpty(old.getComVersion());
    String newVer;
    if(flag){
      newVer = ScriptConstant.COM_DEFAULT_VERSION;
    }else{
      newVer = ScriptCaseUtils.getNextVersion(oldVer);
    }
    entity.setComVersion(newVer);
    logger.debug("提升版本为： {}", newVer);
    if (dto.getScriptContent() != null) {
      logger.debug("更新文件服务器文件内容");
      String scriptContent = dto.getScriptContent();
      JSONObject jsonObject = JSON.parseObject(scriptContent, JSONObject.class);
      Integer scriptType = old.getComType();
      FileBusinessTypeEnum businessCode = null;
      if (scriptType.equals(2) || scriptType.equals(3)) {
        businessCode = FileBusinessTypeEnum.PC_RECORD_SCREENSHOT;
      } else if (scriptType.equals(4) || scriptType.equals(5)) {
        businessCode = FileBusinessTypeEnum.MOBILE_RECORD_SCREENSHOT;
      }
      if (businessCode != null) {
        JSONObject oldJsonObject = scriptCaseUtils.getJsonByFileId(old.getScriptContent());
        Map<String, String> oldPathAndNewPathMap = new HashMap<>();
        atuScriptInfoApiService.getIamgeUrlByJsonArray(null, oldJsonObject.get("commands"), oldPathAndNewPathMap, false, businessCode);
        atuScriptInfoApiService.getIamgeUrlByJsonArray(dto.getId(), jsonObject.get("commands"), oldPathAndNewPathMap, true, businessCode);
        List<String> fileIds = oldPathAndNewPathMap.keySet().stream().map(path -> "/" + MinioPathUtils.idToPath(path)[1]).collect(Collectors.toList());
        fileIds.add("/" + MinioPathUtils.idToPath(old.getScriptContent())[1]);
        if (!CollectionUtils.isEmpty(fileIds)) {
          AssociatedFilesDto associatedFilesDto = new AssociatedFilesDto();
          associatedFilesDto.setObjId("-1");
          associatedFilesDto.setFileIds(fileIds);
          ResultWrapper<String> wrapper = attachmentFeignClient.associatedFiles(associatedFilesDto);
          if (wrapper == null || !wrapper.isSuccess()) {
            throw new InvalidException("文件关联异常");
          }
        }
      }
      scriptContent = jsonObject.toJSONString();
      String newFile = scriptCaseUtils.generateScriptFileAndUpload(scriptContent, dto.getId(), FileBusinessTypeEnum.BUSINESS_COMPONENT_SCRIPT);
      entity.setScriptContent(newFile);
      //发送更新文件服务器
      Map<String,String> map = new HashMap<>();
      map.put(ScriptConstant.UUID,old.getScriptContent());
      map.put(ScriptConstant.NEW_FILE,newFile);
      attachmentFeignClient.update(map);
    }
    logger.debug("更新业务组件信息");
    int num = this.mdBusComponentInfoService.updateByPrimaryKey(entity);
    //更新参数和步骤的json字段
    if(dto.getComJson() !=null ||dto.getParamJson()!=null){
      logger.debug("更新业务组件参数信息");
      MdComponentParam paramUp = new MdComponentParam();
      paramUp.setId(dto.getId());
      paramUp.setComJson(dto.getComJson());
      paramUp.setParamJson(dto.getParamJson());
      mdComponentParamService.updateByPrimaryKey(paramUp);
    }

    return num;
  }

  @Override
  @DatabaseReadOnly
  public MdBusComponentInfoDetailDto findByPK(String uuid)
  {
    MdBusComponentInfo entity = mdBusComponentInfoService.findByPrimaryKey(uuid);
    if(entity==null || 1==entity.getIsDeleted()){
      throw new PlatformRuntimeException(ScriptCaseAppError.DATA_NOT_EXIT);
    }
    MdBusComponentInfoDetailDto dto = new MdBusComponentInfoDetailDto();
    BeanUtils.copyProperties(entity, dto);
    //文件id下载转化报文
    dto.setScriptContent(scriptCaseUtils.getJsonByFileId(dto.getScriptContent()).toJSONString());
    MdComponentParam param = mdComponentParamService.findByPrimaryKey(uuid);
    dto.setComJson(param.getComJson());
    dto.setParamJson(param.getParamJson());
    return dto;
  }

  @Override
  @Transactional
  public int deleteByIds(List<String> ids) {
    //删除会完整删除md和re表数据并发送日志
    String idStr = mdBusComponentInfoService.deleteByIdList(ids);
    if(idStr==null || idStr.length()<32) return 0;
    List<MdBusComponentInfo> delList = mdBusComponentInfoService.findByPrimaryKeys(Arrays.asList(idStr.split(",")));
    Map<String, String> oldPathAndNewPathMap = new HashMap<>();
    delList.forEach(one->{
      if (one.getSharedFlag()==1)
        throw new PlatformRuntimeException(ScriptCaseAppError.BUS_COM_SHARED);
      String fileAddr = one.getScriptContent();
      JSONObject oldJsonObject = scriptCaseUtils.getJsonByFileId(fileAddr);
      atuScriptInfoApiService.getIamgeUrlByJsonArray(null, oldJsonObject.get("commands"), oldPathAndNewPathMap, false, null);
      String[] pathData = MinioPathUtils.idToPath(fileAddr);
      try {
        simpleStorageService.delete(pathData[0], "/" + pathData[1]);
      } catch (Exception e) {
        logger.error("文件删除失败id:{}", "/" + pathData[1]);
        throw new InvalidException("文件删除失败");
      }
    });
    List<String> deletedFilePath = oldPathAndNewPathMap.keySet().stream().map(path -> "/" + MinioPathUtils.idToPath(path)[1]).collect(Collectors.toList());
    if (!CollectionUtils.isEmpty(deletedFilePath)) {
      AssociatedFilesDto associatedFilesDto = new AssociatedFilesDto();
      associatedFilesDto.setObjId("-1");
      associatedFilesDto.setFileIds(deletedFilePath);
      ResultWrapper<String> wrapper = attachmentFeignClient.associatedFiles(associatedFilesDto);
      if (wrapper == null || !wrapper.isSuccess()) {
        throw new InvalidException("文件关联异常");
      }
    }
    mdComponentParamService.deleteByPrimaryKeys(Arrays.asList(ids.toArray()));
    //发送日志
    List<String> names = new ArrayList<>();
    delList.forEach(one->{names.add(one.getComName());});
    String projectId = delList.get(0).getProjectId();
    if (names.size()>1) {
      noticeRabbitMQPublisher.deployHighRiskLog(
              ScriptConstant.BUS_COM_BATCH, delList.size() + "", names, projectId);

    } else {
      noticeRabbitMQPublisher.deployHighRiskLog(
              ScriptConstant.BUS_COM, delList.get(0).getComName(), names, projectId);
    }
    return delList.size();
  }

  /**
   * 单个复制用例
   * @param target
   * @return
   */
  @Override
  public int copyById(MdBusComCopyDto target) {
    int num = 0;
    int faied = 0;
    StringBuilder buff = new StringBuilder("");
    int total = target.getIds().size();
    if (total>0){
      MdBusComponentInfo copy = new MdBusComponentInfo();
      copy.setTreeId(target.getTreeId());
      copy.setProjectId(target.getProjectId());
      for (String id : target.getIds()) {
        copy.setId(id);
        String name = copyByIdTool(copy);
        if(StringUtils.isNotEmpty(name)){
          buff.append(name).append(",");
        }else{
          num++;
        }
        if("".equals(name)){
          faied++;
        }
      }
      if(total==1 && num==0){//只有一个且失败
        throw new PlatformRuntimeException(ScriptCaseAppError.BUS_COM_NAME_TOO_LONG);
      }
      if(total==1 && faied>0){//只有一个且文件上传失败
        throw new PlatformRuntimeException(ScriptCaseAppError.JSON_FILE_UPLOAD_FAILED);
      }
      if(total>1 && num <total){//批量且存在名称超长
        throw new PlatformRuntimeException(ScriptCaseAppError.BUS_COM_NAME_TOO_LONG_BATCH,total,num);
      }
    }
    return total;
  }


  @Override
  @Transactional
  public int busComListToLib(MdBusComCopyDto dto) {
    List<Object> ids = new ArrayList<>(dto.getIds());
    if(ids.size()<1){
      return 0;
    }
    List<MdBusComponentInfo> infoList = mdBusComponentInfoService.findByPrimaryKeys(ids);
    String projectId = infoList.get(0).getProjectId();
    List<LibraryBusComInfoAddDto> insertList = new ArrayList<>();
    Map<String,Integer> checkName = new HashMap<>();
    for (MdBusComponentInfo mdInfo : infoList) {
      if(mdInfo.getSharedFlag()==1){
        throw new PlatformRuntimeException(ScriptCaseAppError.TICK_COM_IS_SHARE,mdInfo.getComName());
      }
      if(checkName.containsKey(mdInfo.getComName())){
        throw new PlatformRuntimeException(ScriptCaseAppError.TICK_COM_NAME_REPEAT,mdInfo.getComName());
      }else{
        checkName.put(mdInfo.getComName(),1);
      }
      LibraryBusComInfoAddDto libCom = new LibraryBusComInfoAddDto();
      libCom.setId(mdInfo.getId());
      libCom.setComName(mdInfo.getComName());
      libCom.setProjectId(projectId);
      libCom.setComType(mdInfo.getComType());
      insertList.add(libCom);
    }
    //批量修改共享组件的是否共享标识
    MdBusComponentInfo update = new MdBusComponentInfo();
    update.setSharedFlag(1);
    mdBusComponentInfoService.updateInfoByIds(update,dto.getIds());
    logger.info("业务组件入库 --------- 数据获取完毕 发送组件库服务");
    return libraryBusComInfoApiService.insertLibComByBatch(insertList,dto.getTreeId());
  }


  /**
   * 取消共享业务组件-直接物理删除即可
   * @param dto
   * @return
   */
  @Override
  public int busComCancelShared(MdBusComCopyDto dto) {
    List<MdBusComponentInfo> list = mdBusComponentInfoService.findByPrimaryKeys(new ArrayList(dto.getIds()));
    boolean check = false;
    if(list.size()>0){
      for (MdBusComponentInfo one : list) {
        if(one.getSharedFlag()==1) check=true;
      }
    }else {
      throw new PlatformRuntimeException(ScriptCaseAppError.DATA_NOT_EXIT1);
    }
    if(!check){
      throw new PlatformRuntimeException(ScriptCaseAppError.BUS_COM_ALL_SELF);
    }

    //将业务组件都置未未共享标识
    MdBusComponentInfo update = new MdBusComponentInfo();
    update.setSharedFlag(0);//置为未共享状态
    mdBusComponentInfoService.updateInfoByIds(update,dto.getIds());
    return libraryBusComInfoApiService.deleteByIds(dto.getIds());
  }

  /**
   * 批量修改业务组件内容
   * @param dto
   * @return
   */
  @Override
  public int updateByBatch(MdBusComCopyDto dto) {
    //批量修改业务组件内容
    MdBusComponentInfo update = new MdBusComponentInfo();
    BeanUtils.copyProperties(dto,update);
    update.setUpdatedBy(String.valueOf(RequestUtil.getRequestUserId()));
    return mdBusComponentInfoService.updateInfoByIds(update,dto.getIds());
  }

  @Override
  public List<RecordComTreeDto> queryComInfoByIdList(List<String> ids) {
    List<MdBusComponentInfoDetailDto> list = mdBusComponentInfoService.queryComInfoByIdList(ids);
    List<RecordComTreeDto> result = new ArrayList<>();
    for (MdBusComponentInfoDetailDto one : list) {
      result.add(dataTransCom(one));
    }
    return result;
  }

    @Override
    public Map<String, String> queryComNameByIdList(List<String> idList) {
      Map<String, String> comNameMap = new HashMap<>();
      List<MdBusComponentInfoDetailDto> list = mdBusComponentInfoService.queryComInfoByIdList(idList);
      if (CollUtil.isEmpty(list)){
        return comNameMap;
      }
      comNameMap = list.stream().collect(Collectors.toMap(MdBusComponentInfoDetailDto::getId,
              MdBusComponentInfoDetailDto::getComName));
      return comNameMap;
    }

    @Override
    public AdvancedQueryOptions advancedQueryOptions(String projectId) {
      AdvancedQueryOptions options = new AdvancedQueryOptions();
      options.setManagerList(new ArrayList<>());
      options.setCreatorList(new ArrayList<>());
      options.setUpdaterList(new ArrayList<>());
      List<String> mangerList = mdBusComponentInfoService.selectManagerByProject(projectId);
      Set<Long> userIds = new HashSet<>();
      if (!CollectionUtils.isEmpty(mangerList)) {
        mangerList.forEach(id -> {
          if (id.length() <= 20) {
            userIds.add(Long.valueOf(id));
          }
        });
      }
      List<String> creatorList = mdBusComponentInfoService.selectCreatorByProject(projectId);
      if (!CollectionUtils.isEmpty(creatorList)) {
        creatorList.forEach(id -> {
          if (id.length() <= 20) {
            userIds.add(Long.valueOf(id));
          }
        });
      }
      List<String> updaterList = mdBusComponentInfoService.selectUpdaterByProject(projectId);
      if (!CollectionUtils.isEmpty(updaterList)) {
        updaterList.forEach(id -> {
          if (id.length() <= 20) {
            userIds.add(Long.valueOf(id));
          }
        });
      }
      if (CollectionUtils.isEmpty(userIds)){
        return options;
      }
      List<UserDTO> userDTOS = monsterCommonFeignClient.getUserByIds(new ArrayList<>(userIds));
      userDTOS.forEach(user -> {
        if (mangerList.contains(user.getId().toString())) {
          options.getManagerList().add(UserOptions.userDTOtoUserOptions(user));
        }
        if (creatorList.contains(user.getId().toString())) {
          options.getCreatorList().add(UserOptions.userDTOtoUserOptions(user));
        }
        if (updaterList.contains(user.getId().toString())) {
          options.getUpdaterList().add(UserOptions.userDTOtoUserOptions(user));
        }
      });
      return options;
    }


  /**
   * 查询人名可带正则表达式
   * @param userName
   * @return
   */
  private List<String> getUserIds(String userName) {
    UserQueryDto example = new UserQueryDto();
    if(userName.contains(",")||userName.contains("，")){
      userName = userName.replace(",","|")
              .replace("，","|")
              .replace("(","\\(")
              .replace(")","\\)");
      example.setUserChnNames(userName);
    }else{
      example.setUserChnName(userName);
    }
    example.setTenantId(NKSecurityContext.getTenantId());
    List<String> userIds = platformFeignClient.selectUserId(example);
    if (userIds == null) {
      userIds = new ArrayList<>();
    }
    return userIds;
  }

  /**
   * 克隆单个组件
   * @param target
   * @return
   */
  private String copyByIdTool(MdBusComponentInfo target) {
    MdBusComponentInfo copy = mdBusComponentInfoService.findByPrimaryKey(target.getId());
    MdComponentParam copyParam = mdComponentParamService.findByPrimaryKey(target.getId());
    String newId = UUIDUtil.create32UUID();
    copy.setId(newId);
    copyParam.setId(newId);
    //处理名称问题
    target.setComName(copy.getComName());
    String newName = getComNewName(target);
    if(newName.length()> RuleDefinitionTool.getNameCopyLength()){
      return copy.getComName();
    }
    Integer scriptType = copy.getComType();
    FileBusinessTypeEnum businessCode = null;
    if (scriptType.equals(4) || scriptType.equals(5)) {
      businessCode = FileBusinessTypeEnum.MOBILE_RECORD_SCREENSHOT;
    } else if (scriptType.equals(2) || scriptType.equals(3)) {
      businessCode = FileBusinessTypeEnum.PC_RECORD_SCREENSHOT;
    }
    logger.info("copy组件类型：{}, 文件businessCode：{}", scriptType, businessCode);
    JSONObject jsonByFileId = scriptCaseUtils.getJsonByFileId(copy.getScriptContent());
    Map<String, String> oldPathAndNewPathMap = new HashMap<>();
    atuScriptInfoApiService.getIamgeUrlByJsonArray(copy.getId(), jsonByFileId.get("commands"), oldPathAndNewPathMap, true, businessCode);
    String path = scriptCaseUtils.generateScriptFileAndUploadByJson(jsonByFileId, copy.getId(), FileBusinessTypeEnum.BUSINESS_COMPONENT_SCRIPT);
    if(StringUtils.isNotEmpty(path)){
      copy.setComName(newName);
      copy.setTreeId(target.getTreeId());
      copy.setCreatedBy(NKSecurityContext.getUserId());
      copy.setCreatedTime(new Date());
      copy.setUpdatedBy(NKSecurityContext.getUserId());
      copy.setUpdatedTime(new Date());
      copy.setComVersion("");//克隆业务组件无版本号
      copy.setSharedFlag(0);//克隆组件默认未共享
      copy.setScriptContent(path);
      mdBusComponentInfoService.insert(copy);
      mdComponentParamService.insert(copyParam);
    }else{
      return "";
    }
    return null;
  }


  /**
   * 获取带后缀的名称
   * @param target
   * @return
   */
  public String getComNewName(MdBusComponentInfo target) {
    MdBusComponentInfo nameQuery = new MdBusComponentInfo();
    String name = target.getComName();
    name = name.replace("(","\\(")
            .replace(")","\\)")
            .replace("^","\\^")
            .replace("*","\\*")
            .replace("+","\\+")+"-副本(\\([0-9]{1,2}\\)$)";
    nameQuery.setComName(name);
    nameQuery.setTreeId(target.getTreeId());
    nameQuery.setTenantId(NKSecurityContext.getTenantId());
    nameQuery.setProjectId(target.getProjectId());

    String mdName  = mdBusComponentInfoService.getMaxCopyComName(nameQuery);
    int md = getMaxNum(mdName);
    return target.getComName()+"-副本("+ md +")";
  }

  private int getMaxNum(String getName){
    int last = 0;
    if (StringUtils.isEmpty(getName)) {
      last = 1;
    }else{
      String reg = ScriptConstant.NUM_REGEX;
      Pattern pattern = Pattern.compile(reg);
      Matcher matcher = pattern.matcher(getName);
      while (matcher.find()) {
        String value = matcher.group();
        int integer = Integer.parseInt(value.substring(1, value.length() - 1));
        last = integer+1;
      }
    }
    return last;
  }

  private RecordComTreeDto dataTransCom(MdBusComponentInfoDetailDto one){
    RecordComTreeDto dto = new RecordComTreeDto();
    dto.setTreeId(one.getId());
    dto.setTreeName(one.getComName());
    dto.setTreeAlias(one.getComName());
    dto.setComFlag(ScriptConstant.STR_ONE);//业务组件
    dto.setIsCom(ScriptConstant.STR_ONE);//组件
    dto.setIsLeaf(ScriptConstant.STR_ONE);//组件永远是叶子节节点
    dto.setMemo(one.getMemo());
    dto.setParamJson(one.getParamJson());
    dto.setVersion(one.getComVersion());
    dto.setScriptContent(one.getScriptContent());
    return dto;
  }
}
