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

import java.util.Date;
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.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.industryservice.domain.BizGrassLivestockImbalanceWarning;
import com.ruoyi.web.modules.industryservice.mapper.BizGrassLivestockImbalanceWarningMapper;
import com.ruoyi.web.modules.industryservice.service.IBizGrassLivestockImbalanceWarningService;
import com.ruoyi.web.modules.industryservice.support.GrassLivestockImbalanceWarningRules;

/**
 * 草畜失衡预警查询。
 */
@Service
public class BizGrassLivestockImbalanceWarningServiceImpl implements IBizGrassLivestockImbalanceWarningService
{
    @Autowired
    private BizGrassLivestockImbalanceWarningMapper mapper;

    @Override
    public BizGrassLivestockImbalanceWarning selectById(Long id)
    {
        BizGrassLivestockImbalanceWarning row = mapper.selectById(id);
        if (row == null)
        {
            throw new ServiceException(GrassLivestockImbalanceWarningRules.MSG_NOT_FOUND);
        }
        return row;
    }

    @Override
    public List<BizGrassLivestockImbalanceWarning> selectList(BizGrassLivestockImbalanceWarning query)
    {
        if (query == null)
        {
            query = new BizGrassLivestockImbalanceWarning();
        }
        applyDateRange(query);
        return mapper.selectList(query);
    }

    private void applyDateRange(BizGrassLivestockImbalanceWarning query)
    {
        if (StringUtils.isEmpty(query.getStartDate()) && StringUtils.isEmpty(query.getEndDate()))
        {
            return;
        }
        Date begin = parseDateStart(query.getStartDate());
        Date end = parseDateEnd(query.getEndDate());
        if (begin != null && end != null && begin.after(end))
        {
            throw new ServiceException(GrassLivestockImbalanceWarningRules.MSG_DATE_RANGE_INVALID);
        }
        query.setAlertTimeBegin(begin);
        query.setAlertTimeEnd(end);
    }

    private static Date parseDateStart(String date)
    {
        if (StringUtils.isEmpty(date))
        {
            return null;
        }
        return DateUtils.parseDate(date);
    }

    private static Date parseDateEnd(String date)
    {
        if (StringUtils.isEmpty(date))
        {
            return null;
        }
        Date d = DateUtils.parseDate(date);
        if (d == null)
        {
            return null;
        }
        // 含结束日整天
        return new Date(d.getTime() + 24L * 60 * 60 * 1000 - 1);
    }
}
