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

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import net.northking.cctp.common.db.BasicService;
import net.northking.cctp.common.db.Pagination;
import net.northking.cctp.common.db.SqlOrderBy;
import net.northking.cctp.common.db.annotation.DatabaseReadOnly;
import net.northking.cctp.common.db.annotation.DatabaseWriteOnly;
import net.northking.cctp.common.db.excel.AbstractExcelService;
import net.northking.cctp.common.db.excel.ExcelHeader;
import net.northking.cctp.common.enums.FileBusinessTypeEnum;
import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.common.http.QueryByPage;
import net.northking.cctp.common.s3.FileUploadException;
import net.northking.cctp.common.s3.NKFile;
import net.northking.cctp.common.s3.SimpleStorageService;
import net.northking.cctp.common.security.authentication.NKSecurityContext;
import net.northking.cctp.common.util.UUIDUtil;

import net.northking.cctp.scriptcase.bus.PlanRabbitMQPublisher;
import net.northking.cctp.scriptcase.constants.ScriptConstant;
import net.northking.cctp.scriptcase.db.entity.AtuCaseDataSet;
import net.northking.cctp.scriptcase.db.service.AtuCaseDataSetService;
import net.northking.cctp.scriptcase.db.service.AtuInputSetService;
import net.northking.cctp.scriptcase.db.entity.AtuInputSet;

import net.northking.cctp.scriptcase.db.service.AtuScriptVersionService;
import net.northking.cctp.scriptcase.dto.inputSet.*;
import net.northking.cctp.scriptcase.enums.ScriptCaseAppError;
import net.northking.cctp.scriptcase.feign.AttachmentFeignClient;
import net.northking.cctp.scriptcase.feign.DataMgrFeignClient;
import net.northking.cctp.scriptcase.feign.ProjectFeignClient;
import net.northking.cctp.scriptcase.tools.DataMgrUtils;
import net.northking.cctp.scriptcase.tools.DownloadFileUtils;
import net.northking.cctp.scriptcase.tools.EnvNameUtils;
import net.northking.cctp.scriptcase.tools.MinioPathUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.xssf.usermodel.*;
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.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * 输入项数据集服务实现类
 *
 * @author maven-cctp-plugin
 * @since 1.0
 */

@Service
@ConditionalOnMissingBean(name = "AtuInputSetApiServiceImpl")
public class AtuInputSetApiServiceImpl extends AbstractExcelService<AtuInputSet> implements AtuInputSetApiService
{
  /**
   * 日志
   */
  private final static Logger logger = LoggerFactory.getLogger(AtuInputSetApiServiceImpl.class);

  @Autowired
  private AtuInputSetService atuInputSetService;

  @Autowired
  private MinioPathUtils pathUtil;

  @Autowired
  private SimpleStorageService simpleStorageService;

  @Autowired
  private RedisTemplate redisTemplate;

  @Autowired
  private DataMgrFeignClient dataMgrFeignClient;

  @Autowired
  private PlanRabbitMQPublisher planRabbitMQPublisher;

  @Autowired
  private AtuCaseDataSetService atuCaseDataSetService;

  @Autowired
  private ProjectFeignClient projectFeignClient;

  @Autowired
  private DownloadFileUtils downloadFileUtils;

  @Autowired
  private DataMgrUtils dataMgrUtils;

  @Autowired
  private EnvNameUtils envNameUtils;

  @Autowired
  private AtuScriptVersionService atuScriptVersionService;
  @Autowired
  private AttachmentFeignClient attachmentFeignClient;

  //= Excel 导入导出相关代码 start ==================//
  @Override
  public BasicService<AtuInputSet> getService()
  {
    return this.atuInputSetService;
  }

