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

import java.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.modules.architecture.domain.AppMedicationWithdrawalCalculateVo;
import com.ruoyi.web.modules.architecture.domain.BizWithdrawalPeriodStandard;
import com.ruoyi.web.modules.architecture.mapper.AppMedicationDrugMapper;
import com.ruoyi.web.modules.architecture.service.IAppMedicationWithdrawalService;
import com.ruoyi.web.modules.architecture.support.AppMedicationDrugNameSupport;
import com.ruoyi.web.modules.architecture.support.AppMedicationStopDateSupport;

/**
 * 移动端用药工具 — 计算休药期。
 */
@Service
public class AppMedicationWithdrawalServiceImpl implements IAppMedicationWithdrawalService
{
    @Autowired
    private AppMedicationDrugMapper appMedicationDrugMapper;

    @Override
    public AppMedicationWithdrawalCalculateVo calculate(String drugName, String stopDate)
    {
        String name = AppMedicationDrugNameSupport.requireDrugName(drugName);
        LocalDate stop = AppMedicationStopDateSupport.parseStopDate(stopDate);

        BizWithdrawalPeriodStandard row = appMedicationDrugMapper.selectWithdrawalByDrugName(name);
        if (row == null)
        {
            throw new ServiceException("未找到该药物标准信息");
        }
        Integer withdrawalDays = row.getWithdrawalDays();
        if (withdrawalDays == null || withdrawalDays < 1)
        {
            throw new ServiceException("该药物休药期天数无效");
        }

        LocalDate end = stop.plusDays(withdrawalDays.longValue());

        AppMedicationWithdrawalCalculateVo vo = new AppMedicationWithdrawalCalculateVo();
        vo.setDrugName(row.getDrugName());
        vo.setStopDate(AppMedicationStopDateSupport.formatDate(stop));
        vo.setWithdrawalDays(withdrawalDays);
        vo.setEndDate(AppMedicationStopDateSupport.formatDate(end));
        return vo;
    }
}
