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

import net.northking.cctp.common.security.authentication.NKSecurityContext;
import net.northking.cctp.common.util.UUIDUtil;

import net.northking.cctp.scriptcase.db.service.HisUseComponentService;
import net.northking.cctp.scriptcase.db.entity.HisUseComponent;

import net.northking.cctp.scriptcase.dto.component.*;
import net.northking.cctp.scriptcase.feign.PlatformFeignClient;
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 java.util.*;

/**
 * 历史使用组件列表服务实现类
 *
 * @author maven-cctp-plugin
 * @since 1.0
 */

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

  @Autowired
  private HisUseComponentService hisUseComponentService;
  @Autowired
  private PlatformFeignClient platformFeignClient;
  @Autowired
  private MdBusComponentInfoApiService mdBusComponentInfoApiService;


  @Override
  @Transactional
  public List<RecordComTreeDto> getHisUseComList(RecordComTreeQueryDto query) {
    //获取列表根据业务和基础的区别分别进行查询
    HisUseComponent huc = new HisUseComponent();
    huc.setTenantId(NKSecurityContext.getTenantId());
    huc.setProjectId(query.getProjectId());
    huc.setRecordType(query.getRecordType());
    huc.setCreatedBy(NKSecurityContext.getUserId());
    List<HisUseComponent> hucList = hisUseComponentService.query(huc);
    List<String> busId = new ArrayList<>();
    List<String> basId = new ArrayList<>();
    for (HisUseComponent one : hucList) {
      if(one.getComType()==0){//基础
        basId.add(one.getComId());
      }else{//业务组件
        busId.add(one.getComId());
      }
    }
    Map<String,RecordComTreeDto> tool = new HashMap<>();
    if(basId.size()>0){
      //发送feing查询基础组件
      List<RecordComTreeDto> baseList = platformFeignClient.getComInfoByIdList(basId).getData();
      if (baseList != null) {
        for (RecordComTreeDto one : baseList) {
          if (one.getLibraryStatus()!=1) {
            //禁用基础组件从例是使用中去掉
            tool.put(one.getTreeId(),one);
          }
        }
      }
    }
    if (busId.size()>0) {
      //查询业务组件service
      List<RecordComTreeDto> busList = mdBusComponentInfoApiService.queryComInfoByIdList(busId);
      for (RecordComTreeDto one : busList) {
        tool.put(one.getTreeId(),one);
      }
    }
    List<HisUseComponent> inList = new ArrayList<>();
    List<RecordComTreeDto> result = new ArrayList<>();
    Map<String,Integer> deleteTool = new HashMap<>();
    int i=0;
    for (HisUseComponent his : hucList) {
      if(tool.containsKey(his.getComId())){
        result.add(tool.get(his.getComId()));
        his.setOrderSeq(i);
        inList.add(his);
        i++;
      }else{
        deleteTool.put(his.getId(),his.getOrderSeq());
      }
    }
    //清除失效历史组件超过三个失效则全量重置，少于三个则循环重置顺序号
    if(deleteTool.size()>2){
      hisUseComponentService.deleteByExample(huc);
      if(inList.size()>0){
        hisUseComponentService.insertByBatch(inList);
      }
    }else{
      for (String id : deleteTool.keySet()) {
        huc.setOrderSeq(deleteTool.get(id));
        hisUseComponentService.reduceOrderSeqByUser(huc);
        hisUseComponentService.deleteByPrimaryKey(id);
      }
    }

    return result;
  }

  @Override
  @Transactional
  public Integer saveHisUseCom(HisUseComponentAddDto dto) {
    //判断是否存在过，存在则挪到第一位
    HisUseComponent insert  = new HisUseComponent();
    BeanUtils.copyProperties(dto,insert);
    HisUseComponent check = new HisUseComponent();
    check.setTenantId(NKSecurityContext.getTenantId());
    check.setProjectId(dto.getProjectId());
    check.setRecordType(dto.getRecordType());
    check.setCreatedBy(NKSecurityContext.getUserId());
    check.setComId(dto.getComId());
    List<HisUseComponent> hucList = hisUseComponentService.query(check);
    if(hucList==null || hucList.size()<1){
      //先将整体编号提升一位
      HisUseComponent huc = new HisUseComponent();
      huc.setTenantId(NKSecurityContext.getTenantId());
      huc.setProjectId(dto.getProjectId());
      huc.setRecordType(dto.getRecordType());
      huc.setCreatedBy(NKSecurityContext.getUserId());
      hisUseComponentService.addOrderSeqByUser(huc);
      //删除第十一个
      huc.setOrderSeq(10);
      hisUseComponentService.deleteByExample(huc);
      insert.setOrderSeq(0);
      insert.setId(UUIDUtil.create32UUID());
      hisUseComponentService.insert(insert);
    }else{
      //已存在提升至第一个
      //找到的组件前面的组件整体往后挪一位
      HisUseComponent huc = new HisUseComponent();
      huc.setTenantId(NKSecurityContext.getTenantId());
      huc.setProjectId(dto.getProjectId());
      huc.setRecordType(dto.getRecordType());
      huc.setCreatedBy(NKSecurityContext.getUserId());
      huc.setOrderSeq(hucList.get(0).getOrderSeq());
      hisUseComponentService.addOrderSeqByUser(huc);
      //将找到的组件提到第一位
      HisUseComponent update = new HisUseComponent();
      update.setId(hucList.get(0).getId());
      update.setOrderSeq(0);
      hisUseComponentService.updateByPrimaryKey(update);
    }
    //插入最新
    return 1;
  }
}
