package com.yami.shop.user.comment.listener;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.enums.OrderType;
import com.yami.shop.bean.enums.ScoreLogType;
import com.yami.shop.bean.event.CancelOrderEvent;
import com.yami.shop.bean.model.UserExtension;
import com.yami.shop.bean.order.CancelOrderOrder;
import com.yami.shop.service.UserExtensionService;
import com.yami.shop.user.comment.model.UserScoreLog;
import com.yami.shop.user.comment.service.UserScoreDetailService;
import com.yami.shop.user.comment.service.UserScoreLogService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;


/**
 * 取消订单事件监听
 */
@Slf4j
@Component("userCancelOrderListener")
@AllArgsConstructor
public class CancelOrderListener {

    final private UserScoreLogService userScoreLogService;
    final private UserScoreDetailService userScoreDetailService;


    /**
     * 取消订单积分抵现花费的积分回退
     */
    @EventListener(CancelOrderEvent.class)
    @Order(CancelOrderOrder.SCORE)
    public void userCancelOrderListener(CancelOrderEvent event) {
        com.yami.shop.bean.model.Order order = event.getOrder();
//        //如果是积分订单无需
//        // 进行此操作
//        if(Objects.equals(order.getOrderType() , OrderType.SCORE.value())){
//            return;
//        }
        UserScoreLog userScoreLog = userScoreLogService.getOne(new LambdaQueryWrapper<UserScoreLog>()
                                                        .eq(UserScoreLog::getBizId, order.getOrderId())
                                                        .eq(UserScoreLog::getUserId,order.getUserId())
                                                        .eq(UserScoreLog::getIoType,0)
                                                        .eq(UserScoreLog::getSource,ScoreLogType.SCORE_CASH.value()));
        //判断此笔订单是否有记录，有进行回退用户积分,并添加日志
        if(userScoreLog != null){
            userScoreDetailService.updateLogAndDetail(order.getOrderId(),order.getUserId());
        }
    }

}
