package com.yeejoin.equipmanage.operation.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.equipmanage.common.entity.dto.BuildSearchDTO;
import com.yeejoin.equipmanage.common.enums.GroupTypeEnum;
import com.yeejoin.equipmanage.context.SpringContextHolder;
import com.yeejoin.equipmanage.operation.PageOperation;
import com.yeejoin.equipmanage.service.IBuilldService;
import com.yeejoin.equipmanage.service.IFormInstanceService;
import com.yeejoin.equipmanage.service.impl.BuildingServiceImpl;
import com.yeejoin.equipmanage.service.impl.FormInstanceServiceImpl;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @Author: songLei
 * @Description: groupType是building的时候分页器
 * @Date: 2020/12/23 10:37
 * @Version: 1.0
 */
public class BuildRoomPage implements PageOperation {
    @Override
    public Page apply(Page page, BuildSearchDTO dto) {
        IFormInstanceService formInstanceService = SpringContextHolder.getBean(FormInstanceServiceImpl.class);
        IBuilldService builldService = SpringContextHolder.getBean(BuildingServiceImpl.class);
        List<Map<String,Object>> pageData = formInstanceService.queryPage(dto);
        StringBuffer sb = new StringBuffer();
        if(CollectionUtils.isNotEmpty(pageData)){
            pageData.parallelStream().forEach(instanceId ->{
                Map<String,Object> instanceIdMap = instanceId;
                Optional optional = Optional.ofNullable(instanceIdMap);
                optional.ifPresent(x ->{
                    if(instanceIdMap.get("groupType").equals(GroupTypeEnum.ROOM.getType())){
                        sb.append(instanceIdMap.get("instanceId")+",");
                    }
                    if(instanceIdMap.get("groupType").equals(GroupTypeEnum.FLOOR.getType())){
                        List<Long> ids = new ArrayList<>();
                        ids.add(Long.parseLong(String.valueOf(instanceIdMap.get("instanceId"))));
                        List<Map<String,Object>> coll = formInstanceService.queryFloorRoom(ids);
                        coll.parallelStream().forEach(item ->{
                            sb.append(item.get("instanceId")+",");
                        });
                    }
                });
            });
            dto.setInstanceId(sb.toString());
            return builldService.roomPage(page,dto);
        }
        return new Page();
    }
}
