package com.bcxin.tenant.open.domains.eventListeners;

import com.bcxin.tenant.open.domains.dtos.RoomCommunicatedGroupDTO;
import com.bcxin.tenant.open.domains.entities.OrgPurseTransactionEntity;
import com.bcxin.tenant.open.domains.events.PreparedRoomCommunicatedGroupEvent;
import com.bcxin.tenant.open.domains.repositories.ConfigOfBillRepository;
import com.bcxin.tenant.open.domains.services.OrgPurseTransactionService;
import com.bcxin.tenant.open.domains.services.commands.CreateOrgPurseTransactionCommand;
import com.bcxin.tenant.open.domains.utils.OrgPurseTransactionUtil;
import com.bcxin.tenant.open.infrastructures.components.IdWorker;
import com.bcxin.tenant.open.infrastructures.components.JsonProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import java.util.Collection;

@Component
public class PreparedRoomCommunicatedGroupListener_OrgPurseTransaction implements ApplicationListener<PreparedRoomCommunicatedGroupEvent> {
    private final Logger logger = LoggerFactory.getLogger(PreparedRoomCommunicatedGroupListener_OrgPurseTransaction.class);
    private final OrgPurseTransactionService orgPurseTransactionService;
    private final IdWorker idWorker;
    private final JsonProvider jsonProvider;
    private final ConfigOfBillRepository configOfBillRepository;
    public PreparedRoomCommunicatedGroupListener_OrgPurseTransaction(OrgPurseTransactionService orgPurseTransactionService,
                                                                     IdWorker idWorker, JsonProvider jsonProvider,
                                                                     ConfigOfBillRepository configOfBillRepository) {
        this.orgPurseTransactionService = orgPurseTransactionService;
        this.idWorker = idWorker;
        this.jsonProvider = jsonProvider;
        this.configOfBillRepository = configOfBillRepository;
    }

    @Override
    public void onApplicationEvent(PreparedRoomCommunicatedGroupEvent event) {
        Collection<RoomCommunicatedGroupDTO> roomCommunicatedGroups = event.getRoomCommunicatedGroups();
        /**
         * 基于构建好的房间的信息，构建好的transactions
         */
        Collection<OrgPurseTransactionEntity> orgPurseTransactions
                = OrgPurseTransactionUtil.build(
                this.idWorker,
                roomCommunicatedGroups, jsonProvider,
                configOfBillRepository.get()
        );

        logger.info("基于构建好的房间的信息，构建好的transactions={}", orgPurseTransactions.size());

        CreateOrgPurseTransactionCommand command =
                CreateOrgPurseTransactionCommand.create(orgPurseTransactions);
        this.orgPurseTransactionService.dispatch(command);
    }
}
