package net.zstong.awump.base.service;

import lombok.extern.slf4j.Slf4j;
import net.zstong.awump.base.entity.AwInstitutionInfo;
import net.zstong.awump.base.entity.AwIntensiveFrameInfo;
import net.zstong.awump.base.entity.AwWarehouseEntity;
import net.zstong.awump.base.entity.AwWarehouseInfo;
import org.hswebframework.web.api.crud.entity.PagerResult;
import org.hswebframework.web.api.crud.entity.QueryParamEntity;
import org.hswebframework.web.crud.service.GenericReactiveCrudService;
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;

@Service
@Slf4j
public class AwWarehouseService extends GenericReactiveCrudService<AwWarehouseEntity, String> {


    @Autowired
    private AwInstitutionService awInstitutionService;

    @Autowired
    private AwRegionService awRegionService;

    public Mono<PagerResult<AwWarehouseInfo>> queryInfo(Mono<QueryParamEntity> paramBody) {
        return paramBody
            .flatMap(param -> this.queryPager(param)
                .flatMap(result -> Flux
                    .fromIterable(result.getData()).flatMap(entity -> toInfo(AwWarehouseInfo.of(entity)))
                    .collectList()
                    .map(info -> PagerResult.of(result.getTotal(), info, param))
                )
            );
    }

    private Mono<AwWarehouseInfo> toInfo(AwWarehouseInfo info) {
        return awInstitutionService.findById(info.getInstitutionId())
            .flatMap(i -> {
                info.setInstitution(AwInstitutionInfo.of(i));
                return awRegionService.findById(i.getRegionId()).map(r -> {
                        info.setRegion(r);
                        return info;
                    })
                    .switchIfEmpty(Mono.just(info));
            }).switchIfEmpty(Mono.just(info));
    }
}
