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

import cn.iocoder.yudao.module.energy.enums.SettlementStatusEnum;
import cn.iocoder.yudao.module.energy.event.BillApprovedEvent;
import cn.iocoder.yudao.module.energy.event.BillCreatedEvent;
import cn.iocoder.yudao.module.energy.service.detail.HydrogenDetailService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;

@Component
@Slf4j
public class BillEventListener {

    @Resource
    private HydrogenDetailService detailService;

    /**
     * 账单生成完成 → 更新明细的 billId
     * AFTER_COMMIT: 非资金操作
     */
    @TransactionalEventListener
    public void onBillCreated(BillCreatedEvent event) {
        log.info("[onBillCreated] billId={}, detailCount={}", event.getBillId(), event.getDetailIds().size());
        detailService.updateBillId(event.getDetailIds(), event.getBillId());
    }

    /**
     * 账单审核通过 → 更新明细结算状态
     * AFTER_COMMIT: 非资金操作
     */
    @TransactionalEventListener
    public void onBillApproved(BillApprovedEvent event) {
        log.info("[onBillApproved] billId={}", event.getBillId());
        detailService.updateSettlementStatus(event.getDetailIds(), SettlementStatusEnum.SETTLED.getStatus());
    }
}
