package com.hzs.sale.refund.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.hzs.common.core.constant.MagicNumberConstants;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.domain.sale.order.SaRefund;
import com.hzs.sale.refund.service.IRefundBusinessService;
import com.hzs.sale.refund.service.ISaRefundService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 退款业务服务
 */
@Slf4j
@Service
public class RefundBusinessServiceImpl implements IRefundBusinessService {

    @Autowired
    private ISaRefundService iSaRefundService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String refundOnlineCallback(String orderCode, String refundCode, Integer refundStatus, String refundMsg) {
        // 存在退款单号处理
        if (StringUtils.isNotEmpty(refundCode)) {
            LambdaQueryWrapper<SaRefund> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SaRefund::getRefundCode, refundCode);
            SaRefund saRefund = iSaRefundService.getOne(queryWrapper);
            if (null == saRefund) {
                return "订单售后信息已不存在";
            }

            LambdaUpdateWrapper<SaRefund> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(SaRefund::getPkId, saRefund.getPkId());
            updateWrapper.set(SaRefund::getRefundStatus, refundStatus);
            updateWrapper.set(SaRefund::getRefundRemark, refundMsg);
            updateWrapper.set(SaRefund::getPkModified, MagicNumberConstants.PK_ADMIN);
            updateWrapper.set(SaRefund::getModifiedTime, new Date());
            if (!iSaRefundService.update(updateWrapper)) {
                return "直销订单在线支付退款，更新退款单失败";
            }
        }
        return null;
    }
}
