package com.izouma.nineth.service;

import com.alibaba.fastjson.JSONObject;
import com.izouma.nineth.domain.ErrorOrder;
import com.izouma.nineth.event.GiftOrderNotifyEvent;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.ErrorOrderRepo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

@Service
@AllArgsConstructor
@Slf4j
public class GiftOrderNotifyService {

    private GiftOrderService giftOrderService;

    private ErrorOrderRepo errorOrderRepo;

    @EventListener
    public void listenNotify(GiftOrderNotifyEvent event){
        log.info("收到转赠回调消息 {} ", JSONObject.toJSONString(event));
        try {
            giftOrderService.giftNotify(event.getGiftOrderId(), event.getPayMethod(), event.getTransactionId());
        }catch (Exception err){
            ErrorOrder errorOrder  = ErrorOrder.builder()
                    .orderId(event.getGiftOrderId())
                    .transactionId(event.getTransactionId())
                    .payMethod(event.getPayMethod())
                    .type("gift")
                    .build();
            if (err instanceof BusinessException) {
                log.error("订单回调出错 giftOrderId: {} , 错误信息：{}", event.getGiftOrderId(), err.getMessage());
            } else {
                log.error("订单回调出错 giftOrderId: " +  event.getGiftOrderId(), err);
            }
            errorOrder.setErrorMessage(err.getMessage());
            errorOrderRepo.save(errorOrder);
        }
    }

}
