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

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
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.BizDisposableIncome;
import com.ruoyi.web.modules.industryservice.mapper.BizDisposableIncomeMapper;
import com.ruoyi.web.modules.industryservice.service.IBizDisposableIncomeService;
import com.ruoyi.web.modules.industryservice.support.DisposableIncomeGrowthSupport;
import com.ruoyi.web.modules.industryservice.support.DisposableIncomeValidation;
import com.ruoyi.web.modules.industryservice.support.YakHerdInventoryYearSupport;

/**
 * 可支配收入数据填报服务实现
 */
@Service
public class BizDisposableIncomeServiceImpl implements IBizDisposableIncomeService
{
    @Autowired
    private BizDisposableIncomeMapper bizDisposableIncomeMapper;

    @Override
    public BizDisposableIncome selectBizDisposableIncomeById(Long id)
    {
        return bizDisposableIncomeMapper.selectBizDisposableIncomeById(id);
    }

    @Override
    public List<BizDisposableIncome> selectBizDisposableIncomeList(BizDisposableIncome query)
    {
        return bizDisposableIncomeMapper.selectBizDisposableIncomeList(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBizDisposableIncome(BizDisposableIncome row)
    {
        DisposableIncomeValidation.validateRowForSave(row);
        assertUniqueYear(row.getStatYear(), null);
        applyGrowthForSave(row, null);
        return bizDisposableIncomeMapper.insertBizDisposableIncome(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBizDisposableIncome(BizDisposableIncome row)
    {
        if (row.getId() == null)
        {
            throw new ServiceException("主键不能为空");
        }
        DisposableIncomeValidation.validateRowForSave(row);
        BizDisposableIncome existing = requireExistingRow(row.getId());
        assertUniqueYear(row.getStatYear(), row.getId());
        applyGrowthForSave(row, existing);
        return bizDisposableIncomeMapper.updateBizDisposableIncome(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBizDisposableIncomeByIds(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 bizDisposableIncomeMapper.deleteBizDisposableIncomeByIds(cleaned.toArray(new Long[0]));
    }

    @Override
    public List<Integer> listYearOptions()
    {
        return YakHerdInventoryYearSupport.resolveYearOptions();
    }

    /**
     * 年份或可支配收入变更时按新口径强制重算；否则仅对未填的增幅/增速补齐。
     */
    private void applyGrowthForSave(BizDisposableIncome row, BizDisposableIncome existing)
    {
        if (row == null || row.getStatYear() == null)
        {
            return;
        }
        BizDisposableIncome previous = bizDisposableIncomeMapper.selectByStatYear(row.getStatYear() - 1);
        boolean yearOrIncomeChanged = existing != null && (!Objects.equals(existing.getStatYear(), row.getStatYear())
                || !DisposableIncomeGrowthSupport.sameDecimal(existing.getRuralDisposableIncome(),
                        row.getRuralDisposableIncome()));
        if (yearOrIncomeChanged)
        {
            DisposableIncomeGrowthSupport.recalculateGrowth(row, previous);
        }
        else
        {
            DisposableIncomeGrowthSupport.fillMissingGrowth(row, previous);
        }
    }

    private void assertUniqueYear(Integer statYear, Long excludeId)
    {
        int count = bizDisposableIncomeMapper.countByStatYearExcludeId(statYear, excludeId);
        if (count > 0)
        {
            throw new ServiceException("该年份数据已存在");
        }
    }

    private BizDisposableIncome requireExistingRow(Long id)
    {
        BizDisposableIncome existing = bizDisposableIncomeMapper.selectBizDisposableIncomeById(id);
        if (existing == null)
        {
            throw new ServiceException("记录不存在或已删除");
        }
        return existing;
    }
}
