package com.bcxin.backend.domain.syncs.services.impls;

import com.bcxin.backend.domain.syncs.events.SyncDataApplicationEvent;
import com.bcxin.backend.domain.syncs.repositories.DataSyncQueueRepository;
import com.bcxin.backend.domain.syncs.services.RetryDataService;
import com.bcxin.runtime.domain.syncs.entities.DataSyncQueueEntity;
import com.bcxin.runtime.domain.syncs.enums.SyncProcessStatus;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class RetryDataServiceImpl implements RetryDataService {
    private final DataSyncQueueRepository dataSyncQueueRepository;
    private final ApplicationEventPublisher applicationEventPublisher;

    public RetryDataServiceImpl(DataSyncQueueRepository dataSyncQueueRepository,
                                ApplicationEventPublisher applicationEventPublisher) {
        this.dataSyncQueueRepository = dataSyncQueueRepository;
        this.applicationEventPublisher = applicationEventPublisher;
    }

    @Override
    public void retrySync() {
        try {
            Page<DataSyncQueueEntity> dataSyncQueueEntities = this.dataSyncQueueRepository
                    .getRetryableQueueData(Pageable.ofSize(100));
            dataSyncQueueEntities.forEach(ii -> {
                ii.retry(String.format("执行同步数据的重试操作:%s", new Date()));
            });

            this.dataSyncQueueRepository.saveAll(dataSyncQueueEntities);


            dataSyncQueueEntities = this.dataSyncQueueRepository
                    .getRetryableQueueFile(Pageable.ofSize(100));
            dataSyncQueueEntities.forEach(ii -> {
                ii.changeFileSyncStatusAndRetryCount(ii.getStatus() == SyncProcessStatus.Error ? SyncProcessStatus.Initialize : SyncProcessStatus.SyncViaFTP,
                        ii.getFileSyncResult());
            });

            this.dataSyncQueueRepository.saveAll(dataSyncQueueEntities);
        } finally {
            this.applicationEventPublisher.publishEvent(SyncDataApplicationEvent.create("重试同步数据"));
        }
    }
}
