package com.ruoyi.web.modules.architecture.service.impl;

import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.architecture.domain.AppMedicationIncompatibilityGroupRow;
import com.ruoyi.web.modules.architecture.domain.AppMedicationDrugQueryVo;
import com.ruoyi.web.modules.architecture.domain.BizWithdrawalPeriodStandard;
import com.ruoyi.web.modules.architecture.mapper.AppMedicationDrugMapper;
import com.ruoyi.web.modules.architecture.service.IAppMedicationDrugService;
import com.ruoyi.web.modules.architecture.support.AppMedicationDrugNameSupport;
import com.ruoyi.web.modules.architecture.support.AppMedicationIncompatibilityDisplaySupport;
import com.ruoyi.web.modules.architecture.support.WithdrawalPeriodStandardDrugType;

/**
 * 移动端用药工具 — 查询药物。
 */
@Service
public class AppMedicationDrugServiceImpl implements IAppMedicationDrugService
{
    private static final int DRUG_NAME_OPTIONS_LIMIT = 50;

    @Autowired
    private AppMedicationDrugMapper appMedicationDrugMapper;

    @Override
    public List<String> selectDrugNameOptions(String keyword)
    {
        String kw = StringUtils.isNotEmpty(keyword) ? keyword.trim() : null;
        if (kw != null && kw.length() > 20)
        {
            throw new ServiceException("检索关键字不能超过20个字符");
        }
        List<String> list = appMedicationDrugMapper.selectDistinctDrugNames(kw, DRUG_NAME_OPTIONS_LIMIT);
        return list != null ? list : Collections.emptyList();
    }

    @Override
    public AppMedicationDrugQueryVo queryByDrugName(String drugName)
    {
        String name = AppMedicationDrugNameSupport.requireDrugName(drugName);
        BizWithdrawalPeriodStandard row = appMedicationDrugMapper.selectWithdrawalByDrugName(name);
        if (row == null)
        {
            throw new ServiceException("未找到该药物标准信息");
        }
        AppMedicationDrugQueryVo vo = new AppMedicationDrugQueryVo();
        vo.setDrugName(row.getDrugName());
        vo.setDrugType(row.getDrugType());
        vo.setDrugTypeName(WithdrawalPeriodStandardDrugType.nameOf(row.getDrugType()));
        vo.setWithdrawalDays(row.getWithdrawalDays());
        vo.setUsageGuide(row.getUsageGuide());
        vo.setDrugEffect(row.getDrugEffect());
        List<AppMedicationIncompatibilityGroupRow> groups = appMedicationDrugMapper
                .selectIncompatibilityGroupsByMainDrugName(name);
        String companions = AppMedicationIncompatibilityDisplaySupport.formatGroupsForDisplay(groups);
        if (StringUtils.isNotEmpty(companions))
        {
            vo.setIncompatibilityCompanions(companions);
        }
        return vo;
    }
}
