package com.bcxin.tenant.domain.services.impls;

import com.bcxin.Infrastructures.UnitWork;
import com.bcxin.tenant.domain.entities.OrganizationStatisticsReportEntity;
import com.bcxin.tenant.domain.repositories.OrganizationStatisticsReportsRepository;
import com.bcxin.tenant.domain.services.OrganizationStatisticsService;
import io.jsonwebtoken.lang.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrganizationStatisticsServiceImpl implements OrganizationStatisticsService {
    private final Logger logger = LoggerFactory.getLogger(OrganizationStatisticsServiceImpl.class);
    private final OrganizationStatisticsReportsRepository organizationStatisticsReportsRepository;
    private final UnitWork unitWork;

    public OrganizationStatisticsServiceImpl(OrganizationStatisticsReportsRepository organizationStatisticsReportsRepository, UnitWork unitWork) {
        this.organizationStatisticsReportsRepository = organizationStatisticsReportsRepository;
        this.unitWork = unitWork;
    }

    @Override
    public void createStatisticsById(Collection<String> orgIds) {
        if(Collections.isEmpty(orgIds)){
            logger.error("组织id不能为空");
            return;
        }
        String transId = unitWork.beginTransaction();
        try{
//            List<OrganizationStatisticsReportEntity> existEntities =
//                    organizationStatisticsReportsRepository.findAllById(orgIds);
//            if(!Collections.isEmpty(existEntities)){
//                Set<String> existOrgIds =
//                        existEntities.stream().map(ix->ix.getId()).collect(Collectors.toSet());
//                orgIds = orgIds.stream().filter(ix->!existOrgIds.contains(ix))
//                        .collect(Collectors.toList());
//            }
            //如果统计表中没有则插入，如果已经存在，则更新
            if(!Collections.isEmpty(orgIds)){
                List<OrganizationStatisticsReportEntity> createOrUpdateEntities =
                        organizationStatisticsReportsRepository.getOrganizationStatisticsInfo(orgIds)
                                .stream().map(
                                        ix-> OrganizationStatisticsReportEntity.create(
                                                ix.getOrgId(),
                                                ix.getUnifySocialCreditCode(),
                                                ix.getCountOfMembers()
                                        )).collect(Collectors.toList());
                organizationStatisticsReportsRepository.saveAll(createOrUpdateEntities);
            }
            unitWork.commit(transId);
        }catch (Exception e){
            unitWork.rollback(transId);
            logger.error(String.format("添加组织统计记录出现异常：%s",e.getMessage()));
        }
    }

    @Override
    public void syncOrganizationStatistics() {
        String transId = unitWork.beginTransaction();
        try{
            List<OrganizationStatisticsReportEntity> orgEntities = organizationStatisticsReportsRepository.findAll();
            if(!Collections.isEmpty(orgEntities)){
                List<String> orgIds = orgEntities.stream().map(ix->ix.getId()).collect(Collectors.toList());
                List<OrganizationStatisticsReportEntity> updateEntities =
                        organizationStatisticsReportsRepository.getOrganizationStatisticsInfo(orgIds)
                                .stream().map(
                                        ix-> OrganizationStatisticsReportEntity.create(
                                                ix.getOrgId(),
                                                ix.getUnifySocialCreditCode(),
                                                ix.getCountOfMembers()
                                        )).collect(Collectors.toList());
                organizationStatisticsReportsRepository.saveAll(updateEntities);
            }
            unitWork.commit(transId);
        }catch (Exception e){
            unitWork.rollback(transId);
            logger.error(String.format("更新组织统计记录出现异常：%s",e.getMessage()));
        }
    }
}
