package com.njcn.gather.icd.service.support;

import com.alibaba.fastjson.JSON;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.gather.icd.pojo.enums.IcdResponseEnum;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.util.Base64;
import java.util.Locale;

@Component
public class IcdPayloadValidator {

    public MultipartFile validateIcdFile(MultipartFile file, boolean required) {
        if ((file == null || file.isEmpty()) && required) {
            throw new BusinessException(IcdResponseEnum.ICD_FILE_NOT_NULL);
        }
        if (file == null || file.isEmpty()) {
            return null;
        }
        String originalName = file.getOriginalFilename();
        if (originalName == null || !originalName.toLowerCase(Locale.ROOT).endsWith(".icd")) {
            throw new BusinessException(IcdResponseEnum.ICD_FILE_TYPE_ERROR);
        }
        return file;
    }

    public String extractName(String originalName) {
        int suffixIndex = originalName.toLowerCase(Locale.ROOT).lastIndexOf(".icd");
        return suffixIndex >= 0 ? originalName.substring(0, suffixIndex) : originalName;
    }

    public byte[] decodeExternalIcdFile(String base64Content) {
        if (base64Content == null || base64Content.trim().isEmpty()) {
            throw new BusinessException(IcdResponseEnum.ICD_FILE_NOT_NULL);
        }
        try {
            return Base64.getDecoder().decode(base64Content.trim());
        } catch (IllegalArgumentException ex) {
            throw new BusinessException(IcdResponseEnum.ICD_FILE_READ_ERROR);
        }
    }

    public void validateJson(String jsonStr) {
        try {
            JSON.parse(jsonStr);
        } catch (Exception ex) {
            throw new BusinessException(IcdResponseEnum.JSON_FORMAT_ERROR);
        }
    }

    public void validateXml(String xmlStr) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // 禁用 DOCTYPE 声明
            factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
            factory.newDocumentBuilder().parse(new InputSource(new StringReader(xmlStr)));
        } catch (Exception ex) {
            throw new BusinessException(IcdResponseEnum.XML_FORMAT_ERROR);
        }
    }
}
