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

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
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.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.dto.AssociatedFilesDto;
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.QueryByPage;
import net.northking.cctp.common.http.ResultWrapper;
import net.northking.cctp.common.s3.*;
import net.northking.cctp.common.security.authentication.NKSecurityContext;
import net.northking.cctp.common.util.UUIDUtil;
import net.northking.cctp.scriptcase.constants.ScriptConstant;
import net.northking.cctp.scriptcase.db.entity.AtuInputSet;
import net.northking.cctp.scriptcase.db.entity.AtuScriptInputSet;
import net.northking.cctp.scriptcase.db.service.AtuInputSetService;
import net.northking.cctp.scriptcase.db.service.AtuScriptInputSetService;
import net.northking.cctp.scriptcase.dto.atuscriptrecord.*;
import net.northking.cctp.scriptcase.dto.casedesign.TableHeader;
import net.northking.cctp.scriptcase.dto.inputSet.AtuInputSetResultDto;
import net.northking.cctp.scriptcase.enums.ErrorMessage;
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.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.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.transaction.annotation.Transactional;
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 = "AtuScriptInputSetApiServiceImpl")
public class AtuScriptInputSetApiServiceImpl implements AtuScriptInputSetApiService {
    /**
     * 日志
     */
    private final static Logger logger = LoggerFactory.getLogger(AtuScriptInputSetApiServiceImpl.class);

    @Autowired
    private AtuScriptInputSetService atuScriptInputSetService;
    @Autowired
    private ProjectFeignClient projectFeignClient;

    @Autowired
    private SimpleStorageService simpleStorageService;

    @Autowired
    private MinioPathUtils pathUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DataMgrFeignClient dataMgrFeignClient;

    @Autowired
    private AtuInputSetService atuInputSetService;

    @Autowired
    private EnvNameUtils envNameUtils;

    @Autowired
    private DownloadFileUtils downloadFileUtils;