  @Override
  public ExcelHeader[] excelHeaders()
  {
    ExcelHeader id = new ExcelHeader("主键", "id", String.class);
    ExcelHeader scriptId = new ExcelHeader("脚本id", "scriptId", String.class);
    ExcelHeader envId = new ExcelHeader("环境id", "envId", String.class);
    ExcelHeader version = new ExcelHeader("版本", "version", Integer.class);
    ExcelHeader dataUrl = new ExcelHeader("数据文件地址", "dataUrl", InputStream.class);
    ExcelHeader createdBy = new ExcelHeader("创建人", "createdBy", String.class);
    ExcelHeader createdTime = new ExcelHeader("创建时间", "createdTime", Date.class);
    ExcelHeader updatedBy = new ExcelHeader("更新人", "updatedBy", String.class);
    ExcelHeader updatedTime = new ExcelHeader("更新时间", "updatedTime", Date.class);
    return new ExcelHeader[]{};
  }

  /**
   * Excel导入，入库之前的处理
   * @param records 从Excel读取到的记录
   * @return 待入库的记录
   */
  @Override
  protected List<AtuInputSet> beforeInsertBatch(List<AtuInputSet> records)
  {
    for (AtuInputSet record : records)
    {
      record.setId(UUIDUtil.create32UUID());
    }
    return records;
  }

  /**
   * 写入Excel之前的处理<br>
   * 数据的特殊处理在此处加工处理
   *
   * @param record 来自数据库记录
   * @return 待写入Excel的记录
   */
  @Override
  protected AtuInputSet beforeWriteExcel(AtuInputSet record)
  {
    return record;
  }

  //= Excel 导入导出相关代码 end =======================//

  //= 增删改查 相关代码 start ==================//
  @Override
  @DatabaseReadOnly
  public Pagination<AtuInputSetDetailDto> pagingQuery(QueryByPage<AtuInputSetQueryDto> queryByPage)
  {
    return this.atuInputSetService.pagingQuery(queryByPage);
  }

  @Override
  @DatabaseWriteOnly
  public String add(AtuInputSetAddDto dto)
  {
    String uuid = UUIDUtil.create32UUID();
    AtuInputSet entity = new AtuInputSet();
    BeanUtils.copyProperties(dto, entity);
    entity.setId(uuid);
    this.atuInputSetService.insert(entity);
    return uuid;
  }

  @Override
  @DatabaseWriteOnly
  public Integer updateByPK(AtuInputSetUpdateDto dto) throws IllegalAccessException
  {
    AtuInputSet entity = new AtuInputSet();
    BeanUtils.copyProperties(dto, entity);
    return this.atuInputSetService.updateByPrimaryKey(entity);
  }

  @Override
  @DatabaseReadOnly
  public AtuInputSetDetailDto findByPK(String uuid)
  {
    AtuInputSet example = new AtuInputSet();
    example.setId(uuid);
    List<AtuInputSet> entitys = this.atuInputSetService.query(example);
    if (entitys.isEmpty())
    {
      return null;
    }

    AtuInputSetDetailDto dto = new AtuInputSetDetailDto();
    BeanUtils.copyProperties(entitys.get(0), dto);
    return dto;
  }

  @Override
  @DatabaseWriteOnly
  public Integer deleteByPK(String uuid)
  {
    AtuInputSet entity = new AtuInputSet();
    entity.setId(uuid);
    return this.atuInputSetService.deleteByExample(entity);
  }

  @Override
  public List<String> addBatch(List<AtuInputSetAddDto> batch)
  {
    List<String> result = new ArrayList<>();
    for (AtuInputSetAddDto dto : batch)
    {
      result.add(this.add(dto));
    }
    return result;
  }

  @Override
  public Integer updateBatch(List<AtuInputSetUpdateDto> batch) throws IllegalAccessException
  {
    int sum = 0;
    for (AtuInputSetUpdateDto dto : batch)
    {
      sum = sum + this.updateByPK(dto);
    }
    return sum;
  }

  @Override
  public Integer deleteBatch(List<Object> batch)
  {
    return this.atuInputSetService.deleteByPrimaryKeys(batch);
  }



