package com.kxs.product.biz.handlers;

import com.kxs.common.core.constant.CommonConstants;
import com.kxs.common.pay.enums.PayConstants;
import com.kxs.common.pay.enums.PayPlatformEnum;
import com.kxs.common.pay.handlers.PayMessageHandler;
import com.kxs.common.pay.model.AliPayMessage;
import com.kxs.common.pay.service.ali.AliPayService;
import com.kxs.product.biz.service.KxsShopOrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 支付宝支付回调处理器
 * @author mac
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class AliPayMessageHandler implements PayMessageHandler<AliPayMessage, AliPayService> {

    private final KxsShopOrderService orderService;

    /**
     * 处理支付回调消息的处理器接口
     *
     * @param payMessage 支付消息
     * @param payService 支付服务
     * @return xml, text格式的消息，如果在异步规则里处理的话，可以返回null
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public String handle(AliPayMessage payMessage, AliPayService payService) {

        log.info("支付宝支付回调消息处理，订单号：{}", payMessage.getOutTradeNo());

        //商城订单处理
        if (payMessage.getPassbackParams().equals(CommonConstants.SHOP_ORDER_FLAG)) {
            orderService.payBack(payMessage.getOutTradeNo());
        }
        return PayConstants.ALI_PAY_SUCCESS;
    }

    @Override
    public boolean support(PayPlatformEnum payPlatformEnum) {
        return PayPlatformEnum.ALIPAY.equals(payPlatformEnum);
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE + 1;
    }
}
