package com.hzy.project.business.income.service.impl;

import java.math.BigDecimal;
import java.util.List;

import com.hzy.common.enums.EDelFlag;
import com.hzy.common.utils.DateUtils;
import com.hzy.common.utils.StringUtils;
import com.hzy.project.business.balance.domain.UserBalance;
import com.hzy.project.business.balance.mapper.UserBalanceMapper;
import com.hzy.project.business.balance.service.IUserBalanceService;
import com.hzy.project.business.income.domain.IncomeVo;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hzy.project.business.income.mapper.IncomeMapper;
import com.hzy.project.business.income.domain.Income;
import com.hzy.project.business.income.service.IIncomeService;
import com.hzy.common.utils.text.Convert;

/**
 * 收入Service业务层处理
 * 
 * @author ruoyi
 * @date 2026-01-04
 */
@Service
public class IncomeServiceImpl implements IIncomeService 
{

    @Autowired
    private IncomeMapper incomeMapper;

    @Autowired
    private UserBalanceMapper userBalanceMapper;

    /**
     * 查询收入
     * 
     * @param incomeId 收入主键
     * @return 收入
     */
    @Override
    public Income selectIncomeByIncomeId(Long incomeId)
    {
        return incomeMapper.selectIncomeByIncomeId(incomeId);
    }

    /**
     * 查询收入列表
     * 
     * @param income 收入
     * @return 收入
     */
    @Override
    public List<Income> selectIncomeList(Income income)
    {
        return incomeMapper.selectIncomeList(income);
    }
    @Override
    public List<IncomeVo> selectIncomeVoList(IncomeVo income)
    {
        return incomeMapper.selectIncomeVoList(income);
    }

    /**
     * 新增收入
     * 
     * @param income 收入
     * @return 结果
     */
    @Override
    public int insertIncome(Income income)
    {
        int rtn = 0;
        income.setCreateTime(DateUtils.getNowDate());
        rtn = incomeMapper.insertIncome(income);

        String duration = DateFormatUtils.format(income.getIncomeDate(), "yyyyMM");
        String preDuration = DateFormatUtils.format(DateUtils.addMonths(DateUtils.getNowDate(), -1), "yyyyMM");
        UserBalance condUserBalance = new UserBalance();
        condUserBalance.setUserId(income.getUserId());
        condUserBalance.setDuration(duration);
        condUserBalance.setDelFlag(EDelFlag.NO.getVal());

        List<UserBalance> userBalances = userBalanceMapper.selectUserBalanceList(condUserBalance);

        if (StringUtils.isEmpty(userBalances)) {
            UserBalance condPreUb = new UserBalance();
            condPreUb.setUserId(income.getUserId());
            condPreUb.setDuration(preDuration);
            condPreUb.setDelFlag(EDelFlag.NO.getVal());
            List<UserBalance> preUserBalances = userBalanceMapper.selectUserBalanceList(condPreUb);
            BigDecimal preClosingBalance = BigDecimal.ZERO;
            if (preUserBalances != null && preUserBalances.size() > 0) {
                preClosingBalance = preUserBalances.get(0).getClosingBalance();
            }

            UserBalance userBalance = new UserBalance();
            userBalance.setUserId(income.getUserId());
            userBalance.setDuration(duration);
            userBalance.setOpeningBalance(preClosingBalance);
            userBalance.setIncome(income.getGrossAmount());
            userBalance.setPayment(BigDecimal.ZERO);
            userBalance.setClosingBalance(preClosingBalance.add(income.getGrossAmount()));
            userBalance.setDelFlag(EDelFlag.NO.getVal());
            userBalance.setCreateBy(income.getCreateBy());
            rtn = rtn + userBalanceMapper.insertUserBalance(userBalance);
        } else {
            rtn = rtn + userBalanceMapper.modifyUserBalanceIncome(userBalances.get(0).getBalanceId(), income.getGrossAmount());
        }

        return rtn;
    }

