package com.ruoyi.bst.credit.service.impl;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.ruoyi.bst.credit.domain.Credit;
import com.ruoyi.bst.credit.domain.CreditQuery;
import com.ruoyi.bst.credit.domain.CreditVO;
import com.ruoyi.bst.credit.mapper.CreditMapper;
import com.ruoyi.bst.credit.service.CreditService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MathUtils;
import com.ruoyi.common.utils.collection.CollectionUtils;

/**
 * 挂账方Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-27
 */
@Service
public class CreditServiceImpl implements CreditService
{
    @Autowired
    private CreditMapper creditMapper;

    /**
     * 查询挂账方
     *
     * @param id 挂账方主键
     * @return 挂账方
     */
    @Override
    public CreditVO selectCreditById(Long id, boolean scope)
    {
        if (id == null) {
            return null;
        }
        CreditQuery query = new CreditQuery();
        query.setId(id);
        query.setScope(scope);
        return this.selectOne(query);
    }

    private CreditVO selectOne(CreditQuery query) {
        PageHelper.startPage(1, 1);
        List<CreditVO> list = this.selectCreditList(query);
        return CollectionUtils.firstElement(list);
    }

    /**
     * 查询挂账方列表
     *
     * @param credit 挂账方
     * @return 挂账方
     */
    @Override
    public List<CreditVO> selectCreditList(CreditQuery credit)
    {
        return creditMapper.selectCreditList(credit);
    }

    /**
     * 新增挂账方
     *
     * @param credit 挂账方
     * @return 结果
     */
    @Override
    public int insertCredit(Credit credit)
    {
        credit.setCreateTime(DateUtils.getNowDate());
        return creditMapper.insertCredit(credit);
    }

    /**
     * 修改挂账方
     *
     * @param credit 挂账方
     * @return 结果
     */
    @Override
    public int updateCredit(Credit credit)
    {
        return creditMapper.updateCredit(credit);
    }

    /**
     * 逻辑删除挂账方
     *
     * @param ids 需要删除的挂账方主键
     * @return 结果
     */
    @Override
    public int logicDel(List<Long> ids){
        if (CollectionUtils.isEmptyElement(ids)) {
            return 0;
        }
        return creditMapper.logicDel(ids);
    }

    @Override
    public int addUsedAmount(Long id, BigDecimal amount) {
        if (id == null || amount == null) {
            return 0;
        }
        if (MathUtils.equals(amount, BigDecimal.ZERO)) {
            return 1;
        }
        return creditMapper.addUsedAmount(id, amount);
    }
}
