package com.seer.teach.mall.app.order.handler;

import com.seer.teach.common.enums.OrderStatusEnum;
import com.seer.teach.common.enums.ShippingStatusEnum;
import com.seer.teach.common.enums.pay.PayChannelEnum;
import com.seer.teach.common.enums.pay.RefundTypeEnum;
import com.seer.teach.common.utils.MoneyUtil;
import com.seer.teach.common.utils.OrderIdGenerator;
import com.seer.teach.mall.entity.OrderChildEntity;
import com.seer.teach.mall.entity.OrderEntity;
import com.seer.teach.mall.entity.OrderGoodsEntity;
import com.seer.teach.mall.handler.OrderHandler;
import com.seer.teach.pay.api.refund.RefundOrderServiceApi;
import com.seer.teach.pay.api.refund.dto.RefundOrderRequestDTO;
import com.seer.teach.pay.api.refund.dto.RefundResponseDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 订单取消退款处理器
 * 当用户在支付成功但未发货前取消订单时，自动发起原路退款
 */
@RequiredArgsConstructor
@Slf4j
@Service
public class RefundOrderHandler implements OrderHandler {


    private final RefundOrderServiceApi refundOrderServiceApi;

    @Override
    public void afterOrderCancel(OrderEntity order, List<OrderGoodsEntity> orderItems) {

    }
    
    /**
     * 生成退款单号（订单取消退款）
     * @return 退款单号
     */
    private String generateRefundSn() {
        return OrderIdGenerator.generateOrderId(OrderIdGenerator.MALL_ORDER_PREFIX);
    }

    @Override
    public void afterOrderCancel(OrderEntity order,OrderChildEntity childOrder, List<OrderGoodsEntity> orderItems) {
        // 检查是否满足退款条件：订单已支付且未发货
        if (childOrder.getOrderStatus().equals(OrderStatusEnum.PAID.getCode()) && 
            ShippingStatusEnum.NOT_SHIPPED.getCode() == childOrder.getShippingStatus()) {
            
            Integer payOrderId = order.getPayOrderId();
            if (payOrderId == null) {
                log.warn("订单 {} 没有关联的支付订单，无法退款", order.getOrderSn());
                return;
            }
            
            // 构造退款请求
            Long refundAmount = null;
            Long totalAmount = null;
            if (PayChannelEnum.COIN.getCode().equalsIgnoreCase(childOrder.getPayChannelCode())) {
                refundAmount = childOrder.getOrderTotalCoin().longValue();
                totalAmount = order.getOrderTotalCoin().longValue();
            } else {
                refundAmount = childOrder.getActualPrice().longValue();
                totalAmount = order.getActualPrice().longValue();
            }
            
            String refundSn = generateRefundSn();
            RefundOrderRequestDTO refundRequest = RefundOrderRequestDTO.builder()
                    .merchantRefundSn(refundSn)
                    .refundReason("用户取消订单")
                    .merchantOrderSn(order.getOrderSn())
                    .channelCode(childOrder.getPayChannelCode())
                    .refundAmount(refundAmount)
                    .totalAmount(totalAmount)
                    .refundType(RefundTypeEnum.ORDER_CANCEL)
                    .userId(order.getUserId())
                    .build();
            
            try {
                log.info("开始处理订单 {} 的退款请求，退款金额: {}", order.getOrderSn(), refundAmount);
                // 调用支付模块的退款接口
                RefundResponseDTO refundResponseDTO = refundOrderServiceApi.submitRefund(refundRequest);
                
                if ("SUCCESS".equals(refundResponseDTO.getStatus())) {
                    log.info("订单 {} 退款成功，退款单号: {}", order.getOrderSn(), refundResponseDTO.getRefundNo());
                    // 退款成功后的处理可以在这里添加
                } else {
                    log.warn("订单 {} 退款处理中或失败，当前状态: {}，退款单号: {}", 
                        order.getOrderSn(), refundResponseDTO.getStatus(), refundResponseDTO.getRefundNo());
                    // 退款处理中或失败的处理可以在这里添加
                }
            } catch (Exception e) {
                log.error("订单 {} 退款申请失败", order.getOrderSn(), e);
                // 退款申请异常处理
            }
        } else {
            log.info("订单 {} 不满足退款条件，订单状态: {}，发货状态: {}", 
                order.getOrderSn(), childOrder.getOrderStatus(), childOrder.getShippingStatus());
        }
    }
}