package net.northking.cctp.scriptcase.tools;

import com.alibaba.fastjson.JSONObject;
import net.northking.cctp.common.enums.FileBusinessTypeEnum;
import net.northking.cctp.common.exception.PlatformRuntimeException;
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.scriptcase.enums.ErrorMessage;
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 java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * 通用工具方法
 */
@Service
@ConditionalOnMissingBean(name = "ScriptCaseUtils")
public class ScriptCaseUtils {

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

    @Autowired
    private MinioPathUtils pathUtil;
    @Autowired
    private SimpleStorageService simpleStorageService;
    /**
     * 获取新的版本号 尾号加一，过十进一原则
     * @param version
     * @return
     */
    public static String getNextVersion(String version){
        if("".equals(version)){
            return "1.0.0";
        }
        String[] arr = version.split("\\.");
        StringBuilder result = new StringBuilder();
        boolean needUp = true;
        for (int i = arr.length - 1; i >= 0; i--) {
            int k=Integer.parseInt(arr[i]);
            if (needUp)k++;
            if(k<10 || i==0){
                needUp=false;
            }else{
                k=0;
            }
            result.insert(0, k + (i == arr.length - 1 ? "" : "."));
        }
        return result.toString();
    }

    /**
     * json存储上传
     * @param scriptJsonStr
     * @return 文件地址
     */
    public String generateScriptFileAndUpload(String scriptJsonStr, String objId, FileBusinessTypeEnum businessCode) {
        File file = pathUtil.objectToJsonFile(JSONObject.parse(scriptJsonStr));
        try {
            NKFile nkFile = simpleStorageService.upload(NKSecurityContext.getTenantId(), file, objId, businessCode);
            String path = pathUtil.pathToId(NKSecurityContext.getTenantId(), nkFile.getId());
            return path;
        } catch (FileUploadException e) {
            logger.error("文件上传报错：",e);
            return null;
        } finally {
            boolean delete = file.delete();
            if (!delete) {
                logger.error("删除文件失败");
            }
        }
    }

    /**
     * json存储上传-json文件
     * @param scriptJsonStr
     * @return 文件地址
     */
    public String generateScriptFileAndUploadByJson(JSONObject scriptJsonStr, String objId, FileBusinessTypeEnum businessCode) {
        File file = pathUtil.objectToJsonFile(scriptJsonStr);
        try {
            NKFile nkFile = simpleStorageService.upload(NKSecurityContext.getTenantId(), file, objId, businessCode);
            String path = pathUtil.pathToId(NKSecurityContext.getTenantId(), nkFile.getId());
            return path;
        } catch (FileUploadException e) {
            return null;
        } finally {
            boolean delete = file.delete();
            if (!delete) {
                logger.error("删除文件失败");
            }
        }
    }


    /**
     * 通过文件id获取脚本json
     * @param fileId
     * @return
     */
    public JSONObject getJsonByFileId(String fileId) {
        String[] resultPath = pathUtil.idToPath(fileId);
        InputStream inputStream = null;
        JSONObject scriptData = null;
        try {
            String path = fileId.substring(fileId.indexOf("_")+1);
            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;
    }
}
