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

import cn.hutool.json.JSONUtil;
import net.northking.cctp.common.cache.EntityNameCache;
import net.northking.cctp.common.cache.EntityNameCatalog;
import net.northking.cctp.common.util.DateUtil;
import net.northking.cctp.executePlan.api.service.AtuPlanInfoApiService;
import net.northking.cctp.executePlan.api.third.devops.dto.DevopsCaseInfoDto;
import net.northking.cctp.executePlan.api.third.devops.dto.DevopsDoExecplanParamDto;
import net.northking.cctp.executePlan.api.third.devops.dto.DevopsExecplanInfoResultDto;
import net.northking.cctp.executePlan.api.third.devops.dto.DevopsProExecplanInfoDto;
import net.northking.cctp.executePlan.constants.PlanConstant;
import net.northking.cctp.executePlan.db.entity.AtuPlanBatch;
import net.northking.cctp.executePlan.db.entity.AtuPlanInfo;
import net.northking.cctp.executePlan.db.service.AtuPlanBatchService;
import net.northking.cctp.executePlan.db.service.AtuPlanInfoService;
import net.northking.cctp.executePlan.db.service.AtuPlanTaskService;
import net.northking.cctp.executePlan.dto.planInfo.AtuPlanInfoDetailDto;
import net.northking.cctp.executePlan.dto.planInfo.AtuPlanInfoQueryDto;
import net.northking.cctp.executePlan.dto.planInfo.AtuPlanRunDto;
import net.northking.cctp.executePlan.dto.planTask.AtuPlanTaskPageDto;
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 java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author maven-cctp-plugin
 * @since 1.0
 */

@Service
@ConditionalOnMissingBean(name = "DevopsServiceImpl")
public class DevopsServiceImpl  implements DevopsService
{
  /**
   * 日志
   */
  private final static Logger logger = LoggerFactory.getLogger(DevopsServiceImpl.class);
  @Autowired
  private AtuPlanInfoService atuPlanInfoService;
  @Autowired
  private EntityNameCache entityNameCache;
  @Autowired
  private AtuPlanInfoApiService atuPlanInfoApiService;
  @Autowired
  private AtuPlanBatchService atuPlanBatchService;
  @Autowired
  private AtuPlanTaskService atuPlanTaskService;
  @Override
  public List<DevopsProExecplanInfoDto> getExecplanListByProjectId(List<String> productIdList) {
    //查询数据
    AtuPlanInfoQueryDto selectParamAtuPlanInfoQueryDto = new AtuPlanInfoQueryDto();
    selectParamAtuPlanInfoQueryDto.setProjectList(productIdList);
    List<AtuPlanInfoDetailDto> tempResultAtuPlanInfoDetailDtos = atuPlanInfoService.queryPlanInfo(selectParamAtuPlanInfoQueryDto);
    //构建返回对象
    List<DevopsProExecplanInfoDto> resultDevopsProExecplanInfoDtoList = new ArrayList<>();
    Map<String, List<AtuPlanInfoDetailDto>> dtoMapKeyToProjectId = tempResultAtuPlanInfoDetailDtos.stream().collect(Collectors.groupingBy(AtuPlanInfoDetailDto::getProjectId));
    for(String key:dtoMapKeyToProjectId.keySet()){
      //构建返回实体
      DevopsProExecplanInfoDto resultBuildDto = new DevopsProExecplanInfoDto();
      AtuPlanInfoDetailDto tempIndex0Dto = dtoMapKeyToProjectId.get(key).get(0);
      //系统名称
      resultBuildDto.setProjectName(entityNameCache.translateById(EntityNameCatalog.MONSTER_SYSTEM, tempIndex0Dto.getProjectId()));
      //系统id
      resultBuildDto.setProjectId(tempIndex0Dto.getProjectId());
      //执行计划集合
      List<DevopsExecplanInfoResultDto> execplanList = new ArrayList<>();
      dtoMapKeyToProjectId.get(key).stream().forEach(item->{
        DevopsExecplanInfoResultDto resultDto = new DevopsExecplanInfoResultDto();
        //执行计划id
        resultDto.setPlanId(item.getId());
        //执行计划名称
        resultDto.setPlanName(item.getPlanName());
        execplanList.add(resultDto);
      });
      resultBuildDto.setExecplanList(execplanList);
      //塞入结果
      resultDevopsProExecplanInfoDtoList.add(resultBuildDto);
    }
    return resultDevopsProExecplanInfoDtoList;
  }

