package com.jeesharp.business.modules.finance.profitsharing.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jeesharp.business.modules.finance.profitsharing.entity.ProfitSharingReturn;
import com.jeesharp.business.modules.finance.profitsharing.mapper.ProfitSharingReturnMapper;
import com.jeesharp.business.modules.finance.profitsharing.service.ProfitSharingReturnService;
import com.jeesharp.business.modules.finance.profitsharing.vo.ProfitSharingReturnQueryVO;
import com.jeesharp.framework.exception.BizErrorException;
import com.jeesharp.framework.mybatis.core.service.CrudService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 分账回退单领域服务实现。
 *
 * @author jeesharp
 * @since 2026-06-11
 */
@Service
@Transactional(readOnly = true)
public class ProfitSharingReturnServiceImpl
        extends CrudService<ProfitSharingReturnMapper, ProfitSharingReturn, ProfitSharingReturnQueryVO>
        implements ProfitSharingReturnService {

    @Override
    public ProfitSharingReturn findByPayRefundOrderId(String payRefundOrderId) {
        if (StrUtil.isBlank(payRefundOrderId)) {
            return null;
        }
        LambdaQueryWrapper<ProfitSharingReturn> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProfitSharingReturn::getPayRefundOrderId, payRefundOrderId.trim());
        wrapper.last("LIMIT 1");
        return getBaseMapper().selectOne(wrapper);
    }

    @Override
    public int sumSuccessReturnFenByProfitSharingOrderId(String profitSharingOrderId) {
        if (StrUtil.isBlank(profitSharingOrderId)) {
            return 0;
        }
        Integer sum = getBaseMapper().sumSuccessReturnFenByProfitSharingOrderId(profitSharingOrderId.trim());
        return sum == null ? 0 : sum;
    }

    @Override
    @Transactional(readOnly = false)
    public ProfitSharingReturn createReturnOrder(ProfitSharingReturn entity) {
        if (StrUtil.isNotBlank(entity.getId())) {
            throw new BizErrorException("新增分账回退单不应预置主键");
        }
        save(entity);
        return entity;
    }

    @Override
    @Transactional(readOnly = false)
    public void updateReturnOrder(ProfitSharingReturn entity) {
        if (StrUtil.isBlank(entity.getId())) {
            throw new BizErrorException("更新分账回退单主键不能为空");
        }
        update(entity);
    }
}
