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

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.finance.payrefund.entity.PayRefundOrder;
import com.jeesharp.business.modules.finance.payrefund.mapper.PayRefundOrderMapper;
import com.jeesharp.business.modules.finance.payrefund.service.PayRefundOrderService;
import com.jeesharp.business.modules.finance.payrefund.vo.PayRefundOrderQueryVO;
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;

import java.math.BigDecimal;

/**
 * 支付退款单领域服务实现。
 *
 * @author jeesharp
 * @since 2026-06-11
 */
@Service
@Transactional(readOnly = true)
public class PayRefundOrderServiceImpl extends CrudService<PayRefundOrderMapper, PayRefundOrder, PayRefundOrderQueryVO>
        implements PayRefundOrderService {

    @Override
    public PayRefundOrder getByOutRefundNo(String outRefundNo) {
        if (StrUtil.isBlank(outRefundNo)) {
            return null;
        }
        return getBaseMapper().getByOutRefundNo(outRefundNo.trim());
    }

    @Override
    public BigDecimal sumSuccessRefundAmountByMallOrderId(String mallOrderId) {
        if (StrUtil.isBlank(mallOrderId)) {
            return BigDecimal.ZERO;
        }
        BigDecimal sum = getBaseMapper().sumSuccessRefundAmountByMallOrderId(mallOrderId.trim());
        return sum == null ? BigDecimal.ZERO : sum;
    }

    @Override
    public PayRefundOrder findActiveByAfterSaleId(String afterSaleId) {
        if (StrUtil.isBlank(afterSaleId)) {
            return null;
        }
        return getBaseMapper().findActiveByAfterSaleId(afterSaleId.trim());
    }

    @Override
    @Transactional(readOnly = false)
    public PayRefundOrder createRefundOrder(PayRefundOrder order) {
        if (StrUtil.isNotBlank(order.getId())) {
            throw new BizErrorException("新增退款单不应预置主键");
        }
        order.preInsert();
        if (StrUtil.isBlank(order.getDelFlag())) {
            order.setDelFlag("0");
        }
        getBaseMapper().insert(order);
        return order;
    }

    @Override
    @Transactional(readOnly = false)
    public void updateRefundOrder(PayRefundOrder order) {
        if (StrUtil.isBlank(order.getId())) {
            throw new BizErrorException("更新退款单主键不能为空");
        }
        if (get(order.getId()) == null) {
            throw new BizErrorException("退款单不存在");
        }
        getBaseMapper().update(order);
    }
}
