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

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.AppMedicationCompatibilityCheckVo;
import com.ruoyi.web.modules.architecture.mapper.AppMedicationDrugMapper;
import com.ruoyi.web.modules.architecture.service.IAppMedicationCompatibilityService;
import com.ruoyi.web.modules.architecture.support.AppMedicationDrugNameSupport;

/**
 * 移动端用药工具 — 用药配伍。
 */
@Service
public class AppMedicationCompatibilityServiceImpl implements IAppMedicationCompatibilityService
{
    @Autowired
    private AppMedicationDrugMapper appMedicationDrugMapper;

    @Override
    public AppMedicationCompatibilityCheckVo checkCompatibility(String drugName1, String drugName2)
    {
        String name1 = AppMedicationDrugNameSupport.requireDrugName(drugName1);
        String name2 = AppMedicationDrugNameSupport.requireDrugName(drugName2);
        if (name1.equals(name2))
        {
            throw new ServiceException("请选择两种不同的药物");
        }

        boolean dir1 = appMedicationDrugMapper.countIncompatibilityPair(name1, name2) > 0;
        boolean dir2 = appMedicationDrugMapper.countIncompatibilityPair(name2, name1) > 0;
        boolean hasIncompatibility = dir1 || dir2;

        AppMedicationCompatibilityCheckVo vo = new AppMedicationCompatibilityCheckVo();
        vo.setDrugName1(name1);
        vo.setDrugName2(name2);
        vo.setHasIncompatibility(Boolean.valueOf(hasIncompatibility));

        if (hasIncompatibility)
        {
            String mainForResult = dir1 ? name1 : name2;
            String companionForResult = dir1 ? name2 : name1;
            String compatResult = appMedicationDrugMapper.selectCompatResultByPair(mainForResult, companionForResult);
            if (StringUtils.isNotEmpty(compatResult))
            {
                vo.setCompatResult(compatResult.trim());
            }
        }
        return vo;
    }
}
