package com.zanxiang.game.module.sdk.listener;

import com.zanxiang.game.module.base.pojo.enums.PayDeviceEnum;
import com.zanxiang.game.module.sdk.enums.KafkaEventTrackEnum;
import com.zanxiang.game.module.sdk.pojo.dto.PlatformOrderDTO;
import com.zanxiang.game.module.sdk.service.*;
import com.zanxiang.module.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

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

/**
 * 订单支付完成事件监听
 *
 * @author xufeng
 * @date 2022/6/27 10:22
 */
@Configuration
@Component
@Slf4j
public class OrderPaySuccessListener {

    @Autowired
    private IKafkaService kafkaService;

    @Resource
    private IOrderService orderService;

    @Autowired
    private IPushMsgService pushMsgService;

    @Resource
    private IPerformOrderService performOrderService;

    @Autowired
    private ICallBackService callBackService;

    @Async
    @EventListener
    public void onApplicationEvent(OrderPaySuccessEvent event) {
        if (Strings.isBlank(event.getOrderId())) {
            log.error("缺少订单ID");
            return;
        }
        log.info("订单:{} 支付成功履约监听逻辑 ------start---------", event.getOrderId());
        PlatformOrderDTO platformOrderDTO = orderService.getByOrderId(event.getOrderId());
        if (Objects.isNull(platformOrderDTO)) {
            log.error("订单:{} 获取详情失败", event.getOrderId());
            return;
        }
        //cp推送
        try {
            performOrderService.pushCp(platformOrderDTO);
        } catch (Exception e) {
            log.error("充值回调CP异常, orderId : {}, e : {}", platformOrderDTO.getOrderId(), e.getMessage());
        }
        //订单回传
        callBackService.orderCallBack(platformOrderDTO);
        //用户充值统计更新
        performOrderService.userRechargeTotal(platformOrderDTO);
        //用户首冲统计
        performOrderService.checkIsFirstRecharge(platformOrderDTO);
        //判断用户是否使用米大师支付
        if (Objects.equals(platformOrderDTO.getPayDeviceId(), PayDeviceEnum.MI_PAY.getPayDeviceId())) {
            //米大师收款统计
            performOrderService.miPayTotal(platformOrderDTO);
        } else {
            //商户号额度统计更新
            performOrderService.payMerchantTotal(platformOrderDTO);
        }
        //订单支付埋点数据发送到卡夫卡
        kafkaService.eventTrack(KafkaEventTrackEnum.KAFKA_EVENT_TRACK_ORDER_PAY, JsonUtil.toString(platformOrderDTO));
        //订单充值消息推送
        pushMsgService.pushMsgByRecharge(platformOrderDTO);
        log.info("订单:{} 支付成功履约监听逻辑 ------end---------", event.getOrderId());
    }
}
