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

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.db.BasicDao;
import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.common.saas.db.TenantEntityService;
import net.northking.cctp.scriptcase.db.dao.AtuScriptInfoDao;
import net.northking.cctp.scriptcase.db.dao.AtuScriptTagDao;
import net.northking.cctp.scriptcase.db.entity.AtuSceneInfo;
import net.northking.cctp.scriptcase.db.entity.AtuScriptInfo;
import net.northking.cctp.scriptcase.db.entity.AtuScriptTag;
import net.northking.cctp.scriptcase.db.service.AtuSceneInfoService;
import net.northking.cctp.scriptcase.db.service.AtuScriptTagService;
import net.northking.cctp.scriptcase.dto.atuScript.atuScriptTag.AtuScriptTagAddDto;
import net.northking.cctp.scriptcase.enums.ErrorMessage;
import net.northking.cctp.scriptcase.feign.ApiTagService;
import net.northking.cctp.scriptcase.feign.PlatformFeignClient;
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.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;


/**
 * 脚本标签表
 *
 * <p>文件内容由代码生成器产生，请不要手动修改！ <br>
 * createdate:  2022-10-18 17:29:31  <br>
 * @author:  maven-cctp-plugin  <br>
 * @since:  1.0 <br>
 */
@Service
@ConditionalOnMissingBean(name = "AtuScriptTagServiceImpl")
public class AtuScriptTagServiceImpl extends TenantEntityService<AtuScriptTag> implements AtuScriptTagService
{
  private static final Logger logger = LoggerFactory.getLogger(AtuScriptTagServiceImpl.class);

  @Autowired
  private AtuScriptInfoDao atuScriptInfoDao;

  @Autowired
  private PlatformFeignClient platformFeignClient;

  private final AtuScriptTagDao atuScriptTagDao;

  public AtuScriptTagServiceImpl(AtuScriptTagDao atuScriptTagDao) {this.atuScriptTagDao = atuScriptTagDao;}

  public BasicDao<AtuScriptTag> getDao() {return atuScriptTagDao;}

  public AtuScriptTag createEntity() { return new AtuScriptTag();}

  @Autowired
  private AtuSceneInfoService atuSceneInfoService;

  @Autowired
  private ApiTagService apiTagService;



  @Override
  @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public ResponseVO<Integer> addScriptTagList(AtuScriptTagAddDto addDto) {
    List<String> scriptIdList = addDto.getScriptIdList();
    List<String> tagNameList = addDto.getTagNameList();
    List<AtuScriptTag> newData = new ArrayList<>();
    //校验脚本是否存在
    if (CollectionUtils.isEmpty(scriptIdList)) {
      throw new PlatformRuntimeException(new ErrorMessage("请选择待打标签脚本"));
    }
    //获取脚本信息
    List<AtuScriptInfo> scriptInfoList = atuScriptInfoDao.queryScriptByIds(scriptIdList);
    Integer num = 0;
    StringBuilder sb = new StringBuilder();
    for (AtuScriptInfo item : scriptInfoList) {
      TagForm form = new TagForm();
      form.setObjectId(item.getId());
      form.setTags(tagNameList);
      form.setType(3); // 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.getScriptName()).append(",");
      }
    }
    ResponseVO<Integer> responseVO = new ResponseVO<>();
    if (!num.equals(scriptInfoList.size())){
      responseVO.setCode(BaseDefineDependencyConstants.RESPONSE_CODE_INVALID_REFRESH);
      responseVO.setData(num);
      sb.setLength(sb.length() - 1);
      String msg = "脚本：" + sb + "添加标签失败";
      responseVO.setMessage(msg);
    } else {
      responseVO.setCode(BaseDefineDependencyConstants.SYSTEM_RESPONSE_CODE_SUCCESS);
      responseVO.setData(num);
      responseVO.setMessage("脚本添加标签成功");
    }
    return responseVO;
  }

  @Override
  @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public Integer deleteScriptTag(String scriptId, Long tagId) {
    AtuScriptInfo atuScriptInfo = atuScriptInfoDao.findByPrimaryKey(scriptId);
    if (null == atuScriptInfo || atuScriptInfo.getIsDeleted().equals("1")) {
      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;
  }

  @Override
  @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public List<TagDto> queryScriptTag(String scriptId) {
    List<TagDto> res = new ArrayList<>();
    // 场景脚本直接返回空标签数组
    AtuSceneInfo sceneInfo = atuSceneInfoService.findByIndexByPkScriptId(scriptId);
    if (null != sceneInfo) {
      return res;
    }
    AtuScriptInfo scriptInfo = atuScriptInfoDao.findByPrimaryKey(scriptId);
    if (null == scriptInfo || scriptInfo.getIsDeleted().equals("1")) {
      throw new InvalidException(BaseDefineDependencyConstants.RESPONSE_CODE_INVALID_REFRESH, "该脚本不存在或已被删除");
    }
    return apiTagService.listTagByObjectId(scriptId);
  }

}