  @Override
  public List<InputSet> saveInputSet(AtuInputSetSaveDto dto) {
    AtuCaseDataSet queryDto = new AtuCaseDataSet();
    queryDto.setScriptId(dto.getScriptId());
    queryDto.setLeaf(true);
    List<AtuCaseDataSet> queryList = this.atuCaseDataSetService.query(queryDto);
    if (queryList == null || queryList.size() == 0){
      throw new PlatformRuntimeException(ScriptCaseAppError.CASE_DATA_SET_IS_NULL);
    }
    if (StringUtils.isBlank(queryList.get(0).getVersion())) {
      throw new PlatformRuntimeException(ScriptCaseAppError.CASE_DATA_SET_VERSION_IS_NULL);
    }else if (!dto.getVersion().equals(queryList.get(0).getVersion())){
      throw new PlatformRuntimeException(ScriptCaseAppError.CASE_DATA_SET_VERSION_UPDATE);
    }
    List<InputSet> resultList = new ArrayList<>();
    if (StringUtils.isBlank(dto.getScriptId()) || CollectionUtils.isEmpty(dto.getInputSetList())) {
      return resultList;
    }
    // 保存修改人信息到atu_case_data_set
    String updateBy = NKSecurityContext.getUserId();
    AtuCaseDataSet atuCaseDataSet = atuCaseDataSetService.queryAtuCaseDataSetByScriptId(dto.getScriptId());
    if (atuCaseDataSet != null) {
      atuCaseDataSet.setUpdatedBy(updateBy);
      atuCaseDataSet.setUpdatedTime(new Date());
      atuCaseDataSetService.updateByPrimaryKey(atuCaseDataSet);
    }
    // 删除文件
    attachmentFeignClient.deleteFileByObjId(dto.getScriptId(), FileBusinessTypeEnum.INPUT_DATA_SET.getCode());
    for (InputSet inputSet : dto.getInputSetList()) {
      InputSet one = new InputSet();
      for (Map<String, Object> contentMap : inputSet.getTableContent()) {
        Object object = contentMap.get(ScriptConstant.SCRIPT_TEST_PURPOSE_ID);
        if (object == null) {
          contentMap.put(ScriptConstant.SCRIPT_TEST_PURPOSE_ID, UUIDUtil.create32UUID());
        }
      }
      JSONObject jsonObject = new JSONObject();
      jsonObject.put(ScriptConstant.SCRIPT_INPUT_VARIABLES,dto.getVariables());
      jsonObject.put(ScriptConstant.SCRIPT_INPUT_TABLE_HEADERS, dto.getTableHeader());
      jsonObject.put(ScriptConstant.SCRIPT_INPUT_TABLE_CONTENT, inputSet.getTableContent());
      AtuInputSet query = new AtuInputSet();
      query.setScriptId(dto.getScriptId());
      query.setEnvId(inputSet.getEnvId());
      List<AtuInputSet> queryResult = atuInputSetService.query(query);
      String dataUrl;
      if (queryResult.size() > 0) {
        //修改
        dataUrl = generateScriptFileAndUpload(jsonObject, dto.getScriptId(), FileBusinessTypeEnum.INPUT_DATA_SET);
        AtuInputSet target = queryResult.get(0);
        target.setDataUrl(dataUrl);
        this.atuInputSetService.updateByPrimaryKey(target);
        //添加静态数据引用关联
        dataMgrUtils.queryInputAndDataLink(inputSet.getTableContent(),inputSet.getEnvId(),queryResult.get(0).getId(),ScriptConstant.DATA_SET_LINK_BY_CASE);
        planRabbitMQPublisher.updatePlanStatusMQ(dto.getScriptId());
      } else {
        //新增
        dataUrl = generateScriptFileAndUpload(jsonObject, dto.getScriptId(), FileBusinessTypeEnum.INPUT_DATA_SET);
        AtuInputSet target = new AtuInputSet();
        String uuid = UUIDUtil.create32UUID();
        target.setId(uuid);
        target.setEnvId(inputSet.getEnvId());
        target.setScriptId(dto.getScriptId());
        target.setDataUrl(dataUrl);
        this.atuInputSetService.insert(target);
        //添加静态数据引用关联
        dataMgrUtils.queryInputAndDataLink(inputSet.getTableContent(),inputSet.getEnvId(),uuid,ScriptConstant.DATA_SET_LINK_BY_CASE);
      }
      one.setDataUrl(dataUrl);
      one.setEnvId(inputSet.getEnvId());
      resultList.add(one);
    }
    return resultList;
  }

