package net.zstong.awump.base.service;


import net.zstong.awump.base.entity.AwInstitutionEntity;
import net.zstong.awump.base.entity.AwRegionEntity;
import org.hswebframework.ezorm.rdb.mapping.ReactiveRepository;
import org.hswebframework.web.api.crud.entity.QueryParamEntity;
import org.hswebframework.web.api.crud.entity.TreeSupportEntity;
import org.hswebframework.web.crud.service.GenericReactiveTreeSupportCrudService;
import org.hswebframework.web.id.IDGenerator;
import org.jetlinks.community.config.entity.ConfigEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;


@Service
public class AwRegionService extends GenericReactiveTreeSupportCrudService<AwRegionEntity, String> {

    @Autowired
    private ReactiveRepository<AwInstitutionEntity, String> institutionRepository;

    @Override
    public IDGenerator<String> getIDGenerator() {
        return IDGenerator.MD5;
    }

    @Override
    public void setChildren(AwRegionEntity entity, List<AwRegionEntity> children) {
        entity.setChildren(children);
    }


    public Flux<AwRegionEntity> getAllCategoryTreeByQueryParam(Mono<QueryParamEntity> query) {
        return this
            .query(query)
            .flatMap(r -> {
                return institutionRepository.createQuery().where(AwInstitutionEntity::getRegionId, r.getId()).count().map(count -> {
                    r.setCountInstitution(count);
                    return r;
                });
            })
            .collectList()
            .flatMapMany(all -> {
                List<AwRegionEntity> t = TreeSupportEntity.list2tree(all, AwRegionEntity::setChildren);
                countInstitutionNum(t);
                return Flux.fromIterable(t);
            });
    }

    private int countInstitutionNum(List<AwRegionEntity> t) {
        int count = 0;
        for (AwRegionEntity e : t) {
            if (e.getChildren() != null && e.getChildren().size() > 0) {
                e.setCountInstitution(e.getCountInstitution() + countInstitutionNum(e.getChildren()));
            }
            count = count + e.getCountInstitution();
        }
        return count;
    }
}
