package com.persagy.adm.server.backstage.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.persagy.adm.server.algorithm.constant.AdmModelFileStatusEnum;
import com.persagy.adm.server.algorithm.entity.AdmModelFile;
import com.persagy.adm.server.algorithm.service.AdmModelFileService;
import com.persagy.adm.server.algorithm.service.AdmModelService;
import com.persagy.adm.server.backstage.domain.AdmAnalysisModel;
import com.persagy.dmp.digital.entity.ObjectDigital;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 查询需要解析的模型文件数据
 * @author : lijie
 * Update By 2022/1/21 14:25
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class AdmPreFloorServiceImpl extends AdmAnalysisServiceBase {

    private final AdmModelService admModelService;

    @Override
    protected void analysisInternal(AdmAnalysisModel model) {
        List<AdmModelFile> admModelFiles = model.getAdmModelFiles();
        if (CollUtil.isEmpty(admModelFiles)){
            return;
        }
        queryFloors(model);
        this.getNext().analysis(model);
    }
    /**
     * 填充楼层信息
     * @param model :模型数据
     * return : void
     * @author : lijie
     * Update By 2022/1/21 16:57
     */
    private void queryFloors(AdmAnalysisModel model) {
        List<AdmModelFile> admModelFiles = model.getAdmModelFiles();
        Map<String, List<AdmModelFile>> listMap = admModelFiles.stream()
                .collect(Collectors.groupingBy(AdmModelFile::getGroupCode, Collectors.toList()));
        Map<String, ObjectDigital> floorMap = MapUtil.newHashMap();
        Set<Map.Entry<String, List<AdmModelFile>>> entries = listMap.entrySet();
        for (Map.Entry<String, List<AdmModelFile>> entry : entries) {
            if (CollUtil.isEmpty(entry.getValue())){
                continue;
            }
            Set<String> floorIds = entry.getValue()
                    .stream()
                    .map(AdmModelFile::getFloorId).collect(Collectors.toSet());
            List<ObjectDigital> floors = new ArrayList<>();
            try{
                floors = admModelService.queryFloorsByGroupCodeAndIds(entry.getKey(),floorIds);
            }catch (Exception e){
                log.warn("查询楼层信息失败:{},集团编码:{},楼层id数组:{}",e.getMessage(),entry.getKey(), JSONObject.toJSONString(floorIds));
            }
            if (CollUtil.isEmpty(floors)){
                continue;
            }
            for (ObjectDigital floor : floors) {
                floorMap.put(floor.getId(),floor);
            }
        }
        model.setFloorMap(floorMap);
    }
}
