package net.zstong.awump.base.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.zstong.awump.base.entity.AwInstitutionEntity;
import net.zstong.awump.base.entity.AwRegionEntity;
import org.apache.commons.collections4.CollectionUtils;
import org.hswebframework.ezorm.rdb.mapping.ReactiveRepository;
import org.hswebframework.web.api.crud.entity.TreeSupportEntity;
import org.hswebframework.web.authorization.DefaultDimensionType;
import org.hswebframework.web.bean.FastBeanCopier;
import org.hswebframework.web.crud.service.GenericReactiveCrudService;
import org.hswebframework.web.exception.BusinessException;
import org.jetlinks.community.device.entity.DeviceInstanceEntity;
import org.jetlinks.community.device.entity.DeviceProductEntity;
import org.jetlinks.community.device.enums.DeviceProductState;
import org.jetlinks.community.device.events.DeviceProductDeployEvent;
import org.jetlinks.core.device.DeviceRegistry;
import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Nullable;
import javax.validation.constraints.NotNull;
import java.util.Collection;
import java.util.List;

@Service
@Slf4j
public class AwInstitutionService extends GenericReactiveCrudService<AwInstitutionEntity, String> {


    @Autowired
    private ReactiveRepository<AwRegionEntity, String> regionRepository;

    public Flux<AwRegionEntity> getAllRegionInstitutionTree() {
        return regionRepository.createQuery().fetch()
            .flatMap(r -> {
                r.setDisabled(true);
                return Flux.concat(Flux.just(r),
                    this.createQuery().where(AwInstitutionEntity::getRegionId, r.getId()).fetch().map(i -> {
                        AwRegionEntity awRegion = new AwRegionEntity();
                        awRegion.setId(i.getId());
                        awRegion.setName(i.getName());
                        awRegion.setDisabled(false);
                        awRegion.setParentId(i.getRegionId());
                        return awRegion;
                    })
                );
            })
            .collectList()
            .flatMapMany(all -> {
                List<AwRegionEntity> t = TreeSupportEntity.list2tree(all, AwRegionEntity::setChildren);
                return Flux.fromIterable(t);
            });
    }


}
