package cn.iocoder.yudao.module.asset.service.event;

import cn.iocoder.yudao.module.asset.enums.replacement.ReplacementTypeEnum;
import cn.iocoder.yudao.module.asset.service.replacement.event.ReplacementApprovedEvent;
import cn.iocoder.yudao.module.asset.service.returnorder.ReturnOrderService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * 还车单事件监听器
 * 监听替换车审批通过事件，自动创建还车单
 *
 * @author 芋道源码
 */
@Component
@Slf4j
public class ReturnOrderEventListener {

    @Resource
    private ReturnOrderService returnOrderService;

    /**
     * 永久替换审批通过时，自动创建还车单
     * 使用 @EventListener 而非 @TransactionalEventListener，确保在同一事务中执行
     */
    @EventListener
    public void onReplacementApproved(ReplacementApprovedEvent event) {
        if (event.getReplacementType().equals(ReplacementTypeEnum.PERMANENT.getType())) {
            log.info("[onReplacementApproved] permanent replacement, creating return order: replacementId={}",
                    event.getReplacementId());
            returnOrderService.createFromReplacement(
                    event.getReplacementId(),
                    event.getContractId(),
                    event.getOriginalVehicleId()
            );
        }
    }

}
