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

import cn.iocoder.yudao.module.asset.dal.dataobject.station.HydrogenStationDO;
import cn.iocoder.yudao.module.asset.service.station.HydrogenStationService;
import cn.iocoder.yudao.module.energy.dal.dataobject.detail.EnergyHydrogenDetailDO;
import cn.iocoder.yudao.module.energy.dal.dataobject.price.EnergyStationPriceDO;
import cn.iocoder.yudao.module.energy.dal.dataobject.record.EnergyHydrogenRecordDO;
import cn.iocoder.yudao.module.energy.dal.mysql.detail.EnergyHydrogenDetailMapper;
import cn.iocoder.yudao.module.energy.dal.mysql.record.EnergyHydrogenRecordMapper;
import cn.iocoder.yudao.module.energy.enums.DeductionStatusEnum;
import cn.iocoder.yudao.module.energy.event.RecordImportedEvent;
import cn.iocoder.yudao.module.energy.service.account.EnergyAccountService;
import cn.iocoder.yudao.module.energy.service.detail.HydrogenDetailService;
import cn.iocoder.yudao.module.energy.service.match.HydrogenMatchService;
import cn.iocoder.yudao.module.energy.service.match.dto.MatchResultDTO;
import cn.iocoder.yudao.module.energy.service.price.EnergyStationPriceService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.event.TransactionalEventListener;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class DetailEventListener {

    @Resource
    private HydrogenDetailService hydrogenDetailService;

    @Resource
    private HydrogenMatchService hydrogenMatchService;

    @Resource
    private EnergyHydrogenRecordMapper hydrogenRecordMapper;

    @Resource
    private EnergyHydrogenDetailMapper hydrogenDetailMapper;

    @Resource
    private HydrogenStationService hydrogenStationService;

    @Resource
    private EnergyStationPriceService stationPriceService;

    @Resource
    private EnergyAccountService accountService;

    /**
     * 记录导入完成 → 触发自动匹配+生成明细
     * AFTER_COMMIT: 非资金操作
     */
    @TransactionalEventListener
    @Transactional(rollbackFor = Exception.class)
    public void onRecordImported(RecordImportedEvent event) {
        log.info("[onRecordImported] 开始处理导入记录，stationId={}, recordCount={}, batchNo={}",
                event.getStationId(), event.getRecordIds().size(), event.getBatchNo());

        // 1. 批量匹配
        MatchResultDTO matchResult = hydrogenMatchService.batchMatch(event.getRecordIds());
        log.info("[onRecordImported] 匹配完成，成功={}, 失败={}",
                matchResult.getSuccessCount(), matchResult.getFailCount());

        // 2. 批量生成明细（只为匹配成功的记录生成）
        if (matchResult.getSuccessCount() > 0) {
            List<EnergyHydrogenRecordDO> matchedRecords = hydrogenRecordMapper.selectBatchIds(matchResult.getSuccessIds());
            List<EnergyHydrogenDetailDO> details = new ArrayList<>();

            for (EnergyHydrogenRecordDO record : matchedRecords) {
                EnergyHydrogenDetailDO detail = createDetailFromRecord(record, event.getStationId());
                if (detail != null) {
                    details.add(detail);
                }
            }

            if (!details.isEmpty()) {
                // 批量插入明细
                for (EnergyHydrogenDetailDO detail : details) {
                    hydrogenDetailMapper.insert(detail);
                }
                log.info("[onRecordImported] 生成明细完成，count={}", details.size());

                // 3. 检查站点配置，决定是否自动扣款
                HydrogenStationDO station = hydrogenStationService.getHydrogenStation(event.getStationId());
                if (station != null && Boolean.TRUE.equals(station.getAutoDeduct())) {
                    log.info("[onRecordImported] 站点配置自动扣款，开始扣款流程");
                    for (EnergyHydrogenDetailDO detail : details) {
                        try {
                            accountService.deduct(
                                    detail.getCustomerId(),
                                    detail.getContractId(),
                                    detail.getCustomerAmount(),
                                    detail.getId(),
                                    null,
                                    "加氢自动扣款"
                            );
                            hydrogenDetailService.updateDeductionStatus(
                                    detail.getId(),
                                    DeductionStatusEnum.DEDUCTED.getStatus()
                            );
                            log.info("[onRecordImported] 扣款成功，detailId={}, amount={}",
                                    detail.getId(), detail.getCustomerAmount());
                        } catch (Exception e) {
                            log.error("[onRecordImported] 扣款失败，detailId={}, error={}",
                                    detail.getId(), e.getMessage(), e);
                        }
                    }
                }
            }
        }

        log.info("[onRecordImported] 处理完成");
    }

    /**
     * 从记录创建明细
     */
    private EnergyHydrogenDetailDO createDetailFromRecord(EnergyHydrogenRecordDO record, Long stationId) {
        // 获取价格配置（使用客户ID和日期）
        EnergyStationPriceDO price = stationPriceService.getEffectivePrice(
                stationId, 
                record.getCustomerId(), 
                record.getHydrogenDate()
        );
        if (price == null) {
            log.warn("[createDetailFromRecord] 未找到有效价格配置，recordId={}, stationId={}, customerId={}, date={}",
                    record.getId(), stationId, record.getCustomerId(), record.getHydrogenDate());
            return null;
        }

        // 重新匹配获取合同ID（因为批量匹配时已经更新了record，但需要获取contractId）
        MatchResultVO matchResult = hydrogenMatchService.matchRecord(record);
        
        // 计算金额
        BigDecimal costAmount = record.getHydrogenQuantity()
                .multiply(price.getCostPrice())
                .setScale(2, RoundingMode.HALF_UP);
        BigDecimal customerAmount = record.getHydrogenQuantity()
                .multiply(price.getCustomerPrice())
                .setScale(2, RoundingMode.HALF_UP);

        return EnergyHydrogenDetailDO.builder()
                .recordId(record.getId())
                .stationId(stationId)
                .vehicleId(record.getVehicleId())
                .plateNumber(record.getPlateNumber())
                .hydrogenDate(record.getHydrogenDate())
                .hydrogenQuantity(record.getHydrogenQuantity())
                .costPrice(price.getCostPrice())
                .costAmount(costAmount)
                .customerPrice(price.getCustomerPrice())
                .customerAmount(customerAmount)
                .contractId(matchResult.getContractId()) // 从匹配结果获取合同ID
                .customerId(record.getCustomerId())
                .projectName(null) // 可以从合同获取，暂时为空
                .costBearer(1) // 默认客户承担，可以从合同配置获取
                .payMethod(1) // 默认预付，可以从合同配置获取
                .auditStatus(0) // 待审核
                .deductionStatus(0) // 未扣款
                .settlementStatus(0) // 未结算
                .build();
    }
}