  @Override
  public List<AtuInputSet> queryInputByEnvIdAndScriptId(AtuPlanInputQueryDto queryDto) {
    return this.atuInputSetService.queryInputByEnvIdAndScriptId(queryDto);
  }

  @Override
  public InputSetResultDto queryInputSetByCase(AtuInputSetCaseDto dto) {
    List<AtuInputSetResultDto> resultList = new ArrayList<>();
    AtuInputSet atuInputSet = new AtuInputSet();
    atuInputSet.setScriptId(dto.getScriptId());
    // 获取用例集下脚本输入项
    AtuCaseDataSet queryDto = new AtuCaseDataSet();
    queryDto.setScriptId(dto.getScriptId());
    queryDto.setLeaf(true);
    List<AtuCaseDataSet> setList = this.atuCaseDataSetService.query(queryDto);
    if (setList == null || setList.size() == 0) {
      throw new PlatformRuntimeException(ScriptCaseAppError.CASE_DATA_SET_IS_DELETE);
    }
    List<AtuInputSet> query = this.atuInputSetService.query(atuInputSet);
    // 获取系统环境关联关系
    List<String> envIds = projectFeignClient.selectEnvIds(dto.getProjectId());
    if (!CollectionUtils.isEmpty(query)) {
      for (AtuInputSet inputSet : query) {
        // 系统环境下的输入项才返回组装，否则不组装
        if (!CollectionUtils.isEmpty(envIds) && envIds.contains(inputSet.getEnvId())) {
          AtuInputSetResultDto resultDto = downloadFileUtils.downloadFile(inputSet.getDataUrl());//tableContent
          if (null != resultDto.getTableContent()) {
            List<Map<String, Object>> mapList = dataMgrUtils.dealWithQuoteFiled(resultDto.getTableContent(),inputSet.getEnvId());
            resultDto.setTableContent(mapList);
          }
          resultDto.setEnvId(inputSet.getEnvId());
          String envName = envNameUtils.getEnvName(inputSet.getEnvId());
          resultDto.setEnvName(envName);
          resultList.add(resultDto);
        }
      }
    }
    InputSetResultDto resultDto = new InputSetResultDto();
    //设置表数据
    if (resultList.size() > 0) {
      resultDto.setDtoList(resultList);
    } else {
      throw new PlatformRuntimeException(ScriptCaseAppError.FILE_GET_TABLE_CONTENT_ERROR);
    }
    //设置表头
    InputSetResultDto resultData = queryTableHeaders(resultList);
    if (resultData.getTableHeaders().size() > 0) {
      resultDto.setTableHeaders(resultData.getTableHeaders());
    } else {
      throw new PlatformRuntimeException(ScriptCaseAppError.FILE_GET_TABLE_HEARER_ERROR);
    }
    if (resultData.getVariables().size() > 0) {
      resultDto.setVariables(resultData.getVariables());
    } else {
      throw new PlatformRuntimeException(ScriptCaseAppError.FILE_GET_VARIABLES_ERROR);
    }
    return resultDto;
  }

    @Override
    public List<AtuInputSet> queryInputByEnvIdAndScriptIdMap(Map<String, List<String>> envScriptMap) {
      List<AtuInputSet> resultList = new ArrayList<>();
      envScriptMap.forEach((envId, scriptIdList) -> {
        AtuPlanInputQueryDto queryDto = new AtuPlanInputQueryDto();
        queryDto.setEnvIdList(CollUtil.newArrayList(envId));
        queryDto.setScriptIdList(scriptIdList);
        List<AtuInputSet> atuInputSets = this.atuInputSetService.queryInputByEnvIdAndScriptId(queryDto);
        if (CollUtil.isNotEmpty(atuInputSets)){
          resultList.addAll(atuInputSets);
        }
      });
      return resultList;
    }