    @Autowired
    private DataMgrUtils dataMgrUtils;

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

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


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

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

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

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

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

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

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

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

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AtuScriptInputSetResultDto queryAtuScriptInputSets(AtuScriptInputSetQueryDto atuScriptInputSetQueryDto) {
        List<JSONObject> jsonList = new ArrayList<>();
        //根据系统id调feign查询关联的环境属性集合 1
        Long projectId = null;
        try {
            projectId = Long.valueOf(atuScriptInputSetQueryDto.getProId());
        } catch (NumberFormatException e) {
            logger.error("系统Id类型转换异常", e);
        }
        ResponseVO<List<Environment>> listResponseVO = apiAtsEnviromentFeign.listByProject(projectId);
        Map<String, Environment> environmentMap = listResponseVO.getData().stream().collect(Collectors.toMap(e -> e.getId().toString(), e -> e));
        Set<String> keySet = environmentMap.keySet();
        List<String> envIds = keySet.stream().sorted(Comparator.comparingLong(Long::parseLong)).collect(Collectors.toList());
        if (envIds.size() != 0) {
            //根据脚本id查脚本输入项数据集草稿表关联表中的环境属性集合 2
            AtuScriptInputSet atuScriptInputSet = new AtuScriptInputSet();
            atuScriptInputSet.setScriptId(atuScriptInputSetQueryDto.getScript());
            SqlOrderBy sqlOrderBy = new SqlOrderBy();
            sqlOrderBy.asc(ScriptConstant.ORDER_BY_ENV);
            List<AtuScriptInputSet> atuScriptInputSets = atuScriptInputSetService.query(atuScriptInputSet, sqlOrderBy);
            if (atuScriptInputSets.size() != 0) {
                //如果存在
                //比较 1和2
                List<AtuScriptInputSet> delIds = new ArrayList<>();
                List<AtuScriptInputSet> noDelObjs = new ArrayList<>();
                for (AtuScriptInputSet a : atuScriptInputSets) {
                    if (!envIds.contains(a.getEnvId())) {//2中存在1中不存在的
                        delIds.add(a);
                    } else {//1和2中共同存在的
                        noDelObjs.add(a);
                    }
                }
                //2中存在1中不存在的 删脚本输入项数据集草稿表关联表中对应的记录
                if (delIds.size() != 0) {
                    List<String> deletedFileIds = delIds.stream().map(item -> "/" + MinioPathUtils.idToPath(item.getDataUrl())[1]).collect(Collectors.toList());
                    associatedFileObjId(deletedFileIds, "-1");
                    atuScriptInputSetService.deleteByPrimaryKeys(delIds.stream().map(AtuScriptInputSet::getId).collect(Collectors.toList()));
                }
                //1和2中共同存在的直接查
                List<Map<String,Object>> maps = new ArrayList<>();
                if (noDelObjs.size() != 0) {
                    for (AtuScriptInputSet inputSet : noDelObjs) {
                        if (StringUtils.isNotBlank(inputSet.getDataUrl())) {
                            JSONObject jsonObject = downloadScriptFile(inputSet.getDataUrl());
                            //添加返回结果集
                            jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_ID, inputSet.getEnvId());
                            Environment environment = environmentMap.get(inputSet.getEnvId());
                            String envName = environment == null ? "" : environment.getName();
                            jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_NAME,envName);

                            Object tableContent = jsonObject.get(ScriptConstant.SCRIPT_INPUT_TABLE_CONTENT);
                            if (null != tableContent && !Objects.equals(tableContent, "")) {
                                List<Map<String, Object>> objectList = JSON.parseObject(tableContent.toString(), new TypeReference<List<Map<String, Object>>>() {
                                });
                                //处理引用型数据
                                List<Map<String, Object>> mapList = dataMgrUtils.dealWithQuoteFiled(objectList, inputSet.getEnvId());
                                jsonObject.put(ScriptConstant.SCRIPT_INPUT_TABLE_CONTENT, mapList);
                                maps.addAll(objectList);
                            }
                            jsonList.add(jsonObject);
                        }
                    }
                }
                //筛选出1中存在2中不存在的
                List<String> refEnvIds = atuScriptInputSets.stream().map(AtuScriptInputSet::getEnvId).collect(Collectors.toList());
                List<String> addEnvIds = new ArrayList<>();
                for (String envId : envIds) {
                    if (!refEnvIds.contains(envId)) {
                        addEnvIds.add(envId);
                    }
                }
                if (addEnvIds.size() != 0) {//1中存在2中不存在的 新增脚本输入项数据集草稿表关联表中对应的记录 其中data_url字段值赋值为其同其他在1和2中都存在的data_url的头信息
                    AtuScriptInputSet atuScriptInputSetAdd = null;
                    JSONObject jsonObject = new JSONObject();
                    String path = null;
                    if (maps.size() != 0) {
                        //上传文件
                        Map map = maps.get(0);
                        List<String> tableHeaders = new ArrayList<>();
                        for (Object a : map.keySet()) {
                            tableHeaders.add(a.toString());
                        }
                        jsonObject.put(ScriptConstant.SCRIPT_INPUT_TABLE_HEADERS, tableHeaders);
                        path = generateScriptFileAndUpload(jsonObject, atuScriptInputSetQueryDto.getScript(), FileBusinessTypeEnum.COMMON_SCRIPT_INPUT_DATA_SET);
                    }
                    //插入
                    for (String envId : addEnvIds) {
                        JSONObject clone = jsonObject.clone();
                        clone.put(ScriptConstant.SCRIPT_INPUT_ENV_ID, envId);
                        Environment environment = environmentMap.get(envId);
                        String envName = environment == null ? "" : environment.getName();
                        clone.put(ScriptConstant.SCRIPT_INPUT_ENV_NAME,envName);
                        jsonList.add(clone);
                        if (path != null) {
                            atuScriptInputSetAdd = new AtuScriptInputSet();
                            atuScriptInputSetAdd.setId(UUIDUtil.create32UUID());
                            atuScriptInputSetAdd.setScriptId(atuScriptInputSetQueryDto.getScript());
                            atuScriptInputSetAdd.setEnvId(envId);
                            atuScriptInputSetAdd.setCreatedBy(NKSecurityContext.getUserId());
                            atuScriptInputSetAdd.setCreatedTime(new Date());
                            atuScriptInputSetAdd.setDataUrl(path);
                            atuScriptInputSetService.insert(atuScriptInputSetAdd);
                        }
                    }

                }
            } else {
                //如果不存在 去查脚本输入项数据集关联表环境属性集合 3
                AtuInputSet atuInputSet = new AtuInputSet();
                atuInputSet.setScriptId(atuScriptInputSetQueryDto.getScript());
                List<AtuInputSet> atuInputSets = atuInputSetService.query(atuInputSet, sqlOrderBy);
                //还不存在 直接返回
                if (atuInputSets.size() != 0) {
                    //存在 1和3共同存在的直接查
                    for (AtuInputSet inputSet : atuInputSets) {
                        if (envIds.contains(inputSet.getEnvId())) {
                            if (StringUtils.isNotBlank(inputSet.getDataUrl())) {
                                JSONObject jsonObject = downloadScriptFile(inputSet.getDataUrl());
                                //添加返回结果集
                                jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_ID, inputSet.getEnvId());
                                Environment environment = environmentMap.get(inputSet.getEnvId());
                                String envName = environment == null ? "" : environment.getName();
                                jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_NAME,envName);

                                Object tableContent = jsonObject.get(ScriptConstant.SCRIPT_INPUT_TABLE_CONTENT);
                                if (null != tableContent && !Objects.equals(tableContent, "")) {
                                    List<Map<String, Object>> objectList = JSON.parseObject(tableContent.toString(), new TypeReference<List<Map<String, Object>>>() {
                                    });
                                    //处理引用型数据
                                    List<Map<String, Object>> mapList = dataMgrUtils.dealWithQuoteFiled(objectList, inputSet.getEnvId());
                                    jsonObject.put(ScriptConstant.SCRIPT_INPUT_TABLE_CONTENT, mapList);
                                }
                                jsonList.add(jsonObject);
                            }
                        }
                    }
                    List<String> inputSetEnvIds = atuInputSets.stream().map(AtuInputSet::getEnvId).collect(Collectors.toList());
                    for (String envId : envIds) {
                        if (!inputSetEnvIds.contains(envId)) {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_ID, envId);
                            Environment environment = environmentMap.get(envId);
                            String envName = environment == null ? "" : environment.getName();
                            jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_NAME,envName);
                            jsonList.add(jsonObject);
                        }
                    }
                } else {
                    //添加返回结果集
                    for (String envId : envIds) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_ID, envId);
                        Environment environment = environmentMap.get(envId);
                        String envName = environment == null ? "" : environment.getName();
                        jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_NAME,envName);
                        jsonList.add(jsonObject);
                    }
                }
            }
        }
        AtuScriptInputSetResultDto resultDto = new AtuScriptInputSetResultDto();
        resultDto.setJsonObjectList(jsonList);
        //获取表头信息
        List<String> tableHeaders = queryTableHeaders(jsonList);
        if (tableHeaders.size() > 0) {
            resultDto.setTableHeaders(tableHeaders);
        }
        return inputSetSeq(envIds, resultDto);
    }

    private void associatedFileObjId(List<String> fileIds, String objId) {
        if (!CollectionUtils.isEmpty(fileIds)) {
            AssociatedFilesDto associatedFilesDto = new AssociatedFilesDto();
            associatedFilesDto.setObjId(objId);
            associatedFilesDto.setFileIds(fileIds);
            ResultWrapper<String> wrapper = attachmentFeignClient.associatedFiles(associatedFilesDto);
            if (wrapper == null || !wrapper.isSuccess()) {
                throw new InvalidException("文件关联异常");
            }
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public AtuScriptInputSetAddDto saveBatch(AtuScriptInputSetAddDto addDto) {
        AtuScriptInputSetAddDto result = new AtuScriptInputSetAddDto();
        //根据系统id查系统环境关联表中的环境属性集合 1
        List<String> envIds = projectFeignClient.selectEnvIds(addDto.getProId());
        if (envIds.size() > 0) {
            //确定每列的_row_id_的值
            List<String> rowIds = new ArrayList<>();
            for (int i = 0; i < addDto.getAtuScriptInputSetAddTmpDtos().get(0).getTableContent().size(); i++) {
                rowIds.add(UUIDUtil.create32UUID());
            }
            attachmentFeignClient.deleteFileByObjId(addDto.getScriptId(), FileBusinessTypeEnum.COMMON_SCRIPT_INPUT_DATA_SET.getCode());
            if (StringUtils.isNotBlank(addDto.getScriptId())) {//编辑
                List<String> ids = new ArrayList<>();
                //根据脚本id查脚本输入项数据集草稿表关联表中的环境属性集合 2
                AtuScriptInputSet atuScriptInputSet = new AtuScriptInputSet();
                atuScriptInputSet.setScriptId(addDto.getScriptId());
                List<AtuScriptInputSet> atuScriptInputSets = atuScriptInputSetService.query(atuScriptInputSet);
                if (atuScriptInputSets.size() > 0) {
                    //如果存在
                    //比较 1和2
                    List<AtuScriptInputSet> delIds = new ArrayList<>();
                    List<AtuScriptInputSet> noDelObjs = new ArrayList<>();
                    for (AtuScriptInputSet inputSet : atuScriptInputSets) {
                        if (!envIds.contains(inputSet.getEnvId())) {//2中存在1中不存在的
                            delIds.add(inputSet);
                        } else {//1和2中共同存在的
                            noDelObjs.add(inputSet);
                        }
                    }
                    //2中存在1中不存在的 删脚本输入项数据集草稿表关联表中对应的记录
                    if (delIds.size() != 0) {
                        List<String> deletedFileIds = delIds.stream().map(item -> "/" + MinioPathUtils.idToPath(item.getDataUrl())[1]).collect(Collectors.toList());
                        associatedFileObjId(deletedFileIds, "-1");
                        atuScriptInputSetService.deleteByPrimaryKeys(delIds.stream().map(AtuScriptInputSet::getId).collect(Collectors.toList()));
                    }
                    if (noDelObjs.size() != 0) {
                        Map<String, List<AtuScriptInputSetAddTmpDto>> mapTmp = addDto.getAtuScriptInputSetAddTmpDtos().stream().collect(Collectors.groupingBy(AtuScriptInputSetAddTmpDto::getEnvId));
                        AtuScriptInputSet atuScriptInputSetUpdate = null;
                        JSONObject jsonObject = null;
                        for (AtuScriptInputSet inputSet : noDelObjs) {
                            //2和1都存在的更新
                            //上传到文件服务器
                            jsonObject = new JSONObject();
                            List<AtuScriptInputSetAddTmpDto> atuScriptInputSetAddTmpDtos = mapTmp.get(inputSet.getEnvId());
                            if (null != atuScriptInputSetAddTmpDtos && atuScriptInputSetAddTmpDtos.size() != 0) {
                                for (AtuScriptInputSetAddTmpDto tmpDto : atuScriptInputSetAddTmpDtos) {
                                    if (inputSet.getEnvId().equals(tmpDto.getEnvId())){
                                        atuScriptInputSetUpdate = new AtuScriptInputSet();
                                        //给每一列数据加一个key _row_id_
                                        addKey(tmpDto.getTableContent(), rowIds);
                                        jsonObject.put(ScriptConstant.SCRIPT_INPUT_TABLE_HEADERS, addDto.getTableHeaders());
                                        jsonObject.put(ScriptConstant.SCRIPT_INPUT_TABLE_CONTENT, tmpDto.getTableContent());
                                        jsonObject.put(ScriptConstant.SCRIPT_INPUT_VARIABLES,addDto.getVariables());
                                        String path = generateScriptFileAndUpload(jsonObject, addDto.getScriptId(), FileBusinessTypeEnum.COMMON_SCRIPT_INPUT_DATA_SET);
                                        //数据更新
                                        atuScriptInputSetUpdate.setId(inputSet.getId());
                                        atuScriptInputSetUpdate.setUpdatedBy(NKSecurityContext.getUserId());
                                        atuScriptInputSetUpdate.setUpdatedTime(new Date());
                                        atuScriptInputSetUpdate.setDataUrl(path);
                                        atuScriptInputSetService.updateByPrimaryKey(atuScriptInputSetUpdate);
                                        //添加静态数据引用关联
                                        dataMgrUtils.queryInputAndDataLink(tmpDto.getTableContent(),inputSet.getEnvId(),inputSet.getId(),ScriptConstant.DATA_SET_LINK_BY_SCRIPT);
                                        ids.add(inputSet.getId());
                                    }
                                }
                            }
                        }
                    }
                    //筛选出1中存在2中不存在的
                    List<String> refEnvIds = atuScriptInputSets.stream().map(AtuScriptInputSet::getEnvId).collect(Collectors.toList());
                    List<String> addEnvIds = new ArrayList<>();
                    for (String envId : envIds) {
                        if (!refEnvIds.contains(envId)) {
                            addEnvIds.add(envId);
                        }
                    }
                    if (addEnvIds.size() != 0) {//1中存在2中不存在的 新增脚本输入项数据集草稿表关联表中对应的记录
                        AtuScriptInputSet atuScriptInputSetAdd = null;
                        JSONObject jsonObjectAdd = null;
                        //插入库
                        long nowTime = new Date().getTime();
                        long num = 0;
                        for (AtuScriptInputSetAddTmpDto tmpDto : addDto.getAtuScriptInputSetAddTmpDtos()) {
                            //更新到云服务器
                            if (addEnvIds.contains(tmpDto.getEnvId())) {
                                jsonObjectAdd = new JSONObject();
                                atuScriptInputSetAdd = new AtuScriptInputSet();
                                atuScriptInputSetAdd.setEnvId(tmpDto.getEnvId());
                                //给每一列数据加一个key _row_id_
                                addKey(tmpDto.getTableContent(), rowIds);
                                jsonObjectAdd.put(ScriptConstant.SCRIPT_INPUT_TABLE_HEADERS, addDto.getTableHeaders());
                                jsonObjectAdd.put(ScriptConstant.SCRIPT_INPUT_TABLE_CONTENT, tmpDto.getTableContent());
                                jsonObjectAdd.put(ScriptConstant.SCRIPT_INPUT_VARIABLES,addDto.getVariables());
                                String path = generateScriptFileAndUpload(jsonObjectAdd, addDto.getScriptId(), FileBusinessTypeEnum.COMMON_SCRIPT_INPUT_DATA_SET);
                                //数据插入
                                String uuid = UUIDUtil.create32UUID();
                                atuScriptInputSetAdd.setId(uuid);
                                atuScriptInputSetAdd.setScriptId(addDto.getScriptId());
                                atuScriptInputSetAdd.setCreatedBy(NKSecurityContext.getUserId());
                                atuScriptInputSetAdd.setCreatedTime(new Date(nowTime + num * 2000));
                                atuScriptInputSetAdd.setDataUrl(path);
                                atuScriptInputSetService.insert(atuScriptInputSetAdd);
                                //添加静态数据引用关联
                                dataMgrUtils.queryInputAndDataLink(tmpDto.getTableContent(),tmpDto.getEnvId(),uuid,ScriptConstant.DATA_SET_LINK_BY_SCRIPT);

                                ids.add(uuid);
                                num++;
                            }
                        }
                    }
                } else {//编辑 没有保存输入项
                    AtuScriptInputSet atuScriptInputSetAdd = null;
                    JSONObject jsonObjectAdd = null;
                    //插入库
                    long nowTime = new Date().getTime();
                    long num = 0;
                    for (AtuScriptInputSetAddTmpDto tmpDto : addDto.getAtuScriptInputSetAddTmpDtos()) {
                        //更新到云服务器
                        if (envIds.contains(tmpDto.getEnvId())) {
                            jsonObjectAdd = new JSONObject();
                            atuScriptInputSetAdd = new AtuScriptInputSet();
                            atuScriptInputSetAdd.setEnvId(tmpDto.getEnvId());
                            //给每一列数据加一个key _row_id_
                            addKey(tmpDto.getTableContent(), rowIds);
                            jsonObjectAdd.put(ScriptConstant.SCRIPT_INPUT_TABLE_HEADERS, addDto.getTableHeaders());
                            jsonObjectAdd.put(ScriptConstant.SCRIPT_INPUT_TABLE_CONTENT, tmpDto.getTableContent());
                            jsonObjectAdd.put(ScriptConstant.SCRIPT_INPUT_VARIABLES,addDto.getVariables());
                            String path = generateScriptFileAndUpload(jsonObjectAdd, addDto.getScriptId(), FileBusinessTypeEnum.COMMON_SCRIPT_INPUT_DATA_SET);
                            //数据插入
                            String uuid = UUIDUtil.create32UUID();
                            atuScriptInputSetAdd.setId(uuid);
                            atuScriptInputSetAdd.setScriptId(addDto.getScriptId());
                            atuScriptInputSetAdd.setCreatedBy(NKSecurityContext.getUserId());
                            atuScriptInputSetAdd.setCreatedTime(new Date(nowTime + num * 2000));
                            atuScriptInputSetAdd.setDataUrl(path);
                            atuScriptInputSetService.insert(atuScriptInputSetAdd);
                            //添加静态数据引用关联
                            dataMgrUtils.queryInputAndDataLink(tmpDto.getTableContent(),tmpDto.getEnvId(),uuid,ScriptConstant.DATA_SET_LINK_BY_SCRIPT);

                            ids.add(uuid);
                            num++;
                        }
                    }
                }
                result.setIds(ids);
            } else {//新增
                JSONObject jsonObject = null;
                List<AtuScriptInputSetAddTmpDto> atuScriptInputSetAddTmpDtos = new ArrayList<>();
                List<JSONObject> objects = new ArrayList<>();
                AtuScriptInputSetAddTmpDto atuScriptInputSetAddTmpDtoRel = null;
                for (AtuScriptInputSetAddTmpDto tmpDto : addDto.getAtuScriptInputSetAddTmpDtos()) {
                    if (envIds.contains(tmpDto.getEnvId())) {
                        atuScriptInputSetAddTmpDtoRel = new AtuScriptInputSetAddTmpDto();
                        jsonObject = new JSONObject();
                        //给每一列数据加一个key _row_id_
                        addKey(tmpDto.getTableContent(), rowIds);
                        jsonObject.put(ScriptConstant.SCRIPT_INPUT_TABLE_HEADERS, addDto.getTableHeaders());
                        jsonObject.put(ScriptConstant.SCRIPT_INPUT_TABLE_CONTENT, tmpDto.getTableContent());
                        jsonObject.put(ScriptConstant.SCRIPT_INPUT_VARIABLES,addDto.getVariables());
                        String upload = generateScriptFileAndUpload(jsonObject, addDto.getScriptId(), FileBusinessTypeEnum.COMMON_SCRIPT_INPUT_DATA_SET);
                        jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_ID, tmpDto.getEnvId());
                        String envName = envNameUtils.getEnvName(tmpDto.getEnvId());
                        jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_NAME,envName);
                        atuScriptInputSetAddTmpDtoRel.setEnvId(tmpDto.getEnvId());
                        atuScriptInputSetAddTmpDtoRel.setPath(upload);
                        atuScriptInputSetAddTmpDtos.add(atuScriptInputSetAddTmpDtoRel);
                        objects.add(jsonObject);
                    }
                }
                result.setJsonObjects(objects);
                result.setAtuScriptInputSetAddTmpDtos(atuScriptInputSetAddTmpDtos);
            }
        } else {
            throw new PlatformRuntimeException(ScriptCaseAppError.SCRIPT_ENV_IS_NULL);
        }
        //返回结果
        return result;
    }

    @Override
    public AtuScriptInputSetAddDto saveSceneInputSet(AtuScriptInputSetAddDto dto) {
        AtuScriptInputSetAddDto result = new AtuScriptInputSetAddDto();
        //创建content的__row_id__
        List<String> rowIds = new ArrayList<>();
        for (int i = 0; i < dto.getAtuScriptInputSetAddTmpDtos().get(0).getTableContent().size(); i++) {
            rowIds.add(UUIDUtil.create32UUID());
        }
        //根据系统id查系统环境关联表中的环境
        List<String> envIds = projectFeignClient.selectEnvIds(dto.getProId());
        List<JSONObject> jsonList = new ArrayList<>();
        if (envIds.size() > 0) {
            Map<String, AtuScriptInputSetAddTmpDto> dtoMap = new HashMap<>();
            for (AtuScriptInputSetAddTmpDto tmpDto : dto.getAtuScriptInputSetAddTmpDtos()) {
                dtoMap.put(tmpDto.getEnvId(), tmpDto);
            }
            AtuScriptInputSet atuScriptInputSet = new AtuScriptInputSet();
            atuScriptInputSet.setScriptId(dto.getScriptId());
            List<AtuScriptInputSet> query = atuScriptInputSetService.query(atuScriptInputSet);
            if (query.size() > 0) {
                //编辑输入项
                List<String> existEnvList = new ArrayList<>();
                query.forEach(one -> {
                    existEnvList.add(one.getEnvId());
                });
                List<String> fileIds = query.stream().map(item -> "/" + MinioPathUtils.idToPath(item.getDataUrl())[1]).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(fileIds)) {
                    AssociatedFilesDto associatedFilesDto = new AssociatedFilesDto();
                    associatedFilesDto.setObjId("-1");
                    associatedFilesDto.setFileIds(fileIds);
                    ResultWrapper<String> wrapper = attachmentFeignClient.associatedFiles(associatedFilesDto);
                    if (wrapper == null || !wrapper.isSuccess()) {
                        throw new InvalidException("文件关联异常");
                    }
                }
                if (existEnvList.containsAll(envIds) && envIds.containsAll(existEnvList)) {
                    //环境没有变化
                    for (AtuScriptInputSet setDto : query) {
                        //更新脚本输入项
                        AtuScriptInputSetAddTmpDto tmpDto = dtoMap.get(setDto.getEnvId());
                        logger.info("环境未变化，上传文件开始，文件内容：tmpDto,{}",JSONObject.toJSONString(tmpDto));
                        JSONObject jsonObject = updateScriptInputSet(dto.getScriptId(), setDto.getId(), setDto.getEnvId(), rowIds, tmpDto, dto.getTableHeaders(),dto.getVariables());
                        jsonList.add(jsonObject);
                    }

                } else {
                    //存在不同环境
                    List<AtuScriptInputSet> deletedScriptInputSet = new ArrayList<>();
                    for (AtuScriptInputSet setDto : query) {
                        if (envIds.contains(setDto.getEnvId())) {
                            //存在就更新
                            AtuScriptInputSetAddTmpDto tmpDto = dtoMap.get(setDto.getEnvId());
                            logger.info("环境变化，上传文件开始，文件内容：tmpDto,{}",JSONObject.toJSONString(tmpDto));
                            JSONObject jsonObject = updateScriptInputSet(dto.getScriptId(), setDto.getId(), setDto.getEnvId(), rowIds, tmpDto, dto.getTableHeaders(),dto.getVariables());
                            jsonList.add(jsonObject);
                        } else {
                            //删除脚本输入项
                            deletedScriptInputSet.add(setDto);
                        }
                    }
                    if (CollectionUtils.isNotEmpty(deletedScriptInputSet)) {
                        List<String> deletedFileIds = deletedScriptInputSet.stream().map(item -> "/" + MinioPathUtils.idToPath(item.getDataUrl())[1]).collect(Collectors.toList());
                        associatedFileObjId(deletedFileIds, "-1");
                        this.atuScriptInputSetService.deleteByPrimaryKey(deletedScriptInputSet.stream().map(AtuScriptInputSet::getId).collect(Collectors.toList()));
                    }
                    //找出新增环境 创建脚本输入项并与环境关联
                    envIds.forEach(one -> {
                        if (existEnvList.contains(one)) {
                            AtuScriptInputSetAddTmpDto tmpDto = dtoMap.get(one);
                            JSONObject jsonObject = insertScriptInputSet(dto.getScriptId(), one, rowIds, dto.getTableHeaders(), tmpDto,dto.getVariables());
                            jsonList.add(jsonObject);
                        }
                    });
                }
                result.setTableHeaders(dto.getTableHeaders());
                result.setJsonObjects(jsonList);
                result.setAtuScriptInputSetAddTmpDtos(dto.getAtuScriptInputSetAddTmpDtos());
            } else {
                //查询脚本输入项为空时 全量新增
                envIds.forEach(one -> {
                    AtuScriptInputSetAddTmpDto tmpDto = dtoMap.get(one);
                    JSONObject jsonObject = insertScriptInputSet(dto.getScriptId(), one, rowIds, dto.getTableHeaders(), tmpDto,dto.getVariables());
                    jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_ID, one);
                    jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_NAME, envNameUtils.getEnvName(one));
                    jsonList.add(jsonObject);
                });
                result.setTableHeaders(dto.getTableHeaders());
                result.setJsonObjects(jsonList);
                result.setAtuScriptInputSetAddTmpDtos(dto.getAtuScriptInputSetAddTmpDtos());
            }
        } else {
            throw new PlatformRuntimeException(ScriptCaseAppError.SCRIPT_ENV_IS_NULL);
        }
        return result;
    }

    @Override
    public AtuScriptInputSetResultDto querySetDataByPath(AtuScriptInputSetAddDto addDto) {
        List<String> envIdList = this.projectFeignClient.queryEnvListSeq(addDto.getProId());
        AtuScriptInputSetResultDto resultDto = new AtuScriptInputSetResultDto();
        List<JSONObject> jsonObjects = new ArrayList<>();
        if (envIdList.size() > 0) {
            if (addDto.getAtuScriptInputSetAddTmpDtos() != null && addDto.getAtuScriptInputSetAddTmpDtos().size() > 0) {
                List<AtuScriptInputSetAddTmpDto> dtoList = addDto.getAtuScriptInputSetAddTmpDtos();
                List<String> existEnvList = new ArrayList<>();
                Map<String, AtuScriptInputSetAddTmpDto> dtoMap = new HashMap<>();
                dtoList.forEach(one -> {
                    existEnvList.add(one.getEnvId());
                    dtoMap.put(one.getEnvId(), one);
                });
                //判断环境有无发生变动
                if (existEnvList.containsAll(envIdList) && envIdList.containsAll(existEnvList)) {
                    for (AtuScriptInputSetAddTmpDto dto : dtoList) {
                        //直接下载文件 解析数据
                        JSONObject jsonObject = getJSONData(dto);
                        jsonObjects.add(jsonObject);
                    }
                } else {
                    for (String envId : existEnvList) {
                        if (envIdList.contains(envId)) {
                            //存在相同环境
                            AtuScriptInputSetAddTmpDto tmpDto = dtoMap.get(envId);
                            JSONObject jsonData = getJSONData(tmpDto);
                            jsonObjects.add(jsonData);
                        }
                    }
                    for (String envId : envIdList) {
                        if (!existEnvList.contains(envId)) {
                            //直接返回环境信息
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_ID, envId);
                            jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_NAME, envNameUtils.getEnvName(envId));
                            jsonObjects.add(jsonObject);
                        }
                    }
                }
            } else {
                //直接返回环境信息
                for (String envId : envIdList) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_ID, envId);
                    jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_NAME, envNameUtils.getEnvName(envId));
                    jsonObjects.add(jsonObject);
                }
            }
        } else {
            throw new PlatformRuntimeException(ScriptCaseAppError.SCRIPT_ENV_IS_NULL);
        }
        //返回数据 处理环境排序
        if (addDto.getTableHeaders() != null && addDto.getTableHeaders().size() > 0) {
            resultDto.setTableHeaders(addDto.getTableHeaders());
        }
        List<JSONObject> resultJsonList = new ArrayList<>();
        if (jsonObjects.size() > 0) {
            Map<String, JSONObject> resultMap = new HashMap<>();
            for (JSONObject jsonObject : jsonObjects) {
                resultMap.put(jsonObject.get(ScriptConstant.SCRIPT_INPUT_ENV_ID).toString(), jsonObject);
            }
            envIdList.forEach(one -> {
                JSONObject jsonObject = resultMap.get(one);
                resultJsonList.add(jsonObject);
            });
        }
        resultDto.setJsonObjectList(resultJsonList);
        return resultDto;
    }

    private JSONObject getJSONData(AtuScriptInputSetAddTmpDto dto) {
        JSONObject jsonObject = downloadScriptFile(dto.getPath());
        Object tableContent = jsonObject.get(ScriptConstant.SCRIPT_INPUT_TABLE_CONTENT);
        if (null != tableContent && !Objects.equals(tableContent, "")) {
            List<Map<String, Object>> objectList = JSON.parseObject(tableContent.toString(), new TypeReference<List<Map<String, Object>>>() {
            });
            //处理引用型数据
            List<Map<String, Object>> mapList = dataMgrUtils.dealWithQuoteFiled(objectList, dto.getEnvId());
            jsonObject.put(ScriptConstant.SCRIPT_INPUT_TABLE_CONTENT, mapList);
        }
        jsonObject.put(ScriptConstant.PATH, dto.getPath());
        jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_ID, dto.getEnvId());
        jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_NAME, envNameUtils.getEnvName(dto.getEnvId()));
        return jsonObject;
    }


    private void addKey(List<Map<String, Object>> tableContent, List<String> rowIds) {
        for (int i = 0; i < tableContent.size(); i++) {
            Object rowId = tableContent.get(i).get(ScriptConstant.SCRIPT_TEST_PURPOSE_ID);
            if (rowId == null || rowId.equals("")) {
                tableContent.get(i).put(ScriptConstant.SCRIPT_TEST_PURPOSE_ID, rowIds.get(i));
            }
        }
    }

    @Override
    public JSONObject importExcel(MultipartFile file, List<TableHeader> tableHeaders, String envId) {
        logger.info("---------------->开始处理数据");
        JSONObject jsonObject = new JSONObject();
        AtuInputSetResultDto resultDto = importByExcel(file, tableHeaders.size());
        List<String> excelHeaders = resultDto.getTableHeader();
        //校验前端表头跟excel表头
        if (CollectionUtils.isEmpty(excelHeaders)
                || tableHeaders.size()!=excelHeaders.size()) {
            throw new PlatformRuntimeException(ScriptCaseAppError.TABLE_HEADER_SIZE_ERROR);
        }
        for (int i = 0; i < tableHeaders.size(); i++) {
            String tableName = tableHeaders.get(i).getName();
            String cellName = excelHeaders.get(i);
            if (!cellName.equals(tableName)){
                throw new PlatformRuntimeException(ScriptCaseAppError.TABLE_HEADER_NAME_ERROR, i + 1, cellName, tableName);
            }
        }
        List<Map<String, Object>> tableContents = resultDto.getTableContent();
        Set<String> rowSet = new HashSet<>();
        Map<String,String> map = new HashMap<>();
        for (int i = 0; i < tableContents.size(); i++) {
            for (String key : excelHeaders) {
                Object cellValue = tableContents.get(i).get(key);
                String row = String.valueOf(i + 1);
                if (key.equals(ScriptConstant.SCRIPT_TEST_PURPOSE_NAME)) {
                    if (cellValue != null) {
                        String value = cellValue.toString();
                        if (StringUtils.isBlank(value)) {
                            throw new PlatformRuntimeException(ScriptCaseAppError.IMPORT_SCRIPT_INPUT_SET_NULL, row);
                        }
                        if (value.length() > 30){
                            throw new PlatformRuntimeException(ScriptCaseAppError.IMPORT_SCRIPT_INPUT_SET_TOO_LONG, row, value.length());
                        }
                        String mapValue = map.get(value);
                        if (mapValue == null) {
                            map.put(value, row);
                        } else {
                            //存在相同测试轮次名数据
                            rowSet.add(mapValue);
                            rowSet.add(row);
                        }
                    } else {
                        throw new PlatformRuntimeException(ScriptCaseAppError.IMPORT_SCRIPT_INPUT_SET_NULL, row);
                    }
                } else {
                    //长度校验 空值校验
                    if (cellValue != null) {
                        String value = cellValue.toString();
                        if (value.length() > 30) {
                            throw new PlatformRuntimeException(ScriptCaseAppError.IMPORT_INPUT_SET_TOO_LONG, row, key);
                        }
                    }
                }
            }
        }
        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());
        }

        String envName = envNameUtils.getEnvName(envId);
        jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_ID,envId);
        jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_NAME,envName);
        jsonObject.put(ScriptConstant.SCRIPT_INPUT_TABLE_CONTENT, tableContents);
        return jsonObject;
    }

    @Override
    public void exportExcel(HttpServletResponse response, AtuScriptInputSetAddTmpDto tmpDto) {
        try {
            XSSFWorkbook hssfWorkbook = getXSSFWorkbook(tmpDto);
            String fileName = ScriptConstant.FILE_INPUT_DATA_SET;

            setResponseHeader(response);
            ServletOutputStream outputStream = response.getOutputStream();
            hssfWorkbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            logger.error(e.getMessage());
            throw new PlatformRuntimeException(ScriptCaseAppError.EXPORT_ERR);
        }
    }

    private XSSFWorkbook getXSSFWorkbook(AtuScriptInputSetAddTmpDto tmpDto) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        List<Map<String, Object>> tableContent = tmpDto.getTableContent();
        List<String> tableHeaders = tmpDto.getTableHeaders();
        String sheetName = ScriptConstant.SHEET;
        String envName = envNameUtils.getEnvName(tmpDto.getEnvId());
        if (StringUtils.isNotBlank(envName)) {
            sheetName = envName;
        }
        XSSFSheet sheet = workbook.createSheet(sheetName);
        XSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        XSSFCell cell = null;
        // 列宽
        List<Integer> widthList = new ArrayList<>();
        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);
                int headerWith = cell.getStringCellValue().getBytes().length * 256;
                widthList.add(headerWith);
            }
            if (null != tableContent && tableContent.size() > 0) {
                //表体填充
                for (int i = 0; i < tableContent.size(); i++) {
                    XSSFRow row1 = sheet.createRow(i + 1);
                    for (int j = 0; j < tableHeaders.size(); j++) {
                        cell = row1.createCell(j);
                        String cellValue = "";
                        Object o = tableContent.get(i).get(tableHeaders.get(j));
                        if (null != o) {
                            cellValue = o.toString();
                        }
                        cell.setCellStyle(cellStyle);
                        cell.setCellValue(cellValue);
                        //计算列宽
                        int width = cell.getStringCellValue().getBytes().length * 256;
                        if (width > widthList.get(j)) {
                            widthList.set(j, width);
                        }
                    }
                }
            }
        }
        for (int i = 0; i < widthList.size(); i++) {
            sheet.setColumnWidth(i, widthList.get(i) + 512);
        }
        return workbook;
    }

    private void setResponseHeader(HttpServletResponse response) {
        try {
            String fileName = ScriptConstant.FILE_EXPORT_INPUT;
            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());
        }
    }

    public JSONObject downloadScriptFile(String url) {
        String[] resultPath = pathUtil.idToPath(url);
        InputStream inputStream = null;
        JSONObject scriptData = null;
        try {
            inputStream = simpleStorageService.downloadAsStream(resultPath[0], "/" + resultPath[1]);
            scriptData = pathUtil.getFileContent(inputStream, JSONObject.class);
        } catch (FileDownloadException e) {
            logger.error("读取原脚本文件失败，失败原因", e);
            throw new PlatformRuntimeException(new ErrorMessage("读取原脚本文件失败"));
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.error("", e);
                }
            }
        }
        return scriptData;
    }

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

    private List<String> queryTableHeaders(List<JSONObject> jsonList) {
        List<String> tableHeaders = new ArrayList<>();
        if (CollUtil.isEmpty(jsonList)){
            logger.debug("输入项数据为空");
            return tableHeaders;
        }
        JSONObject jsonObject = jsonList.get(0);
        if (jsonObject == null){
            logger.debug("输入项首个环境数据为空");
            return tableHeaders;
        }
        Object tableHeader = jsonObject.get(ScriptConstant.SCRIPT_INPUT_TABLE_HEADERS);
        if (tableHeader == null){
            logger.debug("输入项首个环境表头数据为空");
            return tableHeaders;
        }
        tableHeaders = JSON.parseArray(JSON.toJSONString(tableHeader), String.class);
        return tableHeaders;
    }

    //处理环境排序
    private AtuScriptInputSetResultDto inputSetSeq(List<String> envList, AtuScriptInputSetResultDto resultDto) {
        List<JSONObject> jsonList = resultDto.getJsonObjectList();
        List<JSONObject> jsonSeqList = new ArrayList<>();
        for (String envId : envList) {
            for (JSONObject jsonObject : jsonList) {
                if (jsonObject.get(ScriptConstant.SCRIPT_INPUT_ENV_ID).equals(envId)) {
                    jsonSeqList.add(jsonObject);
                }
            }
        }

        resultDto.setJsonObjectList(jsonSeqList);
        return resultDto;
    }

    private JSONObject updateScriptInputSet(String scriptId, String id, String envId, List<String> rowIds, AtuScriptInputSetAddTmpDto tmpDto, List<String> tableHeaders,List<Map<String,Object>> variables) {
        JSONObject jsonObject = new JSONObject();
        if (null != tmpDto) {
            AtuScriptInputSet updateDto = new AtuScriptInputSet();
            //给每一列数据加一个key _row_id_
            addKey(tmpDto.getTableContent(), rowIds);
            jsonObject.put(ScriptConstant.SCRIPT_INPUT_TABLE_HEADERS, tableHeaders);
            jsonObject.put(ScriptConstant.SCRIPT_INPUT_TABLE_CONTENT, tmpDto.getTableContent());
            jsonObject.put(ScriptConstant.SCRIPT_INPUT_VARIABLES,variables);
            logger.info("上传文件内容：jsonObject:{}",jsonObject.toJSONString());
            String path = generateScriptFileAndUpload(jsonObject, scriptId, FileBusinessTypeEnum.SCENE_SCRIPT_INPUT_DATA_SET);
            //数据更新
            updateDto.setId(id);
            updateDto.setDataUrl(path);
            updateDto.setUpdatedBy(NKSecurityContext.getUserId());
            updateDto.setUpdatedTime(new Date());
            atuScriptInputSetService.updateByPrimaryKey(updateDto);

            dataMgrUtils.queryInputAndDataLink(tmpDto.getTableContent(),envId,id,ScriptConstant.DATA_SET_LINK_BY_SCENE);
        }
        jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_ID, envId);
        jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_NAME, envNameUtils.getEnvName(envId));
        return jsonObject;
    }

    private JSONObject insertScriptInputSet(String scriptId, String envId, List<String> rowIds, List<String> tableHeaders, AtuScriptInputSetAddTmpDto tmpDto,List<Map<String,Object>> variables) {
        JSONObject jsonObject = new JSONObject();
        if (null != tmpDto) {
            AtuScriptInputSet addDto = new AtuScriptInputSet();
            addDto.setEnvId(envId);
            //给每一列数据加一个key _row_id_
            addKey(tmpDto.getTableContent(), rowIds);
            jsonObject.put(ScriptConstant.SCRIPT_INPUT_TABLE_HEADERS, tableHeaders);
            jsonObject.put(ScriptConstant.SCRIPT_INPUT_TABLE_CONTENT, tmpDto.getTableContent());
            jsonObject.put(ScriptConstant.SCRIPT_INPUT_VARIABLES,variables);
            String path = generateScriptFileAndUpload(jsonObject, scriptId, FileBusinessTypeEnum.SCENE_SCRIPT_INPUT_DATA_SET);
            //数据插入
            String uuid = UUIDUtil.create32UUID();
            addDto.setId(uuid);
            addDto.setScriptId(scriptId);
            addDto.setCreatedBy(NKSecurityContext.getUserId());
            addDto.setCreatedTime(new Date());
            addDto.setDataUrl(path);
            atuScriptInputSetService.insert(addDto);

            dataMgrUtils.queryInputAndDataLink(tmpDto.getTableContent(),envId,uuid,ScriptConstant.DATA_SET_LINK_BY_SCENE);
        }
        jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_ID, envId);
        jsonObject.put(ScriptConstant.SCRIPT_INPUT_ENV_NAME, envNameUtils.getEnvName(envId));
        return jsonObject;
    }

    private AtuInputSetResultDto importByExcel(MultipartFile file,Integer headerSize) {
        if (file.isEmpty()) {
            throw new PlatformRuntimeException(ScriptCaseAppError.FILE_IS_NULL);
        }
        AtuInputSetResultDto resultDto = new AtuInputSetResultDto();
        String name = file.getOriginalFilename();
        if (StringUtils.isNotBlank(name)) {
            String subStr = name.substring(name.lastIndexOf("."));
            if (subStr.equals(ScriptConstant.FILE_XLSX)) {
                //解析xlsx后缀的excel文件
                resultDto = analysisExcelByXLSX(file,headerSize);
            } else if (subStr.equals(ScriptConstant.FILE_XLS)) {
                //解析xls后缀的excel文件
                resultDto = analysisExcelByXLS(file,headerSize);
            }
        }else {
            throw new PlatformRuntimeException(ScriptCaseAppError.FILE_IS_NULL);
        }
        return resultDto;
    }


    private AtuInputSetResultDto analysisExcelByXLSX(MultipartFile file,Integer headerSize) {
        AtuInputSetResultDto resultDto = new AtuInputSetResultDto();
        List<String> excelHeaders = new ArrayList<>();
        List<Map<String, Object>> excelContents = new ArrayList<>();
        XSSFWorkbook sheets = null;
        try {
            sheets = new XSSFWorkbook(file.getInputStream());
        } catch (IOException e) {
            throw new PlatformRuntimeException(ScriptCaseAppError.EXCEL_FILE_READ_ERROR);
        }
        //获取表头信息
        XSSFSheet sheet = sheets.getSheetAt(ScriptConstant.EXCEL_FIRST_SHEET);
        if (sheet == null) {
            throw new PlatformRuntimeException(ScriptCaseAppError.EXCEL_FISRT_SHEET_NULL);
        }
        XSSFRow rowHeader = sheet.getRow(ScriptConstant.EXCEL_FIRST_ROW);
        if (rowHeader == null) {
            throw new PlatformRuntimeException(ScriptCaseAppError.EXCEL_HEADER_IS_NULL);
        }
        for (int i = 0; i < rowHeader.getPhysicalNumberOfCells(); i++) {
            XSSFCell cell = rowHeader.getCell(i);
            if (cell != null && cell.getCellType() != CellType.BLANK) {
                cell.setCellType(CellType.STRING);
                excelHeaders.add(cell.getStringCellValue());
            } else {
                throw new PlatformRuntimeException(ScriptCaseAppError.EXCEL_HEADER_IS_NULL);
            }
        }
        //组装表体数据
        int rowNum = sheet.getLastRowNum() + 1;
        for (int i = 1; i < rowNum; i++) {
            XSSFRow row = sheet.getRow(i);
            Map<String, Object> cellMap = new LinkedHashMap<>();
            for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
                XSSFCell cell = row.getCell(j);
                if (cell == null) {
                    cellMap.put(excelHeaders.get(j), null);
                } else if (cell.getCellType() == CellType.NUMERIC) {
                    if (DateUtil.isCellDateFormatted(cell)) {
                        SimpleDateFormat sdf = new SimpleDateFormat(ScriptConstant.SIMPLE_FORMAT);
                        cellMap.put(excelHeaders.get(j), sdf.format(cell.getDateCellValue()));
                    } else {
                        cellMap.put(excelHeaders.get(j), cell.getNumericCellValue());
                    }
                } else {
                    cell.setCellType(CellType.STRING);
                    cellMap.put(excelHeaders.get(j), cell.getStringCellValue());
                }
            }
            excelContents.add(cellMap);
        }
        resultDto.setTableHeader(excelHeaders);
        resultDto.setTableContent(excelContents);
        return resultDto;
    }

    private AtuInputSetResultDto analysisExcelByXLS(MultipartFile file,Integer headerSize) {
        AtuInputSetResultDto resultDto = new AtuInputSetResultDto();
        List<String> excelHeaders = new ArrayList<>();
        List<Map<String, Object>> excelContents = new ArrayList<>();
        HSSFWorkbook sheets = null;
        try {
            sheets = new HSSFWorkbook(file.getInputStream());
        } catch (IOException e) {
            throw new PlatformRuntimeException(ScriptCaseAppError.EXCEL_FILE_READ_ERROR);
        }
        //获取表头信息
        HSSFSheet sheet = sheets.getSheetAt(ScriptConstant.EXCEL_FIRST_SHEET);
        if (sheet == null) {
            throw new PlatformRuntimeException(ScriptCaseAppError.EXCEL_FISRT_SHEET_NULL);
        }
        HSSFRow rowHeader = sheet.getRow(ScriptConstant.EXCEL_FIRST_ROW);
        for (int i = 0; i < rowHeader.getPhysicalNumberOfCells(); i++) {
            HSSFCell cell = rowHeader.getCell(i);
            if (cell != null && cell.getStringCellValue() != null) {
                cell.setCellType(CellType.STRING);
                excelHeaders.add(cell.getStringCellValue());
            } else {
                throw new PlatformRuntimeException(ScriptCaseAppError.EXCEL_HEADER_IS_NULL);
            }
        }
        //组装表体数据
        int rowNum = sheet.getLastRowNum() + 1;
        for (int i = 1; i < rowNum; i++) {
            HSSFRow row = sheet.getRow(i);
            Map<String, Object> cellMap = new LinkedHashMap<>();
            for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
                HSSFCell cell = row.getCell(j);
                if (cell == null) {
                    cellMap.put(excelHeaders.get(j), null);
                } else if (cell.getCellType() == CellType.NUMERIC) {
                    if (DateUtil.isCellDateFormatted(cell)) {
                        SimpleDateFormat sdf = new SimpleDateFormat(ScriptConstant.SIMPLE_FORMAT);
                        cellMap.put(excelHeaders.get(j), sdf.format(cell.getDateCellValue()));
                    } else {
                        cellMap.put(excelHeaders.get(j), cell.getNumericCellValue());
                    }
                } else {
                    cell.setCellType(CellType.STRING);
                    cellMap.put(excelHeaders.get(j), cell.getStringCellValue());
                }
            }
            excelContents.add(cellMap);
        }
        resultDto.setTableHeader(excelHeaders);
        resultDto.setTableContent(excelContents);
        return resultDto;
    }

}
