package com.yn.bftl.thirdparty.modules.business.service.impl;

import com.yn.bftl.common.common.exception.YnceError;
import com.yn.bftl.common.modules.order.entity.Refund;
import com.yn.bftl.common.modules.order.enums.RefundStatus;
import com.yn.bftl.thirdparty.common.exception.YnceErrorException;
import com.yn.bftl.thirdparty.common.repository.RefundRepository;
import com.yn.bftl.thirdparty.modules.business.dto.RefundSubaccountDTO;
import com.yn.bftl.thirdparty.modules.business.service.RefundService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author huabiao
 * @create 2023/5/4  18:14
 **/
@Service
public class RefundServiceImpl implements RefundService {

    @Resource
    private RefundRepository refundRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleSubaccountRefund(RefundSubaccountDTO subaccountRefundDTO) {
        // 获取退款单
        Refund refund = refundRepository.findFirstByRefundSn(subaccountRefundDTO.getRefundSn());
        if (refund == null) {
            throw new YnceErrorException(YnceError.YNCE_204028);
        }
        refund.setRefundTime(subaccountRefundDTO.getRefundTime());
        refund.setActualAmount(refund.getActualAmount().add(subaccountRefundDTO.getRefundAmount()));
        if (StringUtils.isBlank(refund.getThirdPartyAccount())) {
            refund.setThirdPartyAccount(subaccountRefundDTO.getExternalId());
        } else {
            refund.setThirdPartyAccount(refund.getThirdPartyAccount() + "," + subaccountRefundDTO.getExternalId());
        }
        // 根据实际退款金额判断状态（仅对非售后单据操作）
        if (refund.getAfterSale() == null) {
            if (refund.getAmount().compareTo(refund.getActualAmount()) == 0) {
                refund.setRefundStatus(RefundStatus.REFUNDED);
            } else {
                refund.setRefundStatus(RefundStatus.PARTIAL_REFUNDED);
            }
        }
        refund.setUnionpayRefundSn(refund.getThirdPartyAccount());
        refund.setIsSeparateAccounts(true);
        refundRepository.save(refund);
    }
}
