package net.northking.cctp.scriptcase.tools;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.common.s3.FileDownloadException;
import net.northking.cctp.common.s3.SimpleStorageService;
import net.northking.cctp.common.security.authentication.NKSecurityContext;
import net.northking.cctp.scriptcase.constants.ScriptConstant;
import net.northking.cctp.scriptcase.dto.inputSet.AtuInputSetResultDto;
import net.northking.cctp.scriptcase.enums.ErrorMessage;
import net.northking.cctp.scriptcase.enums.ScriptCaseAppError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

@Component
public class DownloadFileUtils {

    @Autowired
    private SimpleStorageService simpleStorageService;

    private static final Logger logger = LoggerFactory.getLogger(DownloadFileUtils.class);


    //下载输入项文件
    public AtuInputSetResultDto downloadFile(String url) {
        AtuInputSetResultDto dto = new AtuInputSetResultDto();
        try {
            String newUrl = url.replace(NKSecurityContext.getTenantId(), "");
            File file = simpleStorageService.downloadAsFile(NKSecurityContext.getTenantId(), newUrl.replace("_", "/"));
            byte[] bytes = FileUtil.readBytes(file);
            if (bytes != null) {
                String jsonStr = new String(bytes, StandardCharsets.UTF_8);
                JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                logger.info("===================>文件内容为:{}", jsonObject.toString());

                Object headers = jsonObject.get(ScriptConstant.SCRIPT_INPUT_TABLE_HEADERS);
                if (headers != null) {
                    List<String> tableHeaders = JSONObject.parseArray(JSONObject.toJSONString(headers), String.class);
                    dto.setTableHeader(tableHeaders);
                } else {
                    throw new PlatformRuntimeException(ScriptCaseAppError.FILE_GET_TABLE_HEARER_ERROR);
                }
                Object content = jsonObject.get(ScriptConstant.SCRIPT_INPUT_TABLE_CONTENT);
                if (content != null) {
                    List<Map<String, Object>> mapList = JSON.parseObject(JSONObject.toJSONString(content), new TypeReference<List<Map<String, Object>>>(){
                    });
                    dto.setTableContent(mapList);
                }
                Object variables = jsonObject.get(ScriptConstant.SCRIPT_INPUT_VARIABLES);
                if (variables != null) {
                    List<Map<String, Object>> mapList = JSON.parseObject(JSONObject.toJSONString(variables), new TypeReference<List<Map<String, Object>>>(){
                    });
                    dto.setVariables(mapList);
                }
            }
        } catch (FileDownloadException e) {
            logger.error("下载文件异常", e);
        }
        return dto;
    }

    //下载静态数据集数据
    public JSONObject downloadDataSetFile(String url) {
        String[] resultPath = MinioPathUtils.idToPath(url);
        InputStream inputStream = null;
        JSONObject scriptData = null;
        try {
            inputStream = simpleStorageService.downloadAsStream(resultPath[0], "/" + resultPath[1]);
            scriptData = MinioPathUtils.getFileContent(inputStream, JSONObject.class);
            return scriptData;
        } catch (FileDownloadException e) {
            logger.error("读取原文件失败，失败原因：", e);
            throw new PlatformRuntimeException(ScriptCaseAppError.READ_FILE_ERROR);
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.error("",e);
                }
            }
        }
    }
    public  JSONObject downloadScriptFile(String url) {
        String[] resultPath = MinioPathUtils.idToPath(url);
        InputStream inputStream = null;
        JSONObject scriptData = null;
        try {
            inputStream = simpleStorageService.downloadAsStream(resultPath[0], "/" + resultPath[1]);
            scriptData = MinioPathUtils.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;
    }
}
