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

import com.bcxin.tenant.open.document.domains.documents.*;
import com.bcxin.tenant.open.document.domains.repositories.RdCompanyDocumentRepository;
import com.bcxin.tenant.open.document.domains.utils.GeoPointUtils;
import com.bcxin.tenant.open.domains.entities.RdCompanyEntity;
import com.bcxin.tenant.open.domains.readers.RdCompositedReader;
import com.bcxin.tenant.open.infrastructures.enums.ResourceType;
import com.bcxin.tenant.open.infrastructures.exceptions.DocumentIndexNoFoundException;
import com.bcxin.tenant.open.infrastructures.utils.BusinessUtil;
import com.bcxin.tenant.open.infrastructures.utils.ExceptionUtil;
import com.bcxin.tenant.open.infrastructures.valueTypes.GeoLocationValueType;
import com.redis.om.spring.search.stream.EntityStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

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

public class RdCompanyEntityUtils {
    private final static Logger logger = LoggerFactory.getLogger(RdCompanyEntityUtils.class);

    public static RdCompanyDocument toDocument(RdCompanyEntity ii,
                                               RdCompanyDocumentRepository companyDocumentRepository,
                                               RdCompositedReader compositedReader,
                                               EntityStream entityStream) {
       try{
           RdCompanyDocument document = null;
           Optional<RdCompanyDocument> companyDocumentOptional =
                   companyDocumentRepository.findById(ii.getId());
           if (companyDocumentOptional.isPresent()) {
               document = companyDocumentOptional.get();
           } else {
               /**
                * 新增的时候才刷新总数量, 其他从StationPerson以及SecurityStation来触发
                */
               document = new RdCompanyDocument();


               document.setId(ii.getId());
               document.setOrganizationId(ii.getOrganizationId());
           }

           document.rest();
           if (BusinessUtil.checkIfDynamicCountOfStationsAndMen(ii.getInstitutional())) {
               document.setCountOfActivityStation(0L);
               document.setCountOfSecurityMan(0L);

               String[] securityStationIds =
                       entityStream.of(RdDispatchDataScopeDocument.class)
                               .filter(RdDispatchDataScopeDocument$.SCOPES.in(ii.getId()))
                               .map(RdDispatchDataScopeDocument::getId)
                               .collect(Collectors.toSet()).toArray(ix -> new String[ix]);
               if (securityStationIds != null && securityStationIds.length > 0) {
                   Collection<Integer> countOfSecurityMens =
                           entityStream.of(RdSecurityStationDocument.class)
                                   .filter(RdSecurityStationDocument$.ID.in(securityStationIds))
                                   .map(RdSecurityStationDocument$.COUNT_OF_SECURITY_MAN)
                                   .collect(Collectors.toList());
                   if (!CollectionUtils.isEmpty(countOfSecurityMens)) {
                       document.setCountOfActivityStation((long) countOfSecurityMens.size());
                       document.setCountOfSecurityMan((long) countOfSecurityMens.stream().mapToInt(ix -> ix).sum());
                   }
               }
           } else {
               document.setCountOfActivityStation((long) ii.getCountOfActivityStation());
               document.setCountOfSecurityMan((long) ii.getCountOfSecurityMan());
           }

           document.setStatus(ii.getStatus());
           document.setSuperviseRegionCode(ii.getSuperviseRegionCode());
           document.setName(ii.getName());
           document.setPoints(ii.getPoints());

           document.setCountOfDesk(ii.getCountOfDesk());

           document.setInstitutional(ii.getInstitutional());
           document.setLegal(ii.getLegal());
           document.setLegalTelephone(ii.getLegalTelephone());
           document.setOrganizationId(ii.getOrganizationId());

           document.setRegisterAddress(ii.getRegisterAddress());
           document.setBusinessAddress(ii.getBusinessAddress());

           document.setLastUpdatedTime(ii.getLastUpdatedTime());
           document.setServiceScope(ii.getServiceScope());
           document.addResourceTypes(ResourceType.create(ii.getInstitutional()));

           document.setLonLat(GeoPointUtils.translate(ii.getLonLat()));

           if (document.getLonLat() != null && GeoLocationValueType.isValidLocation(document.getLonLat().getY(), document.getLonLat().getX())) {
               document.setHasLonLatFlag(1);
           } else {
               document.setHasLonLatFlag(0);
           }

           document.setSuperviseDepartId(ii.getSuperviseDepartId());
           document.addScopePermissions(ii.getSuperviseDepartId());
           document.addScopePermissions(ii.getId());

           document.setSuperviseDepartName(ii.getSuperviseDepartName());

           document.setLastUpdatedTime(ii.getLastSyncTime());
           document.setIndustry(ii.getIndustry());
           document.setCountOfMan((long) ii.getCountOfMen());

           document.updateWord(document.getName());

           long countOfProject = 0;
           try {
               String[] organizationIds = new String[]{document.getOrganizationId()};
               countOfProject = entityStream.of(RdProjectDocument.class)
                       .filter(RdProjectDocument$.SCOPE_PERMISSIONS.in(organizationIds))
                       .count();
               document.updateCountOfProject(countOfProject);
           } catch (Exception ex) {
               logger.error("临保项目统计发生异常:{};name={};", document.getId(), document.getName(), ex);
           }

           return document;
       }
       catch (Exception ex) {
           if (ExceptionUtil.getStackMessage(ex).contains("no such index")) {
               throw new DocumentIndexNoFoundException("索引异常", ex);
           }
           throw ex;
       }
    }
}
