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

import com.njcn.gather.icd.mapping.config.MappingModuleConfig;
import com.njcn.gather.icd.mapping.pojo.dto.GenerateFromIcdCommand;
import com.njcn.gather.icd.mapping.pojo.dto.IndexBindingCommand;
import com.njcn.gather.icd.mapping.pojo.dto.IndexSelectionGroupCommand;
import com.njcn.gather.icd.mapping.pojo.param.GenerateMappingFromIcdRequest;
import com.njcn.gather.icd.mapping.pojo.param.IndexBindingRequest;
import com.njcn.gather.icd.mapping.pojo.param.IndexSelectionGroupRequest;
import com.njcn.gather.icd.mapping.pojo.param.SubmitIndexSelectionRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 请求转换器。
 *
 * 作用：
 * 1. 将接口层 request 转成应用层 command；
 * 2. 统一处理 null 和空集合，避免后续业务层到处判空。
 */
@Component
public class MappingRequestConverter {

    /** 模块默认配置，用于补齐作者、输出目录等缺省值。 */
    private final MappingModuleConfig moduleConfig;

    public MappingRequestConverter(MappingModuleConfig moduleConfig) {
        this.moduleConfig = moduleConfig;
    }

    /**
     * 将候选接口上传文件转换为应用层命令，其他参数走模块默认值。
     */
    public GenerateFromIcdCommand toCommand(MultipartFile icdFile) {
        return toCommand(icdFile, null);
    }

    /**
     * 将上传文件和请求体转换为应用层命令。
     */
    public GenerateFromIcdCommand toCommand(MultipartFile icdFile, GenerateMappingFromIcdRequest request) {
        try {
            if (icdFile == null || icdFile.isEmpty()) {
                throw new IllegalArgumentException("ICD 文件不能为空");
            }
            GenerateFromIcdCommand command = new GenerateFromIcdCommand();
            command.setFileName(icdFile.getOriginalFilename());
            command.setFileBytes(icdFile.getBytes());
            command.setVersion(request == null ? null : request.getVersion());
            command.setAuthor(resolveText(request == null ? null : request.getAuthor(), moduleConfig.getDefaultAuthor()));
            command.setSaveToDisk(request != null && request.isSaveToDisk());
            command.setPrettyJson(request != null && request.isPrettyJson());
            command.setOutputDir(resolveText(request == null ? null : request.getOutputDir(), moduleConfig.getDefaultOutputDir()));
            fillIndexSelection(command, request == null ? null : request.getIndexSelection());
            return command;
        } catch (Exception ex) {
            throw new IllegalArgumentException("请求转换失败：" + ex.getMessage(), ex);
        }
    }

    /**
     * 将提交绑定接口请求体转换为应用层命令。
     */
    public GenerateFromIcdCommand toCommand(SubmitIndexSelectionRequest request) {
        try {
            if (request == null) {
                throw new IllegalArgumentException("请求体不能为空");
            }
            if (request.getIcdDocument() == null) {
                throw new IllegalArgumentException("ICD 解析结果不能为空");
            }

            GenerateFromIcdCommand command = new GenerateFromIcdCommand();
            command.setIcdDocument(request.getIcdDocument());
            command.setFileName(request.getIcdDocument().getFileName());
            command.setVersion(request.getVersion());
            command.setAuthor(resolveText(request.getAuthor(), moduleConfig.getDefaultAuthor()));
            command.setSaveToDisk(request.isSaveToDisk());
            command.setPrettyJson(request.isPrettyJson());
            command.setOutputDir(resolveText(request.getOutputDir(), moduleConfig.getDefaultOutputDir()));
            fillIndexSelection(command, request.getIndexSelection());
            return command;
        } catch (Exception ex) {
            throw new IllegalArgumentException("请求转换失败：" + ex.getMessage(), ex);
        }
    }

    /**
     * 复制前端提交的索引绑定结构。
     */
    private void fillIndexSelection(GenerateFromIcdCommand command, List<IndexSelectionGroupRequest> indexSelection) {
        if (indexSelection == null) {
            return;
        }
        for (IndexSelectionGroupRequest groupRequest : indexSelection) {
            if (groupRequest == null) {
                continue;
            }
            IndexSelectionGroupCommand groupCommand = new IndexSelectionGroupCommand();
            groupCommand.setGroupKey(groupRequest.getGroupKey());
            groupCommand.setGroupDesc(groupRequest.getGroupDesc());

            if (groupRequest.getBindings() != null) {
                for (IndexBindingRequest bindingRequest : groupRequest.getBindings()) {
                    if (bindingRequest == null) {
                        continue;
                    }
                    IndexBindingCommand bindingCommand = new IndexBindingCommand();
                    bindingCommand.setReportName(bindingRequest.getReportName());
                    bindingCommand.setDataSetName(bindingRequest.getDataSetName());
                    bindingCommand.setLabel(bindingRequest.getLabel());
                    bindingCommand.setLnInst(bindingRequest.getLnInst());
                    groupCommand.getBindings().add(bindingCommand);
                }
            }

            command.getIndexSelection().add(groupCommand);
        }
    }

    /**
     * 统一处理文本参数的 trim 和默认值回退。
     */
    private String resolveText(String value, String defaultValue) {
        if (value != null && !value.trim().isEmpty()) {
            return value.trim();
        }
        return defaultValue == null ? null : defaultValue.trim();
    }
}