  @Override
  public Boolean checkDataSetDelete(AtuInnputDataSetQueryDto queryDto) {
    AtuInputDataSetDto dataSetDto = new AtuInputDataSetDto();
    dataSetDto.setEnvId(queryDto.getEnvId());
    dataSetDto.setDataSetId(queryDto.getSetId());
    dataSetDto.setSetColumn(queryDto.getColumn());
    Integer integer = this.atuInputSetService.selectOneDataSetLink(dataSetDto);
    if (!integer.equals(0)){
      throw new PlatformRuntimeException(ScriptCaseAppError.DATA_SET_COLUMN_HAS_DATA);
    }
    return true;
  }

  @Override
  public List<AtuInputDataSetResultDto> selectLinkBySetId(List<String> setList) {
    return this.atuInputSetService.selectDataSetLink(setList);
  }

  @Override
  public void downloadInputTemplate(HttpServletResponse response, HttpServletRequest request, List<String> firstLine) {
    try {
      XSSFWorkbook hssfWorkbook = getXSSFWorkbook(firstLine, null);
      setResponseHeader(response,request,ScriptConstant.INPUT_SET_MODULE);
      ServletOutputStream outputStream = response.getOutputStream();
      hssfWorkbook.write(outputStream);
      outputStream.flush();
      outputStream.close();
    }catch (IOException e){
      logger.error(e.getMessage());
    }
  }

  @Override
  public void downloadInputData(HttpServletResponse response, HttpServletRequest request, AtuInputSetDownloadDto dto) {
    try {
      String envName = envNameUtils.getEnvName(dto.getEnvId());
      AtuCaseDataSet dataSet = this.atuCaseDataSetService.findByPrimaryKey(dto.getInputSetId());

      XSSFWorkbook hssfWorkbook = getOutputData(dto.getTitle(),null,envName, dto.getContent());
      String fileName = dataSet.getSetName() + ScriptConstant.FILE_INPUT_SET_END;
      setResponseHeader(response,request, fileName);
      ServletOutputStream outputStream = response.getOutputStream();
      hssfWorkbook.write(outputStream);
      outputStream.flush();
      outputStream.close();
    }catch (IOException e){
      logger.error(e.getMessage());
    }
  }

