package com.ruoyi.ss.refund.service.impl;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.ss.order.domain.OrderVO;
import com.ruoyi.ss.order.service.IOrderService;
import com.ruoyi.ss.payBill.domain.PayBillVO;
import com.ruoyi.ss.payBill.domain.enums.PayBillStatus;
import com.ruoyi.ss.payBill.service.PayBillService;
import com.ruoyi.ss.refund.domain.Refund;
import com.ruoyi.ss.refund.domain.RefundBO;
import com.ruoyi.ss.refund.domain.RefundDTO;
import com.ruoyi.ss.refund.mapper.RefundMapper;
import com.ruoyi.ss.refund.service.IRefundValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Objects;

import static com.ruoyi.common.constant.ServiceConstants.ORDER_PAY_STATUS_NON_PAYMENT;
import static com.ruoyi.common.constant.ServiceConstants.ORDER_STATUS_COMPLETED;

/**
 * 退款订单Service业务层处理
 *
 * @author 邱贞招
 * @date 2024-05-10
 */
@Service
public class RefundValidatormpl implements IRefundValidator
{

    @Resource
    private IOrderService orderService;

    @Autowired
    private PayBillService paymentService;

    @Override
    public RefundBO preRefund(RefundDTO dto) {
        // todo  退款前验证
        PayBillVO payBillVO = paymentService.selectPayBillByPayId(dto.getPayId());
        ServiceUtil.assertion(payBillVO == null, "支付单不存在");
        OrderVO orderVO = orderService.selectRlOrderByOrderNo(payBillVO.getOrderNo());
        ServiceUtil.assertion(orderVO == null, "订单不存在");
        Long userId = SecurityUtils.getUserId();
        if(!SecurityUtils.isAdmin(userId)){
            ServiceUtil.assertion(!Objects.equals(orderVO.getMerchantId(), userId), "不是本商户下的订单不能操作");
        }
        ServiceUtil.assertion(ORDER_PAY_STATUS_NON_PAYMENT.equals(orderVO.getPaid()), "订单未支付，不能发起退款");
        ServiceUtil.assertion(dto.getAmount().compareTo(BigDecimal.ZERO) <= 0, "退款金额不能为0");
        ServiceUtil.assertion(dto.getAmount().compareTo(orderVO.getPayFee()) > 0, "退款金额不能超过订单金额");
        ServiceUtil.assertion(!PayBillStatus.PAY_SUCCESS.getStatus().equals(payBillVO.getStatus()), "支付单状态非"+PayBillStatus.PAY_SUCCESS.getMsg()+",不允许退款");

        RefundBO bo = new RefundBO();
        bo.setOrder(orderVO);
        bo.setDto(dto);
        bo.setPayBill(payBillVO);

        return bo;
    }
}
