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

import cn.iocoder.yudao.module.energy.dal.dataobject.config.EnergyStationConfigDO;
import cn.iocoder.yudao.module.energy.dal.mysql.config.EnergyStationConfigMapper;
import cn.iocoder.yudao.module.energy.enums.DeductionStatusEnum;
import cn.iocoder.yudao.module.energy.event.DetailAuditedEvent;
import cn.iocoder.yudao.module.energy.event.DetailCreatedEvent;
import cn.iocoder.yudao.module.energy.service.account.EnergyAccountService;
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.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

@Component
@Slf4j
public class AccountEventListener {

    @Resource
    private EnergyAccountService accountService;
    @Resource
    private EnergyStationConfigMapper stationConfigMapper;
    @Resource
    private HydrogenDetailService detailService;

    /**
     * 明细创建完成 → 若配置自动扣款则扣款
     * BEFORE_COMMIT: 资金操作，必须同事务
     */
    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT)
    public void onDetailCreated(DetailCreatedEvent event) {
        EnergyStationConfigDO config = stationConfigMapper.selectByStationId(event.getStationId());
        if (config != null && Boolean.TRUE.equals(config.getAutoDeduct())) {
            log.info("[onDetailCreated] auto deduct: detailId={}, amount={}", event.getDetailId(), event.getCustomerAmount());
            accountService.deduct(event.getCustomerId(), event.getContractId(),
                    event.getCustomerAmount(), event.getDetailId(), null, "加氢自动扣款");
            detailService.updateDeductionStatus(event.getDetailId(), DeductionStatusEnum.DEDUCTED.getStatus());
        }
    }

    /**
     * 明细审核通过 → 若配置审核后扣款则扣款
     * BEFORE_COMMIT: 资金操作，必须同事务
     */
    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT)
    public void onDetailAudited(DetailAuditedEvent event) {
        EnergyStationConfigDO config = stationConfigMapper.selectByStationId(event.getStationId());
        if (config != null && !Boolean.TRUE.equals(config.getAutoDeduct())) {
            log.info("[onDetailAudited] audit-then-deduct: detailId={}, amount={}", event.getDetailId(), event.getCustomerAmount());
            accountService.deduct(event.getCustomerId(), event.getContractId(),
                    event.getCustomerAmount(), event.getDetailId(), null, "审核后扣款");
            detailService.updateDeductionStatus(event.getDetailId(), DeductionStatusEnum.DEDUCTED.getStatus());
        }
    }
}
