package com.bcxin.tenant.open.domains.services.impls;

import com.bcxin.tenant.open.document.domains.documents.OrgPurseDocument;
import com.bcxin.tenant.open.document.domains.repositories.OrgPurseDocumentRepository;
import com.bcxin.tenant.open.domains.entities.OrgPurseEntity;
import com.bcxin.tenant.open.domains.repositories.OrgPurseRepository;
import com.bcxin.tenant.open.domains.services.OrgPurseService;
import com.bcxin.tenant.open.domains.services.commands.RefreshOrgPurseCacheCommand;
import com.bcxin.tenant.open.infrastructures.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.sql.Timestamp;
import java.time.Instant;
import java.util.Collection;
import java.util.Collections;
import java.util.stream.Collectors;

@Service

public class OrgPurseServiceImpl implements OrgPurseService {
    private static final Logger logger = LoggerFactory.getLogger(OrgPurseServiceImpl.class);

    private final OrgPurseRepository orgPurseRepository;
    private final OrgPurseDocumentRepository orgPurseDocumentRepository;

    public OrgPurseServiceImpl(OrgPurseRepository orgPurseRepository,
                               OrgPurseDocumentRepository orgPurseDocumentRepository) {
        this.orgPurseRepository = orgPurseRepository;
        this.orgPurseDocumentRepository = orgPurseDocumentRepository;
    }


    @Override
    public Collection<OrgPurseDocument> dispatch(RefreshOrgPurseCacheCommand command) {
        Collection<OrgPurseEntity> orgPurses
                = this.orgPurseRepository.getByOrganizationIds(command.getOrganizationIds());

        if (!CollectionUtils.isEmpty(orgPurses)) {
            Collection<OrgPurseDocument> translateDocuments =
                    orgPurses.stream().map(ii -> OrgPurseDocument.create(ii.getOrganizationId(),
                                    ii.getPoints(), ii.IsDispatchable(),command.isFromAutoDetect()))
                            .collect(Collectors.toList());
            try {
                if (!CollectionUtils.isEmpty(translateDocuments)) {
                    this.orgPurseDocumentRepository.saveAll(translateDocuments);
                } else {
                    translateDocuments =
                            command.getOrganizationIds().stream()
                                    .filter(ii -> StringUtil.isEmpty(ii))
                                    .distinct()
                                    .map(ii -> OrgPurseDocument.create(ii, 0l, false,command.isFromAutoDetect()))
                                    .collect(Collectors.toList());

                    this.orgPurseDocumentRepository.saveAll(translateDocuments);
                }
            } catch (Exception ex) {
                logger.error("验证企业联动值({})信息发生异常", command.getOrganizationIds());
            }

            return translateDocuments;
        }

        return Collections.EMPTY_LIST;
    }
}