    /**
     * 修改收入
     * 
     * @param income 收入
     * @return 结果
     */
    @Override
    public int updateIncome(Income income)
    {
        int rtn = 0;
        Income oldIncome = incomeMapper.selectIncomeByIncomeId(income.getIncomeId());

        income.setUpdateTime(DateUtils.getNowDate());
        rtn = incomeMapper.updateIncome(income);

        String oldDuration = DateFormatUtils.format(oldIncome.getIncomeDate(), "yyyyMM");
        String duration = DateFormatUtils.format(income.getIncomeDate(), "yyyyMM");
        String preDuration = DateFormatUtils.format(DateUtils.addMonths(income.getIncomeDate(), -1), "yyyyMM");

        UserBalance condOldUserBalance = new UserBalance();
        condOldUserBalance.setUserId(income.getUserId());
        condOldUserBalance.setDuration(oldDuration);
        condOldUserBalance.setDelFlag(EDelFlag.NO.getVal());

        List<UserBalance> oldUbs = userBalanceMapper.selectUserBalanceList(condOldUserBalance);

        if (StringUtils.isEmpty(oldUbs)) {

        } else {

            Long oldBalanceId = oldUbs.get(0).getBalanceId();

            rtn = rtn + userBalanceMapper.modifyUserBalanceIncome(oldBalanceId, oldIncome.getGrossAmount().negate());
        }

        UserBalance condNewUserBalance = new UserBalance();
        condNewUserBalance.setUserId(income.getUserId());
        condNewUserBalance.setDuration(duration);
        condNewUserBalance.setDelFlag(EDelFlag.NO.getVal());

        List<UserBalance> ubs = userBalanceMapper.selectUserBalanceList(condNewUserBalance);
        if (StringUtils.isEmpty(ubs)) {

            UserBalance condPreUb = new UserBalance();
            condPreUb.setUserId(income.getUserId());
            condPreUb.setDuration(preDuration);
            condPreUb.setDelFlag(EDelFlag.NO.getVal());
            List<UserBalance> preUserBalances = userBalanceMapper.selectUserBalanceList(condPreUb);
            BigDecimal preClosingBalance = BigDecimal.ZERO;
            if (preUserBalances != null && !preUserBalances.isEmpty()) {
                preClosingBalance = preUserBalances.get(0).getClosingBalance();
            }

            UserBalance userBalance = new UserBalance();
            userBalance.setUserId(income.getUserId());
            userBalance.setDuration(duration);
            userBalance.setOpeningBalance(preClosingBalance);
            userBalance.setIncome(income.getGrossAmount());
            userBalance.setPayment(BigDecimal.ZERO);
            userBalance.setClosingBalance(preClosingBalance.add(income.getGrossAmount()));
            userBalance.setDelFlag(EDelFlag.NO.getVal());
            userBalance.setCreateBy(income.getCreateBy());
            rtn = rtn + userBalanceMapper.insertUserBalance(userBalance);

        } else {
            Long balanceId = ubs.get(0).getBalanceId();
            rtn = rtn + userBalanceMapper.modifyUserBalanceIncome(balanceId, income.getGrossAmount());
        }

        return rtn;
    }

    /**
     * 批量删除收入
     * 
     * @param incomeIds 需要删除的收入主键
     * @return 结果
     */
    @Override
    public int deleteIncomeByIncomeIds(String incomeIds)
    {
        int rtn = 0;
        String[] ids = Convert.toStrArray(incomeIds);

        for (String incomeId : ids) {
            Income oldIncome = incomeMapper.selectIncomeByIncomeId(Long.valueOf(incomeId));
            String oldDuration = DateFormatUtils.format(oldIncome.getIncomeDate(), "yyyyMM");

            UserBalance condOldUserBalance = new UserBalance();
            condOldUserBalance.setUserId(oldIncome.getUserId());
            condOldUserBalance.setDuration(oldDuration);
            condOldUserBalance.setDelFlag(EDelFlag.NO.getVal());

            List<UserBalance> oldUbs = userBalanceMapper.selectUserBalanceList(condOldUserBalance);

            if (oldUbs != null && !oldUbs.isEmpty()) {
                Long oldBalanceId = oldUbs.get(0).getBalanceId();
                rtn = rtn + userBalanceMapper.modifyUserBalanceIncome(oldBalanceId, oldIncome.getGrossAmount().negate());
            }
        }

        rtn = rtn + incomeMapper.logicDelIncomeByIncomeIds(ids);

        return rtn;
    }

    /**
     * 删除收入信息
     *
     * @param incomeId 收入主键
     * @return 结果
     */
    @Override
    public int deleteIncomeByIncomeId(Long incomeId)
    {
        return incomeMapper.deleteIncomeByIncomeId(incomeId);
    }
}
