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

import com.alibaba.fastjson.JSONObject;
import com.hzbank.testteam.autotest.dependencies.baseDefineDependency.entity.Environment;
import com.hzbank.testteam.autotest.dependencies.baseDefineDependency.exception.InvalidException;
import com.hzbank.testteam.autotest.dependencies.baseDefineDependency.vo.ResponseVO;
import net.northking.cctp.common.db.SqlOrderBy;
import net.northking.cctp.common.enums.FileBusinessTypeEnum;
import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.common.feign.ApiAtsEnviromentFeign;
import net.northking.cctp.common.http.ResultWrapper;
import net.northking.cctp.common.s3.FileDownloadException;
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.dataPool.constants.DataPoolConstant;
import net.northking.cctp.dataPool.db.entity.DataSetEnvRel;
import net.northking.cctp.dataPool.db.service.DataSetEnvRelService;
import net.northking.cctp.dataPool.dto.dataSets.*;
import net.northking.cctp.dataPool.enums.DataPoolError;
import net.northking.cctp.dataPool.feign.AttachmentFeignClient;
import net.northking.cctp.dataPool.feign.ProjectFeignClient;
import net.northking.cctp.dataPool.utils.EnvNameUtils;
import net.northking.cctp.dataPool.utils.MinioPathUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
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.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 数据集环境关联表服务实现类
 *
 * @author maven-cctp-plugin
 * @since 1.0
 */

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

  @Autowired
  private DataSetEnvRelService dataSetEnvRelService;
  @Autowired
  private ProjectFeignClient projectFeignClient;
  @Autowired
  private MinioPathUtils pathUtils;
  @Autowired
  private SimpleStorageService simpleStorageService;
  @Autowired
  private EnvNameUtils envNameUtils;

  @Autowired
  private ApiAtsEnviromentFeign apiAtsEnviromentFeign;
  @Autowired
  private AttachmentFeignClient attachmentFeignClient;


  @Override
  @Transactional(rollbackFor = Exception.class)
  public List<DataSetsSaveDto> queryList(DataSetEnvRelQueryDto queryDto) {
    //返回结果集
    List<DataSetsSaveDto> dataSetsSaveDtos=new ArrayList<>();
    //根据数据集id查关联表 1
    DataSetEnvRel dataSetEnvRel=new DataSetEnvRel();
    dataSetEnvRel.setDataSetId(queryDto.getDataSetId());
    SqlOrderBy sqlOrderBy=new SqlOrderBy();
    sqlOrderBy.asc("env_id");
    List<DataSetEnvRel> query = dataSetEnvRelService.query(dataSetEnvRel,sqlOrderBy);
    //跟据系统id查关联环境 调project的feign 2
    //去project服务写feign
    Long projectId = null;
    try {
      projectId = Long.valueOf(queryDto.getProId());
    } catch (NumberFormatException e) {
      logger.error("系统Id类型转换异常");
      throw new InvalidException("系统Id类型转换异常");
    }
    ResponseVO<List<Environment>> listResponseVO = apiAtsEnviromentFeign.listByProject(projectId);
    List<Environment> environmentList = listResponseVO.getData();
    Map<String, Environment> environmentMap = environmentList.stream().collect(Collectors.toMap(e -> e.getId().toString(), e -> e));
    List<String> envIds = environmentList.stream().map(e -> e.getId().toString()).collect(Collectors.toList());
    if (environmentList.size()==0){
      //删除当前数据集全部环境关联记录
      if (query.size()!=0){
        List<Object> ids = query.stream().map(DataSetEnvRel::getId).collect(Collectors.toList());
        dataSetEnvRelService.deleteByPrimaryKeys(ids);
        //是否删除文件服务器上的数据
      }
      return dataSetsSaveDtos;
    }
    if (query.size()!=0) {
      List<Object> delDsIds = new ArrayList<>();
      List<DataSetEnvRel> noDelDs = new ArrayList<>();
      //比较1和2
      for (DataSetEnvRel d : query) {
        if (!envIds.contains(d.getEnvId())) {
          delDsIds.add(d.getId());
        } else {
          noDelDs.add(d);
        }
      }
      // 如果1中存在2不存的环境的话删除1中相关信息
      if (delDsIds.size() != 0) {
        dataSetEnvRelService.deleteByPrimaryKeys(delDsIds);
        //是否删除对应的文件服务器中的json文件
      }
      // 筛选出2中存在1中不存在
      List<String> addEnvIds = new ArrayList<>();
      if (noDelDs.size() != 0) {
        List<String> noDelEnvIds = noDelDs.stream().map(DataSetEnvRel::getEnvId).collect(Collectors.toList());
        for (String envId : envIds) {
          if (!noDelEnvIds.contains(envId)) {
            addEnvIds.add(envId);
          }
        }
        if (addEnvIds.size() != 0) {//如果2中存在1中不存在的环境给1的file_addr加上赋值为与其他记录相同的头信息
          DataSetEnvRel dataSetEnvRelAdd = null;
          Integer seq = noDelDs.get(noDelDs.size() - 1).getSeq();
          String fileAddr = noDelDs.get(0).getFileAddr();
          String fileAddrAdd = "";
          //获取文件数据
          JSONObject data = downloadFile(fileAddr);
          DataSetsSaveDto dataSetsSaveDto = new DataSetsSaveDto();
          if (!ObjectUtils.isEmpty(data)) {
              dataSetsSaveDto = data.toJavaObject(DataSetsSaveDto.class);
              dataSetsSaveDto.setTableContent(null);
          }
          for (int i = 0; i < addEnvIds.size(); i++) {

            dataSetsSaveDto.setEnvId(addEnvIds.get(i));
            if(environmentMap.containsKey(addEnvIds.get(i))){
              dataSetsSaveDto.setEnvName(environmentMap.get(addEnvIds.get(i)).getName());
            }
            dataSetsSaveDtos.add(dataSetsSaveDto);

            dataSetEnvRelAdd = new DataSetEnvRel();
            dataSetEnvRelAdd.setDataSetId(queryDto.getDataSetId());
            dataSetEnvRelAdd.setEnvId(addEnvIds.get(i));
            dataSetEnvRelAdd.setId(UUIDUtil.create32UUID());
            dataSetEnvRelAdd.setCreatedBy(NKSecurityContext.getUserId());
            dataSetEnvRelAdd.setCreatedTime(new Date());
            dataSetEnvRelAdd.setTenantId(NKSecurityContext.getTenantId());
            dataSetEnvRelAdd.setSeq(seq + i + 1);
            //存储文件数据
            fileAddrAdd = uploadFile(dataSetsSaveDto, dataSetEnvRelAdd.getId(), FileBusinessTypeEnum.STATIC_DATA_SET_ENV);
            dataSetEnvRelAdd.setFileAddr(fileAddrAdd);
            dataSetEnvRelService.insert(dataSetEnvRelAdd);
          }
        }
        //封装反显数据
        DataSetsSaveDto dataSetsSaveVo = null;
        for (int i = 0; i < noDelDs.size(); i++) {
          if (StringUtils.hasText(noDelDs.get(i).getFileAddr())) {
            JSONObject data1 = downloadFile(noDelDs.get(i).getFileAddr());
            if (!ObjectUtils.isEmpty(data1)) {
              dataSetsSaveVo = data1.toJavaObject(DataSetsSaveDto.class);
              dataSetsSaveVo.setEnvId(noDelDs.get(i).getEnvId());
              if(environmentMap.containsKey(noDelDs.get(i).getEnvId())){
                dataSetsSaveVo.setEnvName(environmentMap.get(noDelDs.get(i).getEnvId()).getName());
              }
              dataSetsSaveDtos.add(dataSetsSaveVo);
            }
          }
        }
      }
    }
    else{
      //反显系统关联的环境名以及环境id
      DataSetsSaveDto dataSetsSaveDto = null;
      for (String envId:envIds){
        dataSetsSaveDto = new DataSetsSaveDto();
        dataSetsSaveDto.setEnvId(envId);
        if(environmentMap.containsKey(envId)){
          dataSetsSaveDto.setEnvName(environmentMap.get(envId).getName());
        }
          dataSetsSaveDtos.add(dataSetsSaveDto);
      }
    }
    return dataSetListSeq(envIds,dataSetsSaveDtos);
  }

  @Override
  public ResultWrapper<List<String>> saveBatch(DataSetEnvRelAddDto addDto) {
    ResultWrapper<List<String>> resultWrapper=new ResultWrapper<>();
    //用projectId调project服务的feign查系统关联的环境集合 1
    List<String> envIds = projectFeignClient.selectEnvIds(addDto.getProId());
    List<String> resultId = saveDataEnv(envIds, addDto);
    return resultWrapper.success(resultId);
  }

  @Transactional(rollbackFor = Exception.class)
  private List<String> saveDataEnv(List<String> envIds,DataSetEnvRelAddDto addDto){
    List<String> resultId=new ArrayList<>();
    //用dataSetId查数据集环境关联表获取相关关联记录 2
    DataSetEnvRel dataSetEnvRel=new DataSetEnvRel();
    dataSetEnvRel.setDataSetId(addDto.getDataSetId());
    SqlOrderBy sqlOrderBy=new SqlOrderBy();
    sqlOrderBy.asc("seq");
    List<DataSetEnvRel> query = dataSetEnvRelService.query(dataSetEnvRel,sqlOrderBy);
    //系统未关联环境,删除当前数据集关联环境的所有记录
    if (envIds.size()==0){
      if (query.size()!=0) {
        List<Object> ids = query.stream().map(DataSetEnvRel::getId).collect(Collectors.toList());
        dataSetEnvRelService.deleteByPrimaryKeys(ids);
      }
      throw new PlatformRuntimeException(DataPoolError.PROJECT_NO_REFER_ENV);
    }
    if (query.size()!=0) {
      //比较1和2
      List<DataSetEnvRel> delIds=new ArrayList<>();//系统已删除关联的环境id集合
      List<DataSetEnvRel> noDelQuery=new ArrayList<>();//1和2中均存在的
      for (int i = 0; i <query.size() ; i++) {
        if (!envIds.contains(query.get(i).getEnvId())){
          delIds.add(query.get(i));
        }else {
          noDelQuery.add(query.get(i));
        }
      }
      //2中存在1不存在的 删
      if (delIds.size()!=0){
        delIds.forEach(item -> {
          if (StringUtils.hasText(dataSetEnvRel.getFileAddr())) {
            deleteFile(dataSetEnvRel.getFileAddr());
          }
        });
        List<Object> collect = delIds.stream().map(DataSetEnvRel::getId).collect(Collectors.toList());
        dataSetEnvRelService.deleteByPrimaryKeys(collect);
        //是否需要补充删除文件服务器上的json文件
      }
      //2和1中都存在的 改
      if (noDelQuery.size()!=0){
        Map<String, DataSetEnvRel> noDelMap = noDelQuery.stream().collect(Collectors.toMap(DataSetEnvRel::getEnvId, e -> e));
        Set<String> noDelEnvIds = noDelMap.keySet();
        Map<String, List<DataSetEnvRel>> map = noDelQuery.stream().collect(Collectors.groupingBy(DataSetEnvRel::getEnvId));
        DataSetEnvRel update=null;
        DataSetsSaveDto updateSaveDto=null;
        for (DataSetEnvRelAddTmpDto d:addDto.getDataSetEnvRelAddTmpDto()) {
          if (noDelEnvIds.contains(d.getEnvId())){
            update=new DataSetEnvRel();
            update.setId(map.get(d.getEnvId()).get(0).getId());
            update.setUpdatedBy(NKSecurityContext.getUserId());
            update.setUpdatedTime(new Date());
            updateSaveDto=new DataSetsSaveDto();
            updateSaveDto.setDataSetId(addDto.getDataSetId());
            updateSaveDto.setTableContent(d.getTableContent());
            updateSaveDto.setTableHeader(d.getTableHeader());
            //更新到文件服务器
            DataSetEnvRel envRel = noDelMap.get(d.getEnvId());
            if (StringUtils.hasText(envRel.getFileAddr())) {
              deleteFile(envRel.getFileAddr());
            }
            String path = uploadFile(updateSaveDto, update.getId(), FileBusinessTypeEnum.STATIC_DATA_SET_ENV);
            update.setFileAddr(path);
            //更新到表
            resultId.add(map.get(d.getEnvId()).get(0).getId());
            dataSetEnvRelService.updateByPrimaryKey(update);
          }
        }
      }
      //筛选出1中存在2不存在的
      List<String> addEnvIds=new ArrayList<>();
      List<String> foundIds = query.stream().map(DataSetEnvRel::getEnvId).collect(Collectors.toList());
      for (String envId:envIds) {
        if (!foundIds.contains(envId)){
          addEnvIds.add(envId);
        }
      }
      //1中存在2不存在的 加
      if (addEnvIds.size()!=0){
        Integer seq=0;
        if (noDelQuery.size()!=0) {
          seq = noDelQuery.get(query.size() - 1).getSeq();
        }
        DataSetEnvRel dataSetEnvRelAdd=null;
        DataSetsSaveDto dataSetsSaveDto=null;
        for (DataSetEnvRelAddTmpDto d:addDto.getDataSetEnvRelAddTmpDto()) {
          if (addEnvIds.contains(d.getEnvId())) {
            dataSetEnvRelAdd = new DataSetEnvRel();
            dataSetEnvRelAdd.setEnvId(d.getEnvId());
            dataSetEnvRelAdd.setDataSetId(addDto.getDataSetId());
            dataSetEnvRelAdd.setTenantId(NKSecurityContext.getTenantId());
            dataSetEnvRelAdd.setCreatedTime(new Date());
            dataSetEnvRelAdd.setCreatedBy(NKSecurityContext.getUserId());
            String uuid = UUIDUtil.create32UUID();
            dataSetEnvRelAdd.setId(uuid);
            dataSetEnvRelAdd.setSeq(++seq);
            //上传数据到文件服务器
            dataSetsSaveDto = new DataSetsSaveDto();
            dataSetsSaveDto.setTableHeader(d.getTableHeader());
            dataSetsSaveDto.setTableContent(d.getTableContent());
            dataSetsSaveDto.setDataSetId(addDto.getDataSetId());
            String path = uploadFile(dataSetsSaveDto, dataSetEnvRelAdd.getId(), FileBusinessTypeEnum.STATIC_DATA_SET_ENV);
            dataSetEnvRelAdd.setFileAddr(path);
            //存记录到数据库
            resultId.add(uuid);
            dataSetEnvRelService.insert(dataSetEnvRelAdd);
          }
        }
      }
    }
    else {
      //直接新增
      DataSetsSaveDto dataSetsSaveDto=null;
      DataSetEnvRel dataSetEnvRelAdd=null;
      Integer count=1;
      for (DataSetEnvRelAddTmpDto d:addDto.getDataSetEnvRelAddTmpDto()) {
        if (envIds.contains(d.getEnvId())) {
          dataSetEnvRelAdd = new DataSetEnvRel();
          dataSetEnvRelAdd.setEnvId(d.getEnvId());
          dataSetEnvRelAdd.setDataSetId(addDto.getDataSetId());
          dataSetEnvRelAdd.setTenantId(NKSecurityContext.getTenantId());
          dataSetEnvRelAdd.setCreatedTime(new Date());
          dataSetEnvRelAdd.setCreatedBy(NKSecurityContext.getUserId());
          String uuid = UUIDUtil.create32UUID();
          dataSetEnvRelAdd.setId(uuid);
          dataSetEnvRelAdd.setSeq(count++);
          //上传数据到文件服务器
          dataSetsSaveDto = new DataSetsSaveDto();
          dataSetsSaveDto.setTableHeader(d.getTableHeader());
          dataSetsSaveDto.setTableContent(d.getTableContent());
          dataSetsSaveDto.setDataSetId(addDto.getDataSetId());

          String path = uploadFile(dataSetsSaveDto, dataSetEnvRelAdd.getId(), FileBusinessTypeEnum.STATIC_DATA_SET_ENV);
          dataSetEnvRelAdd.setFileAddr(path);
          //存记录到数据库
          resultId.add(uuid);
          dataSetEnvRelService.insert(dataSetEnvRelAdd);
        }
      }
    }
    return resultId;
  }

  private void deleteFile(String fileAddr) {
    String[] pathData = MinioPathUtils.idToPath(fileAddr);
    try {
      simpleStorageService.delete(pathData[0], "/" + pathData[1]);
    } catch (Exception e) {
      throw new PlatformRuntimeException(DataPoolError.FILE_DEL_ERROR);
    }
  }


  @Override
  public void exportExcel(HttpServletResponse response, DataSetEnvRelQueryDto dataSetEnvRelQueryDto) {
    try {
      XSSFWorkbook hssfWorkbook = getXSSFWorkbook(dataSetEnvRelQueryDto);
      setResponseHeader(response);
      ServletOutputStream outputStream = response.getOutputStream();
      hssfWorkbook.write(outputStream);
      outputStream.flush();
      outputStream.close();
    }catch (IOException e){
      logger.error(e.getMessage());
      throw new PlatformRuntimeException(DataPoolError.FILE_DOWNLOAD_ERROR);
    }
  }

  @Override
  public AtuScriptInputSetQuoteFieldDto selectDataUrlAndTreeName(AtuScriptInputSetQuoteFieldDto fieldDto) {
    AtuScriptInputSetQuoteFieldDto dto = dataSetEnvRelService.selectDataUrlAndTreeName(fieldDto);
    if (null!=dto){
      //拼接path
      int row = fieldDto.getRow() + 1;
      String path = dto.getFullName() + ":" + dto.getName() + "." + fieldDto.getColumn() + ".[" + row + "]";
      //获取最新value
      if (StringUtils.hasText(dto.getPath())){
        JSONObject jsonObject = downloadFile(dto.getPath());
        try{
          logger.info("脚本文件内容：jsonobject:{}",jsonObject.toJSONString());
          DataSetsSaveDto dataSetsSaveDto = jsonObject.toJavaObject(DataSetsSaveDto.class);
          Map<String, List<DataContentDto>> tableContent = dataSetsSaveDto.getTableContent();
          dto.setValue(tableContent.get(fieldDto.getColumn()).get(fieldDto.getRow()).getValue());
        }catch (Exception e){
          dto.setValue(null);
          logger.error("文件下载转换异常，e,{}",e);
        }
      }
      dto.setPath(path);
    }
    return dto;
  }

  @Override
  public Map<String, AtuScriptInputSetQuoteFeignDto> getDataSetFile(AtuDataSetFeignDto dto) {
    Map<String, AtuScriptInputSetQuoteFeignDto> resultMap = new HashMap<>();
    List<String> list = new ArrayList<>(dto.getDataSetList());
    List<AtuScriptInputSetQuoteFeignDto> dataSetList = dataSetEnvRelService.getDataSetFile(list, dto.getEnvId());
    if (dataSetList != null && dataSetList.size()>0) {
      for (AtuScriptInputSetQuoteFeignDto fieldDto : dataSetList) {
        resultMap.put(fieldDto.getSetId(),fieldDto);
      }
    }
    return resultMap;
  }

  private XSSFWorkbook getXSSFWorkbook(DataSetEnvRelQueryDto dataSetEnvRelQueryDto) {
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("sheet1");
    XSSFCellStyle cellStyle = workbook.createCellStyle();
    cellStyle.setAlignment(HorizontalAlignment.CENTER);
    XSSFCell cell = null;

    List<String> tableHeaders = dataSetEnvRelQueryDto.getTableHeaders();
    List<Map<String, Object>> tableContent = dataSetEnvRelQueryDto.getTableContent();

    if (null != tableHeaders && tableHeaders.size() > 0) {
      //表头填充
      XSSFRow row = sheet.createRow(0);
      for (int i = 0; i < tableHeaders.size(); i++) {
        cell = row.createCell(i);
        cell.setCellValue(tableHeaders.get(i));
        cell.setCellStyle(cellStyle);
      }
      if (null != tableContent && tableContent.size() > 0) {
        //表体填充
        for (int i = 1; i <= tableContent.size(); i++) {
          XSSFRow xssfRow = sheet.createRow(i);
          for (int j = 0; j < tableHeaders.size(); j++) {
            cell = xssfRow.createCell(j);
            Object obj = tableContent.get(i - 1).get(tableHeaders.get(j));
            if (obj != null) {
              cell.setCellValue(obj.toString());
            } else {
              cell.setCellValue("");
            }
            cell.setCellStyle(cellStyle);
          }
        }
      }
    }
    return workbook;
  }

  private void setResponseHeader(HttpServletResponse response) {
    try {
      String fileName="导出数据集名称";
      fileName= URLEncoder.encode(fileName,"utf8");
      response.reset();
      response.setCharacterEncoding("UTF-8");
      response.setContentType("application/vnd.ms-excel;charset=utf-8");
      response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
    }catch (Exception e){
      logger.error(e.getMessage());
    }
  }

  /**
   * 根据url下载文件
   * @param url
   * @return
   */
  private JSONObject downloadFile(String url) {
    String[] resultPath = pathUtils.idToPath(url);
    InputStream inputStream = null;
    JSONObject scriptData = null;
    try {
      inputStream = simpleStorageService.downloadAsStream(resultPath[0], "/" + resultPath[1]);
      scriptData = pathUtils.getFileContent(inputStream, JSONObject.class);
      return scriptData;
    } catch (FileDownloadException e) {
      logger.error("读取原文件失败，失败原因：", e);
      throw new PlatformRuntimeException(DataPoolError.FILE_DOWNLOAD_ERROR);
    } finally {
      if (null != inputStream) {
        try {
          inputStream.close();
        } catch (IOException e) {
          logger.error("",e);
        }
      }
    }
  }
  /**
   * 上传文件
   * @param scriptJsonStr
   * @return
   */
  private String uploadFile(Object scriptJsonStr, String objId, FileBusinessTypeEnum businessCode) {
    File file = pathUtils.objectToJsonFile(scriptJsonStr);
    try {
      NKFile nkFile = simpleStorageService.upload(NKSecurityContext.getTenantId(), file, objId, businessCode);
      String path = pathUtils.pathToId(NKSecurityContext.getTenantId(), nkFile.getId());
      return path;
    } catch (FileUploadException e) {
      logger.error("上传文件出错", e);
      throw new PlatformRuntimeException(DataPoolError.FILE_UPLOAD_ERROR);
    } finally {
      boolean delete = file.delete();
      if (!delete) {
        logger.error("删除文件失败");
      }
    }
  }

  private List<DataSetsSaveDto> dataSetListSeq(List<String> envList,List<DataSetsSaveDto> dtoList){
    List<DataSetsSaveDto> resultList = new ArrayList<>();
    for (String envId : envList) {
      for (DataSetsSaveDto dataSetsSaveDto : dtoList) {
        if (dataSetsSaveDto.getEnvId().equals(envId)){
          resultList.add(dataSetsSaveDto);
        }
      }
    }
    return resultList;
  }

  @Override
  public DataSetsSaveDto importExcel(MultipartFile file, String dataSetId, String envId, String tableHeader) {
    DataSetsSaveDto dataSetsSaveDto = new DataSetsSaveDto();
    if (file.isEmpty()) {
      throw new PlatformRuntimeException(DataPoolError.FILE_IS_NULL);
    }
    String name = file.getOriginalFilename();
    String[] tableHeaders = new String[0];
    int length = 0;
    if (tableHeader != null && !tableHeader.equals("")) {
      tableHeaders = tableHeader.split(",");
      length = tableHeaders.length;
    }
    if (name != null && !name.equals("")) {
      //表头信息列表
      String subStr = name.substring(name.lastIndexOf("."));
      if (subStr.equals(DataPoolConstant.FILE_XLS)) {
        dataSetsSaveDto = analysisExcelByXLS(file, length);
      } else if (subStr.equals(DataPoolConstant.FILE_XLSX)) {
        dataSetsSaveDto = analysisExcelByXLSX(file, length);
      } else {
        throw new PlatformRuntimeException(DataPoolError.FILE_IS_NOT_EXCEL);
      }
    } else {
      throw new PlatformRuntimeException(DataPoolError.FILE_NAME_IS_NULL);
    }

    int excelSize = dataSetsSaveDto.getTableHeader().size();

    if (length > excelSize) {
      throw new PlatformRuntimeException(DataPoolError.TABLE_HEADER_SIZE_UNEQULE);
    }
    for (int i = 0; i < length; i++) {
      //校验是否一致
      String dto = tableHeaders[i];
      DataHeaderDto headerDto = dataSetsSaveDto.getTableHeader().get(i);
      if (!headerDto.getName().equals(dto)) {
        throw new PlatformRuntimeException(DataPoolError.TABLE_HEADER_NAME_ERROR, i + 1, headerDto.getName(), dto);
      }
    }
    dataSetsSaveDto.setEnvId(envId);
    String envName = envNameUtils.getEnvName(envId);
    dataSetsSaveDto.setEnvName(envName);
    dataSetsSaveDto.setDataSetId(dataSetId);
    return dataSetsSaveDto;
  }


  private DataSetsSaveDto analysisExcelByXLSX(MultipartFile file,Integer headerSize) {
    DataSetsSaveDto resultDto = new DataSetsSaveDto();
    List<DataHeaderDto> excelHeaders = new ArrayList<>();
    Map<String, List<DataContentDto>> excelMap = new HashMap<>();
    XSSFWorkbook sheets = null;
    try {
      sheets = new XSSFWorkbook(file.getInputStream());
    } catch (IOException e) {
      throw new PlatformRuntimeException(DataPoolError.EXCEL_FILE_READ_ERROR);
    }
    //获取表头信息
    XSSFSheet sheet = sheets.getSheetAt(0);
    if (sheet == null) {
      throw new PlatformRuntimeException(DataPoolError.EXCEL_FISRT_SHEET_NULL);
    }
    XSSFRow rowHeader = sheet.getRow(0);
    Boolean checkTableHeader = false;
    if (rowHeader != null) {
      if (headerSize.equals(0)) {
        checkTableHeader = true;
        headerSize = Integer.parseInt(String.valueOf(rowHeader.getLastCellNum()));
      }
      for (int i = 0; i < headerSize; i++) {
        XSSFCell cell = rowHeader.getCell(i);
        if (cell != null && cell.getCellType() != CellType.BLANK) {
          cell.setCellType(CellType.STRING);
          DataHeaderDto headerDto = new DataHeaderDto();
          headerDto.setName(cell.getStringCellValue());
          excelHeaders.add(headerDto);
        } else {
          throw new PlatformRuntimeException(DataPoolError.EXCEL_HEADER_IS_NULL);
        }
      }
      if (checkTableHeader) {
        if (excelHeaders.size() > 1) {
          checkTableHeader(excelHeaders);
        }
      }
      //组装表体数据
      int rowNum = sheet.getLastRowNum() + 1;
      for (int i = 1; i < rowNum; i++) {
        XSSFRow row = sheet.getRow(i);
        for (int j = 0; j < headerSize; j++) {
          String headerName = excelHeaders.get(j).getName();
          List<DataContentDto> dtoList = excelMap.get(headerName);
          if (dtoList == null || dtoList.size() == 0) {
            dtoList = new ArrayList<>();
          }
          XSSFCell cell = row.getCell(j);
          DataContentDto contentDto = new DataContentDto();
          if (cell == null) {
            contentDto.setValue(null);
          } else if (cell.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            contentDto.setValue(sdf.format(cell.getDateCellValue()));
          } else {
            cell.setCellType(CellType.STRING);
            contentDto.setValue(cell.getStringCellValue());
          }
          dtoList.add(contentDto);
          excelMap.put(headerName, dtoList);
        }
      }
    }
    resultDto.setTableHeader(excelHeaders);
    resultDto.setTableContent(excelMap);
    return resultDto;
  }

  private DataSetsSaveDto analysisExcelByXLS(MultipartFile file,Integer headerSize) {
    DataSetsSaveDto resultDto = new DataSetsSaveDto();
    List<DataHeaderDto> excelHeaders = new ArrayList<>();
    Map<String, List<DataContentDto>> excelMap = new HashMap<>();
    HSSFWorkbook sheets = null;
    try {
      sheets = new HSSFWorkbook(file.getInputStream());
    } catch (IOException e) {
      throw new PlatformRuntimeException(DataPoolError.EXCEL_FILE_READ_ERROR);
    }
    //获取表头信息
    HSSFSheet sheet = sheets.getSheetAt(0);
    if (sheet == null) {
      throw new PlatformRuntimeException(DataPoolError.EXCEL_FISRT_SHEET_NULL);
    }
    HSSFRow rowHeader = sheet.getRow(0);
    Boolean checkTableHeader = false;
    if (rowHeader != null) {
      if (headerSize.equals(0)) {
        //校验表头是否存在重复数据
        checkTableHeader = true;
        headerSize = Integer.parseInt(String.valueOf(rowHeader.getLastCellNum()));
      }
      for (int i = 0; i < headerSize; i++) {
        HSSFCell cell = rowHeader.getCell(i);
        if (cell != null && cell.getStringCellValue() != null) {
          cell.setCellType(CellType.STRING);
          DataHeaderDto headerDto = new DataHeaderDto();
          headerDto.setName(cell.getStringCellValue());
          excelHeaders.add(headerDto);
        } else {
          throw new PlatformRuntimeException(DataPoolError.EXCEL_HEADER_IS_NULL);
        }
      }
      if (checkTableHeader) {
        if (excelHeaders.size() > 1) {
          checkTableHeader(excelHeaders);
        }
      }
      //组装表体数据
      int rowNum = sheet.getLastRowNum() + 1;
      for (int i = 1; i < rowNum; i++) {
        HSSFRow row = sheet.getRow(i);
        for (int j = 0; j < headerSize; j++) {
          String headerName = excelHeaders.get(j).getName();
          List<DataContentDto> dtoList = excelMap.get(headerName);
          if (dtoList == null || dtoList.size() == 0) {
            dtoList = new ArrayList<>();
          }
          HSSFCell cell = row.getCell(j);
          DataContentDto contentDto = new DataContentDto();
          if (cell == null) {
            contentDto.setValue(null);
          } else if (cell.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            contentDto.setValue(sdf.format(cell.getDateCellValue()));
          } else {
            cell.setCellType(CellType.STRING);
            contentDto.setValue(cell.getStringCellValue());
          }
          dtoList.add(contentDto);
          excelMap.put(headerName, dtoList);
        }
      }
    }
    resultDto.setTableHeader(excelHeaders);
    resultDto.setTableContent(excelMap);
    return resultDto;
  }

  private void checkTableHeader(List<DataHeaderDto> excelHeaders){
    List<String> nameList = new ArrayList<>();
    for (DataHeaderDto excelHeader : excelHeaders) {
      String headerName = excelHeader.getName();
      if (nameList.contains(headerName)){
        throw new PlatformRuntimeException(DataPoolError.EXCEL_HEADER_HAS_SAME);
      }
      nameList.add(headerName);
    }
  }
}