package com.openhis.web.regdoctorstation.utils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.core.common.utils.AssignSeqUtil;
import com.openhis.common.enums.AssignSeqEnum;
import com.openhis.web.regdoctorstation.dto.RegAdviceSaveDto;

/**
 * 住院处方号工具类
 */
@Component
public class RegPrescriptionUtils {

    @Resource
    private AssignSeqUtil assignSeqUtil;

    /**
     * 主入口：生成处方号
     */
    public void generatePrescriptionNumbers(List<RegAdviceSaveDto> medicineList) {
        if (medicineList == null || medicineList.isEmpty()) {
            return;
        }
        // 1. 按诊断ID分组（不同诊断必须分开）
        Map<Long, List<RegAdviceSaveDto>> diagnosisGroups =
            medicineList.stream().collect(Collectors.groupingBy(RegAdviceSaveDto::getConditionDefinitionId));
        // 2. 处理每个诊断组
        diagnosisGroups.values().forEach(this::processDiagnosisGroup);
    }

    /**
     * 处理单个诊断组
     */
    private void processDiagnosisGroup(List<RegAdviceSaveDto> diagnosisGroup) {
        if (diagnosisGroup.isEmpty()) {
            return;
        }
        // 1. 按药品性质分组
        Map<String, List<RegAdviceSaveDto>> pharmacologyGroups =
            diagnosisGroup.stream().collect(Collectors.groupingBy(RegAdviceSaveDto::getPharmacologyCategoryCode));
        // 2. 处理每个药品性质组
        pharmacologyGroups.values().forEach(pharmaGroup -> {
            // 2.1 按治疗类型分组
            Map<Integer, List<RegAdviceSaveDto>> therapyGroups =
                pharmaGroup.stream().collect(Collectors.groupingBy(RegAdviceSaveDto::getTherapyEnum));
            // 2.2 为每组治疗类型生成唯一处方号
            therapyGroups.forEach((therapyEnum, group) -> {
                String prescriptionNo = generatePrescriptionNo(pharmaGroup.get(0).getPharmacologyCategoryCode());
                group.forEach(medicine -> medicine.setPrescriptionNo(prescriptionNo));
            });
        });
    }

    /**
     * 根据药品性质生成处方号（前缀规则与原工具类一致）
     */
    private String generatePrescriptionNo(String pharmacologyCategoryCode) {
        switch (pharmacologyCategoryCode) {
            case "2": // 麻醉药品
                return assignSeqUtil.getSeq(AssignSeqEnum.PRESCRIPTION_NARCOTIC_NO.getPrefix(), 8);
            case "3": // 毒性药品
                return assignSeqUtil.getSeq(AssignSeqEnum.PRESCRIPTION_TOXIC_NO.getPrefix(), 8);
            case "4": // 一类精神药
                return assignSeqUtil.getSeq(AssignSeqEnum.PRESCRIPTION_A_PSYCHOTROPIC_NO.getPrefix(), 8);
            case "5": // 二类精神药
                return assignSeqUtil.getSeq(AssignSeqEnum.PRESCRIPTION_B_PSYCHOTROPIC_NO.getPrefix(), 8);
            default: // 普通药品
                return assignSeqUtil.getSeq(AssignSeqEnum.PRESCRIPTION_COMMON_NO.getPrefix(), 8);
        }
    }

}
