package com.yeejoin.amos.api.openapi.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class FileDeleteUtil {

    public static List<String> extractFileNames(List<String> fileUrls) {
        if (fileUrls == null || fileUrls.isEmpty()) {
            return Lists.newArrayList();
        }

        List<String> allFileNames = new ArrayList<>();
        for (String url : fileUrls) {
            if (url != null) {
                List<String> fileNames = extractFileNamesFromJsonStr(url);
                allFileNames.addAll(fileNames);
            }
        }
        return allFileNames;
    }

    // 解析JSON字符串，添加文件名到集合中
    public static List<String> extractFileNamesFromJsonStr(String jsonStr) {
        List<String> fileUrls = Lists.newArrayList();
        if (!ValidationUtil.isEmpty(jsonStr)) {
            try {
                Object json = JSONObject.parse(jsonStr);
                if (json instanceof JSONArray) {
                    JSONArray jsonArray = JSONObject.parseArray(jsonStr);
                    if (jsonArray != null) {
                        jsonArray.forEach(fileInfo -> {
                            if (fileInfo instanceof JSONObject) {
                                try {
                                    String fileName = ((JSONObject) fileInfo).get("fileUrl").toString();
                                    fileUrls.add(fileName);
                                } catch (Exception e) {
                                    log.info("Error parsing file URL: {}", fileInfo);
                                }
                            }
                        });
                    }
                } else if (json instanceof JSONObject) {
                    try {
                        String fileName = ((JSONObject) json).getString("fileUrl");
                        if (fileName != null) fileUrls.add(fileName);
                    } catch (Exception e) {
                        log.info("Error parsing file URL: {}", json);
                    }
                }
                return fileUrls;
            } catch (Exception e) {
                log.info("Error parsing JSON: {}", jsonStr);
                System.err.println("Error parsing JSON: " + e.getMessage());
            }
        }
        return fileUrls;
    }
}
