package com.njcn.gather.icd.mapping.component;

import com.njcn.gather.icd.mapping.pojo.bo.IcdToXmlGenerateResult;
import com.njcn.gather.icd.mapping.pojo.bo.analysis.IndexCandidate;
import com.njcn.gather.icd.mapping.pojo.bo.analysis.IndexCandidateReportItem;
import com.njcn.gather.icd.mapping.pojo.vo.IcdToXmlResponse;
import com.njcn.gather.icd.mapping.pojo.vo.IndexCandidateReportItemResponse;
import com.njcn.gather.icd.mapping.pojo.vo.IndexCandidateResponse;
import com.njcn.gather.icd.mapping.pojo.vo.MappingDocumentResponse;
import com.njcn.gather.icd.mapping.pojo.vo.XmlFileResponse;
import com.njcn.gather.icd.mapping.utils.GeneratedFileNameUtil;
import org.springframework.stereotype.Component;

@Component
public class IcdToXmlResponseConverter {

    /** 默认 XML 展示文件名。 */
    private static final String DEFAULT_XML_FILE_NAME = "mapping.xml";
    /** XML 内容类型。 */
    private static final String XML_CONTENT_TYPE = "application/xml";
    /** XML 文件编码。 */
    private static final String XML_ENCODING = "UTF-8";

    public IcdToXmlResponse fromResult(IcdToXmlGenerateResult result) {
            IcdToXmlResponse response = new IcdToXmlResponse();
            response.setStatus(result.getStatus());
            response.setMessage(result.getMessage());
            response.setIedName(result.getIedName());
            response.setLdInst(result.getLdInst());
            response.setXmlFile(buildXmlFile(result));
            response.getProblems().addAll(result.getProblems());

            if (result.getIndexAnalysis() != null && result.getIndexAnalysis().getCandidates() != null) {
                for (IndexCandidate candidate : result.getIndexAnalysis().getCandidates()) {
                    IndexCandidateResponse candidateResponse = new IndexCandidateResponse();
                    candidateResponse.setGroupKey(candidate.getGroupKey());
                    candidateResponse.setGroupDesc(candidate.getGroupDesc());
                    candidateResponse.setReportCount(candidate.getReportCount());
                    candidateResponse.getTemplateLabels().addAll(candidate.getTemplateLabels());

                    if (candidate.getReports() != null) {
                        for (IndexCandidateReportItem item : candidate.getReports()) {
                            IndexCandidateReportItemResponse itemResponse = new IndexCandidateReportItemResponse();
                            itemResponse.setReportName(item.getReportName());
                            itemResponse.setDataSetName(item.getDataSetName());
                            itemResponse.setReportDesc(item.getReportDesc());
                            itemResponse.getAvailableLnInstValues().addAll(item.getAvailableLnInstValues());
                            candidateResponse.getReports().add(itemResponse);
                        }
                    }

                    response.getIndexCandidates().add(candidateResponse);
                }
            }

            if (result.getMappingDocument() != null) {
                MappingDocumentResponse doc = new MappingDocumentResponse();
                doc.setVersion(result.getMappingDocument().getVersion());
                doc.setAuthor(result.getMappingDocument().getAuthor());
                doc.setIed(result.getMappingDocument().getIed());
                doc.setLd(result.getMappingDocument().getLd());
                doc.setReportCount(result.getMappingDocument().getReportMap() == null
                        ? 0 : result.getMappingDocument().getReportMap().size());
                doc.setDataSetCount(result.getMappingDocument().getDataSetList() == null
                        ? 0 : result.getMappingDocument().getDataSetList().size());
                response.setMappingDocument(doc);
            }

            return response;
        }

    /**
     * 将 XML 内容包装为前端展示用的标准文件容器。
     */
    private XmlFileResponse buildXmlFile(IcdToXmlGenerateResult result) {
        if (result.getXmlContent() == null || result.getXmlContent().isEmpty()) {
            return null;
        }

        XmlFileResponse xmlFile = new XmlFileResponse();
        xmlFile.setFileName(resolveXmlFileName(result));
        xmlFile.setContentType(XML_CONTENT_TYPE);
        xmlFile.setEncoding(XML_ENCODING);
        xmlFile.setContent(result.getXmlContent());
        return xmlFile;
    }

    /**
     * 优先使用 IED 名称构造文件名，缺失时回退默认名。
     */
    private String resolveXmlFileName(IcdToXmlGenerateResult result) {
        String iedName = result.getIedName();
        if (iedName == null || iedName.trim().isEmpty()) {
            return GeneratedFileNameUtil.appendToday(DEFAULT_XML_FILE_NAME);
        }

        String safeName = iedName.replaceAll("[\\\\/:*?\"<>|]+", "_").trim();
        if (safeName.isEmpty()) {
            return GeneratedFileNameUtil.appendToday(DEFAULT_XML_FILE_NAME);
        }
        return GeneratedFileNameUtil.appendToday(safeName + ".xml");
    }
}
