package net.northking.cctp.executePlan.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.common.s3.SimpleStorageService;
import net.northking.cctp.common.util.UUIDUtil;
import net.northking.cctp.executePlan.exception.ExecPlanError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author chenjianfeng
 */
@Component
public class MinioPathUtils {
    private static final Logger logger = LoggerFactory.getLogger(MinioPathUtils.class);

    private static final String TEMP_FILE_PATH = MinioPathUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();

    public static final String DIAGONAL = "/";

    public static final String UNDERLINE = "_";

    /**
     * 第一个是租户id,第二个是文件id，第三个是文件名
     * @param fileId
     * @return
     */
    public static String[] idToPath(String fileId) {
        String[] result = new String[3];
        if (fileId.startsWith("/") || fileId.startsWith("_")) {
            fileId = fileId.substring(1);
        }
        if (fileId.endsWith("/") || fileId.endsWith("_")) {
            fileId = fileId.substring(0, fileId.length() - 1);
        }
        int index = fileId.indexOf("_");
        result[0] = fileId.substring(0, index);  //租户id
        result[1] = fileId.substring(index + 1);  //文件id
        result[2] = result[1];  //文件名
        return result;
    }

    public static<T> File objectToJsonFile(T t) {
        String objectStr = JSON.toJSONString(t);
        byte[] bytes;
        bytes = objectStr.getBytes(StandardCharsets.UTF_8);
        //获取脚本输入流
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        File tempFilePath = new File(TEMP_FILE_PATH);
        if (!tempFilePath.exists()) {
            tempFilePath.mkdirs();
        }
        File file = new File(TEMP_FILE_PATH + "/tempFile" + UUIDUtil.create32UUID() + ".json");
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(file);
            byte[] readBytes = new byte[1024 * 1024];
            int length;
            while ((length = inputStream.read(readBytes, 0, readBytes.length)) > 0) {
                fileOutputStream.write(readBytes,0,length);
            }
            fileOutputStream.flush();
        } catch (Exception e) {
            logger.error("object写入文件出错");
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                logger.error("关闭文件流异常", e);
            }
            try {
                if (null != fileOutputStream) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                logger.error("关闭文件流异常", e);
            }
        }
        return file;
    }

    public static<T> T getFileContent(InputStream inputStream, Class<T> clazz) {
        InputStreamReader streamReader = null;
        BufferedReader reader = null;
        T t = null;
        try {
            streamReader = new InputStreamReader(inputStream,StandardCharsets.UTF_8);
            reader = new BufferedReader(streamReader);
            StringBuilder builder = new StringBuilder();
            String temp;
            while (null != (temp = reader.readLine())) {
                builder.append(temp);
            }
            String jsonStr = builder.toString();
            if (StringUtils.hasText(jsonStr)) {
                t = JSON.parseObject(JSON.parse(jsonStr).toString(), clazz);
            }
        } catch (IOException e) {
            logger.error("读取文件内容失败");
            throw new PlatformRuntimeException(ExecPlanError.DOWNLOAD_SCRIPT_FAIL);
        }finally {
            if (null != streamReader) {
                try {
                    streamReader.close();
                } catch (IOException e) {
                    logger.error("关闭文件流异常", e);
                }
            }
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("关闭文件流异常", e);
                }
            }
        }
        return t;
    }

    /**
     * 文件下载并转换成对象
     * @param filePath 文件地址
     * @param clazz 需转换的对象
     * @return 结果
     */
    public static <T> T downloadFileCoverObj(SimpleStorageService simpleStorageService, String tenantId,
                                             String filePath, Class<T> clazz){
        File file = null;
        T t = null;
        if (StrUtil.isBlank(filePath)){
            logger.debug("需下载的文件地址为空");
            return t;
        }
        try {
            logger.debug("需下载的文件地址：{}", filePath);
            String path = filePath.replace(tenantId, "");
            path = path.replace("_","/");
            logger.debug("转换后的地址：{}", path);
            file = simpleStorageService.downloadAsFile(tenantId, path);
            byte[] bytes = FileUtil.readBytes(file);
            if (bytes != null){
                String jsonStr = new String(bytes, StandardCharsets.UTF_8);
                t = JSONUtil.toBean(jsonStr, clazz);
            }
        } catch (Exception e) {
            logger.error("读取结果文件失败", e);
        } finally {
            // 删除下载的临时文件
            if (file != null) {
                if (!file.delete()) {
                    logger.error("临时文件删除失败， file => " + file.getAbsolutePath());
                }
            }
        }
        return t;
    }

}
