package net.zstong.awump.base.web;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import net.zstong.awump.base.entity.*;
import net.zstong.awump.base.service.AwInstitutionService;
import net.zstong.awump.base.service.AwIntensiveFrameService;
import net.zstong.awump.base.service.AwRegionService;
import net.zstong.awump.base.service.AwWarehouseService;
import org.hswebframework.web.api.crud.entity.PagerResult;
import org.hswebframework.web.api.crud.entity.QueryOperation;
import org.hswebframework.web.api.crud.entity.QueryParamEntity;
import org.hswebframework.web.authorization.annotation.QueryAction;
import org.hswebframework.web.authorization.annotation.Resource;
import org.hswebframework.web.crud.service.ReactiveCrudService;
import org.hswebframework.web.crud.web.reactive.ReactiveServiceCrudController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping({"/aw/base/intensive-frame"})
@Resource(id = "aw-base-intensive-frame", name = "密集柜管理接口")
@Tag(name = "密集柜管理接口")
@Slf4j
public class AwIntensiveFrameController implements ReactiveServiceCrudController<AwIntensiveFrameEntity, String> {

    @Autowired
    private AwIntensiveFrameService awIntensiveFrameService;

    @Autowired
    private AwWarehouseService awWarehouseService;

    @Override
    public ReactiveCrudService<AwIntensiveFrameEntity, String> getService() {
        return awIntensiveFrameService;
    }



    @PostMapping("/info/_query")
    @QueryAction
    @Operation(summary = "分页查询密集柜带相关信息详情")
    public Mono<PagerResult<AwIntensiveFrameInfo>> queryInstitution(@RequestBody Mono<QueryParamEntity> paramBody) {
        return paramBody
            .flatMap(param -> awIntensiveFrameService.queryPager(param)
                .flatMap(result -> Flux
                    .fromIterable(result.getData()).flatMap(tp2 -> convert(tp2))
                    .collectList()
                    .map(info -> PagerResult.of(result.getTotal(), info, param))
                )
            );
    }

    private Mono<AwIntensiveFrameInfo> convert(AwIntensiveFrameEntity entity) {
        return Mono.just(AwIntensiveFrameInfo.of(entity)).flatMap(e->{
            return awWarehouseService.findById(e.getWarehouseId()).defaultIfEmpty(new AwWarehouseEntity()).map(h->{
                e.setWarehouse(h);
                return e;
            });
        });
    }
}
