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

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.UserOptions;
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.security.authentication.NKSecurityContext;
import net.northking.cctp.scriptcase.bus.NoticeRabbitMQPublisher;
import net.northking.cctp.scriptcase.constants.ScriptConstant;
import net.northking.cctp.scriptcase.db.entity.LibraryBusComInfo;
import net.northking.cctp.scriptcase.db.entity.MdComponentParam;
import net.northking.cctp.scriptcase.db.service.LibraryBusComInfoService;
import net.northking.cctp.scriptcase.db.service.LibraryBusComTreeService;
import net.northking.cctp.scriptcase.db.service.MdComponentParamService;
import net.northking.cctp.scriptcase.dto.comLib.LibraryBusComCheckDto;
import net.northking.cctp.scriptcase.dto.comLib.LibraryBusComInfoAddDto;
import net.northking.cctp.scriptcase.dto.comLib.LibraryBusComInfoDetailDto;
import net.northking.cctp.scriptcase.dto.comLib.LibraryBusComInfoQueryDto;
import net.northking.cctp.scriptcase.enums.ScriptCaseAppError;
import net.northking.cctp.scriptcase.feign.PlatformFeignClient;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.util.*;
import java.util.stream.Collectors;

/**
 * 业务组件库组件列表服务实现类
 *
 * @author maven-cctp-plugin
 * @since 1.0
 */

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

  @Autowired
  private LibraryBusComInfoService libraryBusComInfoService;

  @Autowired
  private LibraryBusComTreeService libraryBusComTreeService;
  @Autowired
  private MdComponentParamService mdComponentParamService;
  @Autowired
  private PlatformFeignClient platformFeignClient;
  @Autowired
  private EntityNameCache entityNameCache;
  @Autowired
  private NoticeRabbitMQPublisher noticeRabbitMQPublisher;
  @Autowired
  MonsterCommonFeignClient monsterCommonFeignClient;
  @Override
  @DatabaseReadOnly
  public Pagination<LibraryBusComInfoDetailDto> pagingQuery(QueryByPage<LibraryBusComInfoQueryDto> queryByPage)
  {
    LibraryBusComInfoQueryDto query = queryByPage.getQuery();
    query.setTenantId(NKSecurityContext.getTenantId());
    // 处理树目录
    if (!StringUtils.isEmpty(query.getTreeId())) {
      if (!ScriptConstant.DATA_FIRST_NODE.equals(query.getTreeId())) {
        List<String> treeIds = libraryBusComTreeService.getChildTreeIds(query.getTreeId());
        query.setTreeIds(treeIds);
      }
      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);
    }

    //处理排序问题
    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);
    }

    Pagination<LibraryBusComInfoDetailDto> pagination = libraryBusComInfoService.pagingQueryNew(queryByPage);
    if (pagination.getRecords().size() > 0) {
      List<LibraryBusComInfoDetailDto> records = pagination.getRecords();
      List<Object> ids = new ArrayList<>();
      for (LibraryBusComInfoDetailDto record : records) {
        ids.add(record.getId());
      }
      List<MdComponentParam> paramList =  mdComponentParamService.findByPrimaryKeys(ids);
      Map<String,MdComponentParam> map = new HashMap<>();
      paramList.forEach(one->map.put(one.getId(),one));
      for (LibraryBusComInfoDetailDto record : records) {
        record.setComJson(map.get(record.getId()).getComJson());
        record.setParamJson(map.get(record.getId()).getParamJson());
        record.setProjectId(entityNameCache.translateById(EntityNameCatalog.MONSTER_SYSTEM.name(),record.getProjectId()));
        record.setUpdatedBy(entityNameCache.translateById(EntityNameCatalog.MONSTER_USER.name(), record.getUpdatedBy()));
        record.setCreatedBy(entityNameCache.translateById(EntityNameCatalog.MONSTER_USER.name(), record.getCreatedBy()));
      }
    }
    return pagination;
  }

  @Override
  @Transactional
  public Integer insertLibComByBatch(List<LibraryBusComInfoAddDto> comList,String treeId) {
    List<String> nameList = new ArrayList<>();
    comList.forEach(name->nameList.add(name.getComName()));
    String projectId = comList.get(0).getProjectId();
    List<String> repeatList = libraryBusComInfoService.checkRepeatName(projectId,nameList,treeId);
    if (repeatList.size()>0) {
      throw new PlatformRuntimeException(ScriptCaseAppError.LIB_COM_NAME_EXIT,repeatList.get(0));
    }
    if (!(libraryBusComTreeService.findByPrimaryKey(treeId).getIsLeaf()==1)) {
      throw new PlatformRuntimeException(ScriptCaseAppError.LIB_TREE_NOT_LEAF);
    }
    //校验通过 数据入库
    List<LibraryBusComInfo> infoList = new ArrayList<>();
    for (LibraryBusComInfoAddDto one : comList) {
      LibraryBusComInfo info = new LibraryBusComInfo();
      info.setId(one.getId());
      info.setIsDeleted(0);
      info.setTreeId(treeId);
      info.setComName(one.getComName());
      info.setComType(one.getComType());
      info.setProjectId(one.getProjectId());
      infoList.add(info);
    }
    libraryBusComInfoService.insertByBatch(infoList);

    return infoList.size();
  }

  @Override
  public int deleteByIds(List<String> ids) {
    List<Object> idList = new ArrayList<>(ids);
    libraryBusComInfoService.deleteByPrimaryKeys(idList);
    return idList.size();
  }

  @Override
  public int checkByIds(LibraryBusComCheckDto target) {
    LibraryBusComInfo info = new LibraryBusComInfo();
    if (target.getLibStatus()!=1) {
      info.setIsDeleted(1);//不通过即删除
      info.setLibStatus(0);//只审核未审核数据
    }else{
      info.setLibStatus(0);//通过
      info.setIsDeleted(0);//只审核未审核数据
    }
    String idStr = libraryBusComInfoService.updateByIdList(info,target.getIds());
    if(idStr==null || idStr.length()<32) return 0;
    return idStr.split(",").length;
  }
    /**
     * 获取高级查询筛选项
     * @return
     */
    @Override
    public AdvancedQueryOptions advancedQueryOptions() {
      AdvancedQueryOptions options = new AdvancedQueryOptions();
      options.setCreatorList(new ArrayList<>());
      List<String> creatorList = libraryBusComInfoService.selectCreator();
      Set<Long> userIds = new HashSet<>();
      if (!CollectionUtils.isEmpty(creatorList)) {
        creatorList.forEach(id -> {
          if (id.length() <= 20) {
            userIds.add(Long.valueOf(id));
          }
        });
      }
      List<UserDTO> userDTOS = monsterCommonFeignClient.getUserByIds(new ArrayList<>(userIds));
      userDTOS.forEach(user -> {
        if (creatorList.contains(user.getId().toString())) {
          options.getCreatorList().add(UserOptions.userDTOtoUserOptions(user));
        }
      });
      return options;
    }


    /**
   * 查询人名可带正则表达式
   * @param userName
   * @return
   */
  private List<String> getUserIds(String userName) {
    List<String> userIds = new ArrayList<>();
    Map<String, Object> params = new HashMap<>();
    params.put("employeeName", userName);
    params.put("deleted", 0);
    List<UserDTO> userDTOS = monsterCommonFeignClient.selectByMap(params);
    if (!CollectionUtils.isEmpty(userDTOS)) {
      userIds = userDTOS.stream().map(UserDTO::getId).map(String::valueOf).collect(Collectors.toList());
    }
    return userIds;
  }
}