  @Override
  public void doExecplanByThirdPlatforn(DevopsDoExecplanParamDto doExecplanParamDto) {
    //build 入参
    AtuPlanRunDto atuPlanRunDto = new AtuPlanRunDto();
    atuPlanRunDto.setPlanId(doExecplanParamDto.getExecplanId());
    atuPlanRunDto.setTriggerType(PlanConstant.TRIGGER_TYPE_DEVOPS);
    atuPlanRunDto.setExecutedBy(doExecplanParamDto.getExecMan());
    atuPlanRunDto.setBatchId(doExecplanParamDto.getDevopsExecUuid());
    try{
      atuPlanInfoApiService.run(atuPlanRunDto);
    }catch (Exception e){
      throw new RuntimeException("执行计划执行失败"+e.getMessage());
    }
  }

  @Override
  public DevopsExecplanInfoResultDto getExecplanResultInfo(DevopsDoExecplanParamDto doExecplanParamDto) {
    DevopsExecplanInfoResultDto resultDto = new DevopsExecplanInfoResultDto();
    //请求uuid = 系统内批次id 按照我们系统batchid生成规则生成uuid

    AtuPlanBatch tempResultAtuPlanBatchDto = atuPlanBatchService.findByPrimaryKey(doExecplanParamDto.getDevopsExecUuid());
    //脚本总数
    resultDto.setTasktotal(tempResultAtuPlanBatchDto.getTaskTotal());
    //脚本成功数
    resultDto.setSuccessNum(tempResultAtuPlanBatchDto.getSuccessNum());
    //脚本失败数
    resultDto.setFailNum(tempResultAtuPlanBatchDto.getExecFailNum());
    //脚本取消数
    resultDto.setCancelNum(tempResultAtuPlanBatchDto.getCancelNum());
    //脚本超时数
    resultDto.setTimeoutNum(tempResultAtuPlanBatchDto.getTimeoutNum());
    //执行时间
    resultDto.setExecTime(DateUtil.toYearMonthDay24HourMinSecond(tempResultAtuPlanBatchDto.getStartTime()));
    //执行状态 0-等待中，1-执行中，2-已完成，3-已取消
    resultDto.setExecState(tempResultAtuPlanBatchDto.getStatus());
    //执行计划id
    resultDto.setPlanId(tempResultAtuPlanBatchDto.getPlanId());

    //查询计划名称
    String planId = tempResultAtuPlanBatchDto.getPlanId();
    AtuPlanInfo tempResultAtuPlanInfoDto = atuPlanInfoService.findByPrimaryKey(planId);
    resultDto.setPlanName(tempResultAtuPlanInfoDto.getPlanName());

    //Case集合信息
    List<DevopsCaseInfoDto> resultCaseList = new ArrayList<>();
    String batchId = doExecplanParamDto.getDevopsExecUuid();

    List<AtuPlanTaskPageDto> result = this.atuPlanTaskService.queryCaseListByBatchId(batchId);
    logger.info("查询的case集合有" +result.size()+"个"+ JSONUtil.toJsonStr(result));
    result.stream().forEach(item->{
      DevopsCaseInfoDto resultCaseDto = new DevopsCaseInfoDto();
      resultCaseDto.setCaseName(item.getCaseName());
      resultCaseDto.setCaseNo(item.getCaseNo());
      resultCaseDto.setCaseResult(item.getStatus());
      resultCaseDto.setCaseType(item.getCaseType());
      resultCaseDto.setScriptId(item.getScriptId());
      resultCaseDto.setScriptName(item.getScriptName());
      resultCaseList.add(resultCaseDto);
    });
    resultDto.setCaseList(resultCaseList);

    return resultDto;
  }

}
