package cn.iocoder.yudao.module.order.listener;


import cn.iocoder.yudao.framework.apollo.core.event.OrderNumberLogEvent;
import cn.iocoder.yudao.module.order.dal.dataobject.orderNumberLog.OrderNumberLogDO;
import cn.iocoder.yudao.module.order.service.orderNumberLog.OrderNumberLogService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Objects;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.order.enums.ErrorCodeConstants.ORDER_NUMBER_PARAM_NOT_NULL;

/**
 * 编号记录监听
 *
 * @author zhengYi
 */
@Component("OrderNumberLongListener")
@AllArgsConstructor
public class OrderNumberLogListener {

    private final OrderNumberLogService orderNumberLogService;
    /**
     * 有最新编号记录则执行修改或插入操作，无最新编号记录执行查询最新编号记录操作
     *
     * @param event 编号记录
     */
    @EventListener(OrderNumberLogEvent.class)
    public void orderNumberLongEvent(OrderNumberLogEvent event) {
        if (Objects.isNull(event)){
            throw exception(ORDER_NUMBER_PARAM_NOT_NULL);
        }
        if (StringUtils.isBlank(event.getNewNumber())){
            // 查询
            OrderNumberLogDO orderNumberLogDO = orderNumberLogService.newNumberInfo(event.getNumberKey(), event.getType());
            if (Objects.nonNull(orderNumberLogDO)){
                BeanUtils.copyProperties(orderNumberLogDO, event);
            }
        }else {
            OrderNumberLogDO orderNumberLogDO = new OrderNumberLogDO();
            BeanUtils.copyProperties(event, orderNumberLogDO);
            // 更新
            orderNumberLogService.saveOrUpdateNewNumber(orderNumberLogDO, event.getNumberKey(), event.getType(), event.getNewNumber());
        }

    }
}
