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

import com.hzbank.testteam.autotest.dependencies.baseDefineDependency.constants.BaseDefineDependencyConstants;
import com.hzbank.testteam.autotest.dependencies.baseDefineDependency.dto.TagDto;
import com.hzbank.testteam.autotest.dependencies.baseDefineDependency.exception.InvalidException;
import com.hzbank.testteam.autotest.dependencies.baseDefineDependency.form.TagForm;
import com.hzbank.testteam.autotest.dependencies.baseDefineDependency.vo.ResponseVO;
import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.executePlan.constants.MsgConstant;
import net.northking.cctp.executePlan.db.dao.AtuPlanInfoDao;
import net.northking.cctp.executePlan.db.entity.AtuPlanInfo;
import net.northking.cctp.executePlan.dto.execplanTag.AtuExecplanTagAddDto;
import net.northking.cctp.executePlan.exception.ExecPlanError;
import net.northking.cctp.executePlan.feign.ApiTagService;
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.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 执行计划标签表服务实现类
 *
 * @author maven-cctp-plugin
 * @since 1.0
 */

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


  @Autowired
  private AtuPlanInfoDao atuPlanInfoDao;

  @Autowired
  private ApiTagService apiTagService;


  @Override
  public ResponseVO<Integer> addExecplanTagList(AtuExecplanTagAddDto addDto) {
    //获取参数
    List<String> execplanIdList = addDto.getExecplanIdList();
    List<String> tagNameList = addDto.getTagNameList();
    //校验参数是否为空
    if (CollectionUtils.isEmpty(execplanIdList)) {
      throw new PlatformRuntimeException(ExecPlanError.EXECPLAN_ID_IS_NULL);
    }
    //获取执行计划信息
    List<AtuPlanInfo> execplanInfoList = atuPlanInfoDao.queryPlanInfoByIds(execplanIdList);
    Integer num = 0;
    StringBuilder sb = new StringBuilder();
    for (AtuPlanInfo item : execplanInfoList) {
      TagForm form = new TagForm();
      form.setObjectId(item.getId());
      form.setTags(tagNameList);
      form.setType(4); // UI计划
      try {
        form.setProjectId(Long.valueOf(item.getProjectId()));
      } catch (NumberFormatException e) {
        logger.error("系统Id转为Long类型异常，执行计划Id：{}, 执行计划系统Id：{}", item.getId(), item.getProjectId(), e);
      }
      ResponseVO responseVO = apiTagService.saveTags(form);
      if (BaseDefineDependencyConstants.SYSTEM_RESPONSE_CODE_SUCCESS.equals(responseVO.getCode())) {
        num ++;
      } else {
        sb.append(item.getPlanName()).append(",");
      }
    }
    ResponseVO<Integer> responseVO = new ResponseVO<>();
    if (!num.equals(execplanInfoList.size())){
      responseVO.setCode(BaseDefineDependencyConstants.RESPONSE_CODE_INVALID_REFRESH);
      responseVO.setData(num);
      sb.setLength(sb.length() - 1);
      String msg = MsgConstant.RESPONSE_VO_EXECUTE_PLAN +"：" + sb + MsgConstant.RESPONSE_VO_ADD_TAGS_FAILURE;
      responseVO.setMessage(msg);
    } else {
      responseVO.setCode(BaseDefineDependencyConstants.SYSTEM_RESPONSE_CODE_SUCCESS);
      responseVO.setData(num);
      responseVO.setMessage(MsgConstant.RESPONSE_VO_ADD_TAGS_SUCCESSFULLY);
    }
    return responseVO;
  }

  @Override
  public List<TagDto> queryExecplanTag(String execplanId) {
    //判断执行计划是否存在
    AtuPlanInfo atuPlanInfo = atuPlanInfoDao.findByPrimaryKey(execplanId);
    if (null == atuPlanInfo) {
      throw new InvalidException(BaseDefineDependencyConstants.RESPONSE_CODE_INVALID_REFRESH, "该执行计划不存在或已被删除");
    }
    return apiTagService.listTagByObjectId(execplanId);
  }

  @Override
  public Integer deleteByExecplanIdAndTagId(String execplanId, Long tagId) {
    //判断删除参数是否存在
    if(StringUtils.isEmpty(execplanId)||StringUtils.isEmpty(tagId)){
      throw new PlatformRuntimeException(ExecPlanError.DELETE_EXECPLANTAG_ERROR);
    }
    AtuPlanInfo atuPlanInfo = atuPlanInfoDao.findByPrimaryKey(execplanId);
    if (null == atuPlanInfo || atuPlanInfo.getDeleted()) {
      throw new InvalidException(BaseDefineDependencyConstants.RESPONSE_CODE_INVALID_REFRESH, "该执行计划不存在或已被删除");
    }
    ResponseVO<Integer> responseVO = apiTagService.removeById(tagId);
    if (!BaseDefineDependencyConstants.SYSTEM_RESPONSE_CODE_SUCCESS.equals(responseVO.getCode())) {
      throw new InvalidException("删除标签失败");
    }
    return 1;
  }

}
