package com.ruoyi.web.modules.architecture.support;

import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.kb.support.KbMarkdownGenerator;
import com.ruoyi.web.modules.architecture.domain.BizDrugIncompatibilityCompanion;
import com.ruoyi.web.modules.architecture.domain.BizDrugIncompatibilityStandard;
import com.ruoyi.web.modules.architecture.mapper.BizDrugIncompatibilityCompanionMapper;

/**
 * 药物禁配标准同步知识库前，按模板生成 Markdown 文件。
 */
@Component
public class DrugIncompatibilityStandardKbMarkdown
{
    public static final String TEMPLATE_FILE = "biz_drug_incompatibility_standard.md";

    public static final String OUTPUT_FILE_PREFIX = "药物禁配标准_";

    @Autowired
    private KbMarkdownGenerator kbMarkdownGenerator;

    @Autowired
    private BizDrugIncompatibilityCompanionMapper bizDrugIncompatibilityCompanionMapper;

    /**
     * 生成 {@code {profile}/template/药物禁配标准_{id}.md}。
     */
    public Path generateForSync(BizDrugIncompatibilityStandard row)
    {
        if (row == null || row.getId() == null)
        {
            throw new ServiceException("药物禁配标准主键为空，无法生成知识库 Markdown");
        }
        Map<String, String> placeholders = new LinkedHashMap<>();
        placeholders.put("mainDrugName", StringUtils.nvl(row.getMainDrugName(), ""));
        placeholders.put("compatibilityDrugs", formatCompanionDrugNames(row.getId()));
        placeholders.put("compatResult", StringUtils.nvl(row.getCompatResult(), ""));
        String outputName = OUTPUT_FILE_PREFIX + row.getId() + ".md";
        return kbMarkdownGenerator.generateFromTemplate(TEMPLATE_FILE, outputName, placeholders);
    }

    /**
     * 子表配伍药物名称，按库中顺序逗号拼接。
     */
    public String formatCompanionDrugNames(Long standardId)
    {
        List<BizDrugIncompatibilityCompanion> companions =
                bizDrugIncompatibilityCompanionMapper.selectBizDrugIncompatibilityCompanionListByStandardId(standardId);
        if (companions == null || companions.isEmpty())
        {
            return "";
        }
        return companions.stream()
                .map(BizDrugIncompatibilityCompanion::getCompanionDrugName)
                .filter(StringUtils::isNotEmpty)
                .map(String::trim)
                .collect(Collectors.joining(","));
    }
}
