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

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.modules.industryservice.domain.BizGrassland;
import com.ruoyi.web.modules.industryservice.mapper.BizGrasslandMapper;
import com.ruoyi.web.modules.industryservice.service.IBizGrasslandService;
import com.ruoyi.web.modules.industryservice.support.GrasslandRules;
import com.ruoyi.web.modules.industryservice.support.GrasslandValidation;

/**
 * 草场管理服务实现。
 */
@Service
public class BizGrasslandServiceImpl implements IBizGrasslandService
{
    @Autowired
    private BizGrasslandMapper bizGrasslandMapper;

    @Override
    public BizGrassland selectBizGrasslandById(Long id)
    {
        return bizGrasslandMapper.selectBizGrasslandById(id);
    }

    @Override
    public List<BizGrassland> selectBizGrasslandList(BizGrassland query)
    {
        return bizGrasslandMapper.selectBizGrasslandList(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBizGrassland(BizGrassland row)
    {
        GrasslandValidation.validateRowForSave(row);
        row.setDelFlag(GrasslandRules.DEL_FLAG_NORMAL);
        return bizGrasslandMapper.insertBizGrassland(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBizGrassland(BizGrassland row)
    {
        if (row.getId() == null)
        {
            throw new ServiceException("主键不能为空");
        }
        GrasslandValidation.validateRowForSave(row);
        requireActiveRow(row.getId());
        row.setDelFlag(GrasslandRules.DEL_FLAG_NORMAL);
        return bizGrasslandMapper.updateBizGrassland(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBizGrasslandByIds(Long[] ids, String updateBy)
    {
        if (ids == null || ids.length == 0)
        {
            return 0;
        }
        List<Long> cleaned = new ArrayList<>();
        for (Long id : ids)
        {
            if (id != null)
            {
                cleaned.add(id);
            }
        }
        if (cleaned.isEmpty())
        {
            return 0;
        }
        return bizGrasslandMapper.logicDeleteBizGrasslandByIds(cleaned.toArray(new Long[0]), updateBy);
    }

    private BizGrassland requireActiveRow(Long id)
    {
        BizGrassland row = bizGrasslandMapper.selectBizGrasslandById(id);
        if (row == null)
        {
            throw new ServiceException("记录不存在或已删除");
        }
        return row;
    }
}