  @Override
  public String importSetExcel(MultipartFile file, AtuInputSetFileDto dto) {
    if (StringUtils.isBlank(dto.getScriptId())) {
      throw new PlatformRuntimeException(ScriptCaseAppError.SCRIPT_NULL_ERROR);
    }
    if (StringUtils.isBlank(dto.getEnvId())) {
      throw new PlatformRuntimeException(ScriptCaseAppError.ENV_ID_NULL_ERROR);
    }
    if (file.isEmpty()) {
      logger.error("文件不能为空！");
      throw new PlatformRuntimeException(ScriptCaseAppError.FILE_IS_NULL);
    }
    //校验导入数据
    //获取excel实例
    XSSFWorkbook sheets = null;
    try {
      sheets = new XSSFWorkbook(file.getInputStream());
    } catch (IOException e) {
      logger.error("", e);
      throw new PlatformRuntimeException(ScriptCaseAppError.EXCEL_FILE_READ_ERROR);
    }
    //1、校验导入数据表头是否为空
    //获取sheet
    XSSFSheet sheet = sheets.getSheetAt(0);
    //获取表头信息
    XSSFRow rowHeader = sheet.getRow(0);

    //获取列数
    int rows = 0;
    if (rowHeader != null) {
      rows = rowHeader.getPhysicalNumberOfCells();
    }
    //2、校验输入项表头是否为空
    if (dto.getTableHeaders() == null) {
      throw new PlatformRuntimeException(ScriptCaseAppError.TABLE_INPUT_SET_IS_NULL);
    }
    //3、判断列数是否少于表头列数 提示异常
    if (rows < dto.getTableHeaders().size()) {
      throw new PlatformRuntimeException(ScriptCaseAppError.TABLE_HEADER_SIZE_ERROR);
    }
    //4、校验表头跟导入的参数是否一致
    for (int i = 0; i < dto.getTableHeaders().size(); i++) {
      String headerName = dto.getTableHeaders().get(i).getName();
      if (rowHeader != null && rowHeader.getCell(i) != null) {
        String cellValue = rowHeader.getCell(i).getStringCellValue();
        if (!headerName.equals(cellValue)) {
          throw new PlatformRuntimeException(ScriptCaseAppError.TABLE_HEADER_NAME_ERROR, i + 1, cellValue, headerName);
        }
      }
    }
    //5、导入的表头列长度大于输入项表头长度 校验是否为空格 空就不处理 不为空就提示用户删除对应的值
    if (rows > dto.getTableHeaders().size()) {
      for (int i = dto.getTableHeaders().size(); i < rows; i++) {
        if (rowHeader.getCell(i) != null && !rowHeader.getCell(i).getStringCellValue().equals("")) {
          throw new PlatformRuntimeException(ScriptCaseAppError.TABLE_HEADER_HAS_VALUE, i + 1, rowHeader.getCell(i).getStringCellValue());
        }
      }
    }

    // 判断测试轮次数据是否存在重复数据
    Set<String> rowSet = new HashSet<>();
    Map<String, String> dataMap = new HashMap<>();
    //根据行数遍历
    for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
      XSSFRow xssfRow = sheet.getRow(i);
      //当前行数
      int row = i + 1;
      if (xssfRow != null && xssfRow.getCell(0) != null) {
        XSSFCell cell = xssfRow.getCell(0);
        //设置单元格类型
        cell.setCellType(CellType.STRING);
        //判空
        if (StringUtils.isBlank(cell.getStringCellValue())) {
          throw new PlatformRuntimeException(ScriptCaseAppError.IMPORT_SCRIPT_INPUT_SET_NULL, row);
        }
        int length = cell.getStringCellValue().length();
        //判断长度是否大于30
        if (length > 30) {
          throw new PlatformRuntimeException(ScriptCaseAppError.IMPORT_SCRIPT_INPUT_SET_TOO_LONG, row, length);
        }
        //判断是否重名
        if (dataMap.get(cell.getStringCellValue()) != null) {
          rowSet.add(dataMap.get(cell.getStringCellValue()));
          rowSet.add(String.valueOf(row));
        }
        dataMap.put(cell.getStringCellValue(), String.valueOf(row));
      } else {
        throw new PlatformRuntimeException(ScriptCaseAppError.IMPORT_SCRIPT_INPUT_SET_NULL, row);
      }
    }
    if (rowSet.size() > 0) {
      StringBuffer errorData = new StringBuffer();
      rowSet.forEach(one -> {
        errorData.append(one).append(",");
      });
      errorData.deleteCharAt(errorData.length() - 1);
      throw new PlatformRuntimeException(ScriptCaseAppError.IMPORT_SCRIPT_INPUT_SET_SAME, errorData.toString());
    }
    //解析excel文件内容
    JSONObject jsonObject = new JSONObject();
    List<Map<String, Object>> tableContents = new ArrayList<>();
    Map<String, Object> map = null;
    //从第二行开始
    for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
      map = new HashMap<>();
      XSSFRow row = sheet.getRow(i);
      for (int j = 0; j < dto.getTableHeaders().size(); j++) {
        XSSFCell cell = row.getCell(j);
        if (cell == null) {
          map.put(dto.getTableHeaders().get(j).getName(), null);
        } else {
          cell.setCellType(CellType.STRING);
          map.put(dto.getTableHeaders().get(j).getName(), cell.getStringCellValue());
        }
      }
      tableContents.add(map);
    }
    jsonObject.put(ScriptConstant.SCRIPT_INPUT_TABLE_CONTENT, tableContents);
    //插入文件服务器minio
    String result = insertToMinio(jsonObject, dto.getScriptId(), FileBusinessTypeEnum.INPUT_DATA_SET);
    //更新到脚本信息表
    AtuInputSet atuInputSet = new AtuInputSet();
    atuInputSet.setScriptId(dto.getScriptId());
    atuInputSet.setEnvId(dto.getEnvId());
    List<AtuInputSet> query = this.atuInputSetService.query(atuInputSet);
    if (query.size() > 0) {
      query.get(0).setDataUrl(result);
      this.atuInputSetService.updateByPrimaryKey(query.get(0));
      planRabbitMQPublisher.updatePlanStatusMQ(dto.getScriptId());
    } else {
      AtuInputSet set = new AtuInputSet();
      set.setId(UUIDUtil.create32UUID());
      set.setScriptId(dto.getScriptId());
      set.setEnvId(dto.getEnvId());
      set.setDataUrl(result);
      this.atuInputSetService.insert(set);
    }

    //放回输入项文件地址
    return result;
  }

  @Override
  public InputSetResultDto queryInputData(String scriptId, Boolean flag) {
    List<AtuInputSetResultDto> resultList = new ArrayList<>();
    AtuInputSet dto = new AtuInputSet();
    dto.setScriptId(scriptId);
    SqlOrderBy sqlOrderBy=new SqlOrderBy();
    sqlOrderBy.asc(ScriptConstant.ORDER_BY_ENV);
    //输入项信息
    List<AtuInputSet> query = this.atuInputSetService.query(dto,sqlOrderBy);
    //用例集信息
    AtuCaseDataSet caseDataSet = this.atuCaseDataSetService.findByPrimaryKey(scriptId);
    //环境信息
    List<String> envIds = projectFeignClient.queryEnvListSeq(caseDataSet.getProjectId());
    if (query.size() > 0) {
      if (flag) {
        if (envIds != null && envIds.size() > 0) {
          List<String> setEnvList = new ArrayList<>();
          query.forEach(one -> {
            setEnvList.add(one.getEnvId());
          });
          for (String envId : envIds) {
            if (setEnvList.contains(envId)) {
              for (AtuInputSet inputSet : query) {
                if (envId.equals(inputSet.getEnvId())) {
                  AtuInputSetResultDto resultDto = downloadFileUtils.downloadFile(inputSet.getDataUrl());//tableContent
                  logger.info("============>下载文件内容为:" + resultDto.toString());
                  if (null != resultDto.getTableContent()) {
                    List<Map<String, Object>> mapList = dataMgrUtils.dealWithQuoteFiled(resultDto.getTableContent(), inputSet.getEnvId());
                    resultDto.setTableContent(mapList);
                  }
                  resultDto.setEnvId(inputSet.getEnvId());
                  String envName = envNameUtils.getEnvName(inputSet.getEnvId());
                  resultDto.setEnvName(envName);
                  resultList.add(resultDto);
                }
              }
            } else {
              AtuInputSetResultDto resultDto = new AtuInputSetResultDto();
              resultDto.setEnvId(envId);
              String envName = envNameUtils.getEnvName(envId);
              resultDto.setEnvName(envName);
              resultList.add(resultDto);
            }
          }

        }
      }else {
        AtuInputSet inputSet = query.get(0);
        AtuInputSetResultDto resultDto = downloadFileUtils.downloadFile(inputSet.getDataUrl());
        logger.info("============>下载文件内容为:" + resultDto.toString());
        resultList.add(resultDto);
      }
    }
    InputSetResultDto resultDto = new InputSetResultDto();
    if (flag) {
      resultDto = queryTableHeaders(resultList);
    }
    resultDto.setDtoList(resultList);
    return resultDto;
  }

  private InputSetResultDto queryTableHeaders(List<AtuInputSetResultDto> list) {
    List<String> tableHeaders = new ArrayList<>();
    List<Map<String,Object>> variables = new ArrayList<>();
    if (list != null && list.size() > 0) {
      AtuInputSetResultDto resultDto = list.get(0);
      if (null != resultDto.getTableHeader() && resultDto.getTableHeader().size() > 0) {
        tableHeaders = resultDto.getTableHeader();
      }
      if (resultDto.getVariables() != null && resultDto.getVariables().size()>0) {
        variables = resultDto.getVariables();
      }
    }
    InputSetResultDto dto = new InputSetResultDto();
    dto.setTableHeaders(tableHeaders);
    dto.setVariables(variables);
    return dto;
  }

  public XSSFWorkbook getXSSFWorkbook (List<String> title, XSSFWorkbook workbook){
    if (null==workbook){
      workbook=new XSSFWorkbook();
    }
    XSSFSheet sheet1 = workbook.createSheet(ScriptConstant.INPUT_SET_IMPORT_MODULE);
    XSSFRow row = sheet1.createRow(0);
    XSSFCellStyle cellStyle = workbook.createCellStyle();
    cellStyle.setAlignment(HorizontalAlignment.CENTER);
    XSSFCell cell=null;
    for (int i=0;i<title.size();i++){
      cell = row.createCell(i);
      cell.setCellValue(title.get(i));
      cell.setCellStyle(cellStyle);
    }
    return workbook;
  }


  public XSSFWorkbook getOutputData (List<String> title, XSSFWorkbook workbook,String envName,List<Map<String,Object>> content){
    if (null==workbook){
      workbook=new XSSFWorkbook();
    }
    //表头
    XSSFSheet sheet = workbook.createSheet(envName);
    XSSFRow row = sheet.createRow(0);
    XSSFCellStyle cellStyle = workbook.createCellStyle();
    cellStyle.setAlignment(HorizontalAlignment.CENTER);
    XSSFCell cell=null;
    for (int i=0;i<title.size();i++){
      cell = row.createCell(i);
      cell.setCellValue(title.get(i));
      cell.setCellStyle(cellStyle);
    }
    for (int i = 0; i < content.size(); i++) {
      Map<String, Object> map = content.get(i);
      row = sheet.createRow(i+1);
      for (int j = 0; j < title.size(); j++) {
        XSSFCell rowCell = row.createCell(j);
        String data = "";
        Object object = map.get(title.get(j));
        if (object != null){
          data = object.toString();
        }
        rowCell.setCellValue(data);
        rowCell.setCellStyle(cellStyle);
      }
    }
    return workbook;
  }

  public void setResponseHeader(HttpServletResponse response, HttpServletRequest request,String name)  {
    try {
      String fileName=name;
      fileName= URLEncoder.encode(fileName,ScriptConstant.UTF);
      response.reset();
      response.setCharacterEncoding(ScriptConstant.STR_ENCODE);
      response.setContentType(ScriptConstant.APPLICATION_CHARSET);
      response.setHeader(ScriptConstant.CONTENT_DISPOSITION,ScriptConstant.FILE_NAME+fileName+ScriptConstant.FILE_XLSX);
    }catch (Exception e){
      logger.error(e.getMessage());
    }
  }



    /**
   * 生成文件并上传
   * @param scriptJsonStr
   * @return
   */
  private String generateScriptFileAndUpload(Object scriptJsonStr, String objId, FileBusinessTypeEnum businessCode) {
    File file = MinioPathUtils.objectToJsonFile(scriptJsonStr);
    try {
      NKFile nkFile = simpleStorageService.upload(NKSecurityContext.getTenantId(), file, objId, businessCode);
      return MinioPathUtils.pathToId(NKSecurityContext.getTenantId(), nkFile.getId());
    } catch (FileUploadException e) {
      logger.error("上传脚本文件出错", e);
    } finally {
      boolean delete = file.delete();
      if (!delete) {
        logger.error("删除文件失败");
      }
    }
    return null;
  }

  private String insertToMinio(JSONObject object, String objId, FileBusinessTypeEnum businessCode) {
    File nkFile = MinioPathUtils.objectToJsonFile(object);
    NKFile upload = null;
    try {
      upload = simpleStorageService.upload(NKSecurityContext.getTenantId(), nkFile, objId, businessCode);
    } catch (FileUploadException e) {
      logger.error("",e);
    }
    String result = null;
    if (upload != null) {
      result = MinioPathUtils.pathToId(NKSecurityContext.getTenantId(), upload.getId());
    }
    return result;
  }

}
