package com.persagy.proxy.report.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.persagy.dmp.basic.dto.RequestData;
import com.persagy.dmp.basic.model.QueryCriteria;
import com.persagy.dmp.basic.utils.JsonNodeUtils;
import com.persagy.dmp.common.constant.ResponseCode;
import com.persagy.dmp.common.model.entity.BaseEntity;
import com.persagy.dmp.define.client.DigitalObjectInfoFacade;
import com.persagy.dmp.define.entity.ObjectInfoDefine;
import com.persagy.dmp.digital.client.DigitalObjectFacade;
import com.persagy.dmp.digital.client.DigitalRelationFacade;
import com.persagy.dmp.digital.entity.ObjectRelation;
import com.persagy.dmp.simple.client.DigitalObjectSimpleFacade;
import com.persagy.proxy.adm.constant.AdmCommonConstant;
import com.persagy.proxy.adm.constant.AdmDictCategoryEnum;
import com.persagy.proxy.adm.request.AdmCreateRequest;
import com.persagy.proxy.adm.request.AdmQueryCriteria;
import com.persagy.proxy.adm.request.AdmResponse;
import com.persagy.proxy.adm.request.AdmZoneEquipQueryRequest;
import com.persagy.proxy.adm.utils.AdmContextUtil;
import com.persagy.proxy.adm.utils.AdmQueryCriteriaHelper;
import com.persagy.proxy.common.entity.DmpResult;
import com.persagy.proxy.common.entity.InstanceUrlParam;
import com.persagy.proxy.dictionary.model.AdmDict;
import com.persagy.proxy.dictionary.model.AdmObjectType;
import com.persagy.proxy.dictionary.service.IAdmDictService;
import com.persagy.proxy.object.model.*;
import com.persagy.proxy.object.service.IAdmComponentService;
import com.persagy.proxy.object.service.IAdmEquipmentService;
import com.persagy.proxy.object.service.IAdmSystemService;
import com.persagy.proxy.report.model.AdmGatherInfoPoint;
import com.persagy.proxy.report.model.AdmInfoPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Field;
import java.util.*;

/**
 *  设备报表API
 * @author lvxy
 * @date 2021/9/18
 */
@RestController
@RequestMapping("/equip-query")
public class AdmReportEquipController {

    @Autowired
    private IAdmDictService dictService;
    @Autowired
    private IAdmEquipmentService equipmentService;
    @Autowired
    private IAdmComponentService componentService;
    @Autowired
    private IAdmSystemService systemService;

    /**
     * 查询设备信息 关联的部件 资产信息
     * 查询设备关联资产部件数量
     *
     *
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/equip-components")
    public AdmResponse getEquipAssetComponents(@RequestBody AdmQueryCriteria request) throws Exception {
        //查询设备
        request.setName(AdmEquipment.OBJ_TYPE);
        List<AdmQueryCriteria> cascade = new ArrayList<>();
        //查询设备关联的部件
        AdmQueryCriteria cascadeCom = new AdmQueryCriteria();
        cascadeCom.setName("component");
        cascade.add(cascadeCom);
        //查询设备关联的系统
        AdmQueryCriteria cascadeSys = new AdmQueryCriteria();
        cascadeSys.setName("linkSystem");
        cascade.add(cascadeSys);
        request.setCascade(cascade);
        AdmResponse admResponse = equipmentService.query(request);
        Boolean showComponentFlag = false;
        List<AdmEquipment> equipmentList = (List<AdmEquipment>) admResponse.getContent();
        if(CollUtil.isNotEmpty(equipmentList)){
            equipmentList.stream().forEach(equip -> {
                if (CollUtil.isNotEmpty(equip.getComponent())) {
                    equip.setCount(equip.getComponent().size());
                    equip.setComponent(null);
                } else {
                    equip.setCount(0);
                }
               /* //特殊处理前端需要展示的字段
                if(StrUtil.isNotEmpty(equip.getLocalId())){
                    equip.getInfos().put("localId",equip.getLocalId());
                }
                if(StrUtil.isNotEmpty(equip.getBimId())){
                    equip.getInfos().put("bimId",equip.getBimId());
                }
                if(StrUtil.isNotEmpty(equip.getBimLocation())){
                    equip.getInfos().put("bimLocation",equip.getBimLocation());
                }*/
            });
            //查询设备的类型信息，取list中的第一个数据
            AdmEquipment admEquipment = equipmentList.get(0);
            QueryCriteria defineCriteria = new QueryCriteria();
            ObjectNode criteria = JsonNodeFactory.instance.objectNode();
            criteria.put("equipmentCode", admEquipment.getClassCode());
            defineCriteria.setCriteria(criteria);
            AdmResponse defRes = dictService.doQueryObjectType(AdmContextUtil.toDmpContext(), defineCriteria, AdmObjectType.class);
            if (CollUtil.isNotEmpty(defRes.getContent())) {
                List<AdmObjectType> componentCategory = (List<AdmObjectType>) defRes.getContent();
                if(CollUtil.isNotEmpty(componentCategory)){
                    showComponentFlag = true;
                }
                admEquipment.setComponentCategory(componentCategory);
                equipmentList.set(0, admEquipment);
            }
        }else{
            equipmentList = new ArrayList<>();
        }
        AdmResponse response = AdmResponse.success(equipmentList, request);
        response.setTotal(admResponse.getTotal());
        if(showComponentFlag){
            response.setMessage("1");
        }
        return response;
    }

    /**
     * 查询当前设备类型下的部件分类以及数量
     *
     * @param request 查询信息条件
     * @return 查询结果
     */
    @PostMapping("/components-count")
    public AdmResponse getEquipComponentsCount(@RequestBody AdmQueryCriteria request){
        QueryCriteria queryCriteria = AdmQueryCriteriaHelper.toDmpCriteria(request);
        ObjectNode criteria = queryCriteria.getCriteria();
        if(JSONUtil.isNull(criteria)){
            return AdmResponse.failure("请求参数错误");
        }
        final String KEY="id";
        if (!criteria.has(KEY)
                || !criteria.get(KEY).isTextual()){
            return AdmResponse.success();
        }
        RequestData requestData = new RequestData();
        requestData.setEquipmentId(criteria.get(KEY).asText());
        InstanceUrlParam context = AdmContextUtil.toDmpContext();
        List<Map<String, Object>> result = DigitalObjectSimpleFacade.queryComponentsCountByEquipId(context.getGroupCode(),
                context.getProjectId(), context.getAppId(),null,requestData);
        if(CollUtil.isEmpty(result)){
            return AdmResponse.success();
        }
        // 处理一下返回值
        for (Map<String, Object> objectMap : result) {
            if (MapUtil.isEmpty(objectMap)){
                continue;
            }
            objectMap.put("categoryName",objectMap.get("category_name"));
            objectMap.put("category",objectMap.get("class_code"));
            objectMap.put("objectType",null);
            objectMap.put("statistics",new HashMap<>());
        }
        return AdmResponse.success(result);
    }


    /**
     * 查詢部件关联的资产
     *  资产相关暂未支持
     *
     * @param   request     查询信息条件
     * @return              查询结果
     */
    @PostMapping("/components-property")
    public AdmResponse getComponentProperty(@RequestBody AdmQueryCriteria request){
        request.setName(AdmComponent.OBJ_TYPE);
        return componentService.doQuery(AdmContextUtil.toDmpContext(), request, AdmComponent.class);
    }

    /**
     *查询当前设备类型的允许下所有部件类型，设备下的部件对应数量
     *
     * @param   id          设备id
     * @param   category    分类
     */
    @GetMapping("/equip-compon")
    public AdmResponse getEquipCompon(@RequestParam(value = "id") String id,
                                      @RequestParam(value = "category") String category){
        //return  rEquipComponService.getEquipCompon(id,category)
        RequestData requestData = new RequestData();
        if(StrUtil.isNotEmpty(id)){
            requestData.setEquipmentId(id);
        }
        if(StrUtil.isNotEmpty(category)){
            requestData.setClassCode(category);
        }
        InstanceUrlParam context = AdmContextUtil.toDmpContext();
        List<Map<String, Object>> result = DigitalObjectSimpleFacade.queryEquipComponentsByProjectId(context.getGroupCode(),
                context.getProjectId(), context.getAppId(),null, requestData);
        if(CollUtil.isEmpty(result)){
            return AdmResponse.success();
        }
        return AdmResponse.success(result);
    }

    /**
     * TODO
     * 根据设备批量创建资产
     * 资产相关暂未支持
     */
    @PostMapping("/creat-propertys")
    public AdmResponse batchCreation(@RequestBody AdmCreateRequest<AdmEquipment> createRequest ) {
        //return EquipmentService.batchCreationProperty(request)
        return null;
    }

    /**
     * 根据条件查询统计数量 查询设备或部件
     * 例子： 根据设备类型或部件类型查询（\"Filters\": \"category ='SISU'\"）," +
     *      "根据设备类型和建筑查询（\"Filters\": \"category ='FASE';buildingId = '建筑id'\"），" +
     *      "根据设备类型和建筑楼层查询（\"Filters\": \"category ='FASE';buildingId = '建筑id';floorId = '楼层id'\"）"
     */
    @PostMapping("/count")
    public AdmResponse count(@RequestBody AdmQueryCriteria request) {
        QueryCriteria queryCriteria = AdmQueryCriteriaHelper.toDmpCriteria(request);
        ObjectNode criteria = JsonNodeFactory.instance.objectNode();
        if(StrUtil.isNotEmpty(request.getFilters()) && request.getFilters().contains("category")){
            criteria.put("classCode", criteria.get("category").textValue());
            criteria.remove("category");
        }
        queryCriteria.setCriteria(criteria);
        queryCriteria.setOnlyCount(true);
        List<ObjectNode> euipCom = DigitalObjectFacade.query(AdmContextUtil.toDmpContext().getGroupCode(),AdmContextUtil.toDmpContext().getProjectId(),AdmCommonConstant.APP_ID,null, queryCriteria);
        if(CollUtil.isNotEmpty(euipCom)){
            return AdmResponse.success(euipCom);
        }else{
            return AdmResponse.success();
        }
    }

    /**
     * 查询设备或部件
     *
     * 例子： 根据设备类型或部件类型查询（\"Filters\": \"category ='SISU'\"）," +
     *             "根据设备类型和建筑查询（\"Filters\": \"category ='FASE';buildingId = '建筑id'\"），" +
     *             "根据设备类型和建筑楼层查询（\"Filters\": \"category ='FASE';buildingId = '建筑id';floorId = '楼层id'\"）"
     */
    @PostMapping("/pagequery")
    public AdmResponse pageQuery(@RequestBody AdmQueryCriteria request) {
        QueryCriteria queryCriteria = AdmQueryCriteriaHelper.toDmpCriteria(request);
        ObjectNode criteria = JsonNodeFactory.instance.objectNode();
        queryCriteria.setCriteria(criteria);
        if(StrUtil.isNotEmpty(request.getFilters()) && request.getFilters().contains("category")){
            criteria.put("classCode", criteria.get("category").textValue());
            criteria.remove("category");
        }
        List<ObjectNode> euipCom = DigitalObjectFacade.query(AdmContextUtil.toDmpContext().getGroupCode(),AdmContextUtil.toDmpContext().getProjectId(),AdmCommonConstant.APP_ID,null, queryCriteria);
        if(CollUtil.isNotEmpty(euipCom)){
            return AdmResponse.success(euipCom);
        }else{
            return AdmResponse.success();
        }
    }

    /**
     * 跟维新确认过 暂未使用
     *
     * 根据建筑, 楼层, 业务空间类型, 业务空间id 查询设备
     *
     *  description = "例子： 根据设备类型或部件类型查询（\"Filters\": \"category ='SISU'\"）," +
     *             "根据设备类型和建筑查询（\"Filters\": \"category ='FASE';buildingId = '建筑id'\"），" +
     *             "根据设备类型和建筑楼层查询（\"Filters\": \"category ='FASE';buildingId = '建筑id';floorId = '楼层id'\"）" +
     *             "所属业务空间类型填在ZoneType字段, 所属业务空间id填在ZoneId字段" +
     *             "如果是查询不属于任何业务空间的对象, 设置notInZone = true"
     */
    @PostMapping("/zone-query")
    public AdmResponse zoneQuery(@RequestBody AdmZoneEquipQueryRequest request) {
        request.setName(AdmEquipment.OBJ_TYPE);
        if(StrUtil.isAllEmpty(request.getZoneType(),request.getZoneId())){
            return pageQuery(request);
        }else{

        }
        return null;
    }

    /**
     *  跟维新确认过 暂未使用
     * 根据建筑, 楼层, 业务空间类型, 业务空间id  查询部件
     *
     * 根据建筑, 楼层, 业务空间类型, 业务空间id查询部件", description = "例子： 根据设备类型或部件类型查询（\"Filters\": \"category ='SISU'\"）," +
     *             "根据设备类型和建筑查询（\"Filters\": \"category ='FASE';buildingId = '建筑id'\"），" +
     *             "根据设备类型和建筑楼层查询（\"Filters\": \"category ='FASE';buildingId = '建筑id';floorId = '楼层id'\"）" +
     *             "所属业务空间类型填在ZoneType字段, 所属业务空间id填在ZoneId字段" +
     *             "如果是查询不属于任何业务空间的对象, 设置notInZone = true"
     */
    @PostMapping("/zone-component-query")
    public AdmResponse zoneComponentQuery(@RequestBody AdmZoneEquipQueryRequest request) {
        if(StrUtil.isAllEmpty(request.getZoneType(),request.getZoneId())){
            request.setName(AdmComponent.OBJ_TYPE);
            return pageQuery(request);
        }
        return null;
    }

    /**
     * 批量创建设备同时创建资产、创建设备和系统的关系
     *
     */
    @PostMapping("/creat-equip-pro")
    public AdmResponse create(@RequestBody AdmCreateRequest<AdmEquipment> createRequest){
        //return EquipmentProSyService.createList(request)
        List<AdmEquipment> vos = CollUtil.newArrayList(createRequest.getContent());
        vos = equipmentService.doInsert(AdmContextUtil.toDmpContext(), AdmEquipment.class, vos);
        return AdmResponse.success(vos);
    }

    /**
     * 查询不在当前系统下的设备
     */
    @PostMapping("/equip-sys")
    public AdmResponse pageQueryEquipSys(@RequestBody AdmQueryCriteria request,
                                         @RequestParam(value = "sysId") String sysId){
        //return EquipmentService.queryBeforeEquipSy(sysId,request)
        QueryCriteria queryCriteria = AdmQueryCriteriaHelper.toDmpCriteria(request);
        ObjectNode criteriaEquip = JsonNodeFactory.instance.objectNode();
        criteriaEquip.put("objType", AdmEquipment.OBJ_TYPE);
        JSONObject relationTo = new JSONObject();
        relationTo.put("relCode", "Sy2Eq");
        relationTo.put("graphCode", "MechSubset");
        JSONObject objFrom = new JSONObject();
        objFrom.put("$ne",sysId);
        relationTo.put("objFrom", objFrom);
        criteriaEquip.putPOJO("relationTo",relationTo);
        queryCriteria.setCriteria(criteriaEquip);
        List<ObjectNode> equips = DigitalObjectFacade.query(AdmContextUtil.toDmpContext().getGroupCode(),AdmContextUtil.toDmpContext().getProjectId(),AdmCommonConstant.APP_ID,null,queryCriteria);
        return AdmResponse.success(equips);
    }

    /**
     * 查询当前系统下的设备
     *
     * datacenter 查询目标是SysEquip 没先查询系统，根据系统id查询系统和设备的关系，根据关系查询设备，拼接数据
     */
    @PostMapping("/sys-equip")
    public AdmResponse pageQuerySysEquip(@RequestBody AdmQueryCriteria request){
        //return SysEquipService.pageQuery(request, arrayListOf(SFilter.eq("projectId", SPageAdmContextUtil.toDmpContext().getHeader("projectId").toString())))
        request.setName(AdmSystem.OBJ_TYPE);
        QueryCriteria queryCriteria = AdmQueryCriteriaHelper.toDmpCriteria(request);
        queryCriteria.setSize(500L);
        List<ObjectNode> objectNodeList = DigitalObjectFacade.query(AdmContextUtil.toDmpContext().getGroupCode(), AdmContextUtil.toDmpContext().getProjectId(),AdmCommonConstant.APP_ID,null,queryCriteria);
        if(CollUtil.isEmpty(objectNodeList)){
            return AdmResponse.success();
        }
        List<AdmSystem> admSystemList = JSONUtil.toList(objectNodeList.toString(), AdmSystem.class);
        Map<String, AdmSystem> admSystemMap = CollUtil.fieldValueMap(admSystemList, BaseEntity.PROP_ID);
        QueryCriteria queryCriteriaRelation = new QueryCriteria();
        queryCriteriaRelation.setPage(request.getPageNumber() == null ? 0 : request.getPageNumber()*1L);
        queryCriteriaRelation.setSize(request.getPageSize() == null ? 0 : request.getPageSize()*1L);

        ObjectNode criteria = JsonNodeFactory.instance.objectNode();
        criteria.put("relCode", "Sy2Eq");
        criteria.put("graphCode", "MechSubset");
        ArrayNode arrayNode = criteria.putObject("objTo").putArray("$in");
        admSystemMap.keySet().stream().forEach(id -> arrayNode.add(id));
        queryCriteriaRelation.setCriteria(criteria);

        List<ObjectRelation> relations = DigitalRelationFacade.query(AdmContextUtil.toDmpContext().getGroupCode(),AdmContextUtil.toDmpContext().getProjectId(),AdmCommonConstant.APP_ID,null,queryCriteriaRelation);
        if(CollUtil.isEmpty(relations)){
            AdmResponse.success();
        }
        //objfrom = euipId
        Map<String, ObjectRelation> relationMap = CollUtil.fieldValueMap(relations,"objFrom");

        QueryCriteria queryCriteriaEqu = new QueryCriteria();
        ObjectNode criteriaEquip = JsonNodeFactory.instance.objectNode();
        criteriaEquip.put("objType", AdmEquipment.OBJ_TYPE);
        ArrayNode array = criteriaEquip.putObject("id").putArray("$in");
        relationMap.keySet().stream().forEach(id -> array.add(id));
        queryCriteriaEqu.setCriteria(criteriaEquip);
        List<ObjectNode> equips = DigitalObjectFacade.query(AdmContextUtil.toDmpContext().getGroupCode(),AdmContextUtil.toDmpContext().getProjectId(),AdmCommonConstant.APP_ID,null,queryCriteriaEqu);
        List<AdmEquipment> equipsList = JSONUtil.toList(equips.toString(), AdmEquipment.class);
        Map<String, AdmEquipment> admEquipmentMap = CollUtil.fieldValueMap(equipsList, BaseEntity.PROP_ID);

        List<AdmSystem> admSystems = new ArrayList<>(relations.size());
        relationMap.keySet().stream().forEach(euipId -> {
            ObjectRelation relation = relationMap.get(euipId);
            AdmSystem admSystem = admSystemMap.get(relation.getObjTo());
            admSystem.setEquipId(euipId);
            admSystem.setEquipLocalName(admEquipmentMap.get(euipId).getLocalName());
            admSystems.add(admSystem);
        });

        AdmResponse admResponse = new AdmResponse();
        admResponse.setPageNumber(request.getPageNumber());
        admResponse.setPageSize(admSystems.size());
        admResponse.setContent(admSystems);
        admResponse.setResult(DmpResult.SUCCESS);
        return admResponse;
    }

    /**
     * 查询项目下的所有设备和部件的类型、以及类型名称
     */
    @GetMapping("/equip-compon-category")
    public AdmResponse equipORComponCategory(){
        //return EquipORComponCategoryService.getEquipORComponCategory()
        RequestData requestData = new RequestData();
        if(StrUtil.isNotEmpty(AdmContextUtil.toDmpContext().getProjectId())){
            requestData.setProjectId(AdmContextUtil.toDmpContext().getProjectId());
        }
        requestData.setObjTypes(CollUtil.newHashSet(AdmEquipment.OBJ_TYPE, AdmComponent.OBJ_TYPE));
        List<Map<String, Object>> result = DigitalObjectSimpleFacade.queryDefineInfoByObjType(AdmContextUtil.toDmpContext().getGroupCode(),AdmContextUtil.toDmpContext().getProjectId(),AdmContextUtil.toDmpContext().getAppId(),null,requestData);
        if(CollUtil.isNotEmpty(result)){
            return AdmResponse.success(result);
        }else{
            return AdmResponse.success();
        }
    }

    /**
     *  批量处理设备关联资产、 查询接口
     *  查询项目下的设备或部件-根据项目、建筑、楼层、设备或部件分类、业务空间实例筛选设备 然后通过计算匹配资产
     *  查询条件中建筑id必须书写为buildingId，楼层id必须书写为floorId,spacrType物理世界定义的空间类型，spaceIdList业务空间实例id列表，category设备或部件类型
     *  TODO 资产相关功能暂时不提供，之后根据业务进行需求处理
     */
    @PostMapping("/equip-category-property")
    public AdmResponse equipProperty(@RequestParam(value = "category") String category,
                                     @RequestBody AdmQueryCriteria request, @RequestBody List<String>  spaceIdList,
                                     @RequestParam(value = "spacrType") String spacrType){
        //return EquipmentComService.equipProperty(category, request, spaceIdList, spacrType)
        return null;
    }

    /**
     * 批量添加设备和资产的关系
     * TODO 资产相关功能暂时不提供，之后根据业务进行需求处理
     */
    @PostMapping("/equip-r-property")
    public AdmResponse equipRelationshipProperty(@RequestBody AdmCreateRequest<AdmProperty> createRequest ) {
        //return EquipmentComService.equipPro(request)
        return null;
    }

    /**
     * 修改设备的附件功能
     * {
     *     "content":"{....}"  EquipUpDateEnclosure 实体list
     * }
     */
    @PostMapping("/update")
    public AdmResponse equipUpDateEnclosure(@RequestBody ObjectNode equipUpDateEnclosureRequest) {
        //return EquipmentService.equipUpDateEnclosurs(equipUpDateEnclosureRequest)
        if(JSONUtil.isNull(equipUpDateEnclosureRequest)){
            return AdmResponse.failure(ResponseCode.A0400.getDesc()+",不能为空");
        }

        List<EquipUpDateEnclosure> equipUpDateEnclosure = JSONUtil.toList(equipUpDateEnclosureRequest.get("content").toString(), EquipUpDateEnclosure.class);
        if(CollUtil.isNotEmpty(equipUpDateEnclosure)){
            Map<String, EquipUpDateEnclosure> equipUpDateEnclosureMap = CollUtil.fieldValueMap(equipUpDateEnclosure, BaseEntity.PROP_ID);
            if(equipUpDateEnclosureMap.size() < equipUpDateEnclosure.size()) {
                return AdmResponse.failure("设备id不能为空");
            }
            //获取待更新的设备
            QueryCriteria queryCriteria = new QueryCriteria();
            ObjectNode criteria = JsonNodeFactory.instance.objectNode();
            criteria.put("objType", AdmEquipment.OBJ_TYPE);
            ArrayNode arrayNode = criteria.putObject("id").putArray("$in");
            equipUpDateEnclosureMap.keySet().stream().forEach(equipId -> arrayNode.add(equipId));
            queryCriteria.setCriteria(criteria);
            AdmResponse equips = equipmentService.doQuery(AdmContextUtil.toDmpContext(), queryCriteria, AdmEquipment.class);
            if(CollUtil.isEmpty(equips.getContent())){
                return AdmResponse.failure(ResponseCode.A0400.getDesc());
            }
            //将需要更新的数据放到待更新的设备中
            List<AdmEquipment> equipmentList = JSONUtil.toList(equips.getContent().toString(), AdmEquipment.class);
            //获取所有属性
            Map<String, Field> fieldMap = ReflectUtil.getFieldMap(EquipUpDateEnclosure.class);
            //对每个设备更新属性
            equipmentList.stream().forEach(admEquipment -> {
                fieldMap.keySet().forEach(fieldName -> {
                    EquipUpDateEnclosure enclosure = equipUpDateEnclosureMap.get(admEquipment.getId());
                    List<AdmTaskPic> newAttr = (List<AdmTaskPic>) ReflectUtil.getFieldValue(enclosure,fieldName);
                    if(CollUtil.isNotEmpty(newAttr)){
                        dealTaskFiles(admEquipment, fieldName, newAttr);
                    }
                });
            });
            List<AdmEquipment> vos = equipmentService.doUpdate(AdmContextUtil.toDmpContext(), AdmEquipment.class, equipmentList);
            return AdmResponse.success(vos);
        }else{
            return AdmResponse.failure(ResponseCode.A0400.getDesc());
        }
    }

    /**
     * 根据模型id查询待删除的设备数量
     [{
     *    "modelId":"",
     *    "count":""
     * }]
     */
    @PostMapping("/equip-del-com")
    public AdmResponse equipComDel(@RequestBody List<ObjectNode> equipComDelList){
        //return EquipmentService.equipComDels(equipComDelList)
        if(CollUtil.isEmpty(equipComDelList)){
            return AdmResponse.success();
        }
        QueryCriteria queryCriteriaEuip = new QueryCriteria();
        ObjectNode criteriaEquip = JsonNodeFactory.instance.objectNode();
        criteriaEquip.put("objType", AdmEquipment.OBJ_TYPE);
        criteriaEquip.put("taskState",-1);
        ArrayNode idList = criteriaEquip.putObject("modelId").putArray("$in");
        // 组装结果Map 并 设置modelId数组
        Map<String, ObjectNode> equipDelMap = new HashMap<>(equipComDelList.size());
        for (ObjectNode equipComDel : equipComDelList) {
            // 取id
            JsonNode idNode = equipComDel.get("modelId");
            if(idNode == null || !idNode.isTextual()) {
                continue;
            }
            // 设置默认count
            JsonNode countNode = equipComDel.get("count");
            if(countNode == null || !countNode.isIntegralNumber()) {
                // 没有count，则设置为0
                equipComDel.put("count", 0);
            }
            idList.add(idNode.textValue());
            equipDelMap.put(idNode.textValue(), equipComDel);
        }
        queryCriteriaEuip.setCriteria(criteriaEquip);
        List<ObjectNode> equipList = DigitalObjectFacade.query(AdmContextUtil.toDmpContext().getGroupCode(),AdmContextUtil.toDmpContext().getProjectId(),AdmCommonConstant.APP_ID,null, queryCriteriaEuip);
        if(CollUtil.isEmpty(equipList)){
            return AdmResponse.success(equipComDelList);
        }
        // 按查询到的设备计数
        equipList.stream().forEach(eq -> {
            String modelId = eq.get("modelId").textValue();
            if(equipDelMap.containsKey(modelId)){
                ObjectNode delCounter = equipDelMap.get(modelId);
                int count = delCounter.get("count").intValue() + 1;
                delCounter.put("count", count);
            }
        });
        return AdmResponse.success(equipComDelList);
    }


    /**
     * 根据模型id查询待补充的设备数量
     * [{
     *    "modelId":"",
     *    "count":""
     * }]
     */
    @PostMapping("/equip-supply")
    public AdmResponse equipPropertySupply(@RequestBody List<ObjectNode> equipComDelList){
        if(CollUtil.isEmpty(equipComDelList)){
            return AdmResponse.success();
        }
        //1. 根据modelId查询楼层信息
        QueryCriteria queryCriteria = new QueryCriteria();
        ObjectNode criteria = JsonNodeFactory.instance.objectNode();
        criteria.put("objType", AdmFloor.OBJ_TYPE);
        ArrayNode idList = criteria.putObject("modelId").putArray("$in");
        // 组装结果Map 并 设置modelId数组
        Map<String, ObjectNode> equipDelMap = new HashMap<>(equipComDelList.size());
        for (ObjectNode equipComDel : equipComDelList) {
            // 取id
            JsonNode idNode = equipComDel.get("modelId");
            if(idNode == null || !idNode.isTextual()) {
                continue;
            }
            // 设置默认count
            JsonNode countNode = equipComDel.get("count");
            if(countNode == null || !countNode.isIntegralNumber()) {
                // 没有count，则设置为0
                equipComDel.put("count", 0);
            }
            idList.add(idNode.textValue());
            equipDelMap.put(idNode.textValue(), equipComDel);
        }
        queryCriteria.setCriteria(criteria);
        List<ObjectNode> floorList = DigitalObjectFacade.query(AdmContextUtil.toDmpContext().getGroupCode(),AdmContextUtil.toDmpContext().getProjectId(),AdmCommonConstant.APP_ID,null,queryCriteria);
        if(CollUtil.isEmpty(floorList)){
            return AdmResponse.success(equipComDelList);
        }
        List<AdmFloor> admFloorList = JSONUtil.toList(floorList.toString(), AdmFloor.class);
        Map<String, AdmFloor> admFloorMap = CollUtil.fieldValueMap(admFloorList, BaseEntity.PROP_ID);
        //2. 根据楼层信息 查询需要补充设备（bimId isnull,bimLocation not isnull,modelId isnull）数量
        QueryCriteria queryCriteriaEuip = new QueryCriteria();
        ObjectNode criteriaEquip = JsonNodeFactory.instance.objectNode();
        criteriaEquip.put("objType", AdmEquipment.OBJ_TYPE);
        ArrayNode array = criteriaEquip.putObject("floorId").putArray("$in");
        admFloorMap.keySet().stream().forEach(id -> array.add(id));
        criteria.putObject("bimId").put("$null", true);
        criteria.putObject("bimLocation").put("$null", false);
        criteria.putObject("modelId").put("$null", true);
        queryCriteriaEuip.setCriteria(criteriaEquip);
        List<ObjectNode> equipList = DigitalObjectFacade.query(AdmContextUtil.toDmpContext().getGroupCode(),AdmContextUtil.toDmpContext().getProjectId(),AdmCommonConstant.APP_ID,null, queryCriteriaEuip);
        if(CollUtil.isEmpty(equipList)){
            return AdmResponse.success(equipComDelList);
        }
        // 按楼层统计设备数量
        equipList.forEach(equip -> {
            String floorId = equip.get("floorId").textValue();
            if(admFloorMap.containsKey(floorId)){
                AdmFloor floor = admFloorMap.get(floorId);
                int count = floor.getCount() == null ? 0 : floor.getCount();
                floor.setCount(count+1);
            }
        });
        // 3 根据floorId,modelId 汇总
        admFloorMap.values().forEach(floor -> {
            String modelId = floor.getModelId();
            if(equipDelMap.containsKey(modelId)){
                ObjectNode delCounter = equipDelMap.get(modelId);
                int count = delCounter.get("count").intValue() + (floor.getCount() == null ? 0 : floor.getCount());
                delCounter.put("count", count);
            }
        });
        return AdmResponse.success(equipComDelList);
    }

    /**
     * 模型质量报告 待删除的设备
     * 级联-任务（scanTaskBase）、资产（property）、设备类型（equipCategory），级联任务的时候需要设置条件（TaskState = 0 添加时间降序  取第一个值 ）
     */
    @PostMapping("/equip-comm-del")
    public AdmResponse equipCommDel(@RequestBody AdmQueryCriteria request){
        //return EquipDelService.pageQuery(sQueryRequest,withFilterList)
        //e.task_state = '-1'::integer
        //AND NOT e.model_id IS NULL
        //TODO 关联 revit.model_floor revit.model_folder 展示模型相关内容
        request.setName(AdmEquipment.OBJ_TYPE);
        QueryCriteria queryCriteria = AdmQueryCriteriaHelper.toDmpCriteria(request);
        ObjectNode criteria = queryCriteria.getCriteria();
        JSONObject modelId = new JSONObject();
        modelId.put("$null", false);
        criteria.putPOJO("modelId", modelId);
        criteria.put("taskState","-1");
        queryCriteria.setCriteria(criteria);

        AdmResponse equipRes = equipmentService.doQuery(AdmContextUtil.toDmpContext(), queryCriteria, AdmEquipment.class);
        return equipRes;
    }

    /**
     * 模型质量报告 待补充的设备
     * 级联-设备类型（equipFamily）
     */
    @PostMapping("/property-equip-supp")
    public AdmResponse propertyEquip(@RequestBody AdmQueryCriteria request){

        //return EquipmentService.equipPropertySupp(sQueryRequest)
        //equipment.bim_id IS NULL
        //  AND equipment.model_id IS NULL
        //  AND NOT equipment.bim_location IS NULL;

        AdmQueryCriteria admQueryCriteria = request;
        StringBuilder filters = new StringBuilder();
        filters.append("floorId startwith 'Eq'");
        filters.append(";buildingId startwith 'Bd'");
        filters.append(";bimId isnull");
        filters.append(";modelId isnull");
        admQueryCriteria.setFilters(filters.toString());
        admQueryCriteria.setName(AdmEquipment.OBJ_TYPE);
        QueryCriteria queryCriteria = AdmQueryCriteriaHelper.toDmpCriteria(admQueryCriteria);
        ObjectNode criteria = queryCriteria.getCriteria();
        JSONObject bimLocation = new JSONObject();
        bimLocation.put("$null", false);
        criteria.putPOJO("bimLocation", bimLocation);
        queryCriteria.setCriteria(criteria);

        AdmResponse equipRes = equipmentService.doQuery(AdmContextUtil.toDmpContext(), queryCriteria, AdmEquipment.class);
        if(CollUtil.isNotEmpty(equipRes.getContent())){
            List<AdmEquipment> admEquipments = JSONUtil.toList(equipRes.getContent().toString(), AdmEquipment.class);
            Map<String, AdmEquipment> admEquipmentMap = CollUtil.fieldValueMap(admEquipments, BaseEntity.PROP_ID);
            if(CollUtil.isEmpty(request.getCascade())){
                List<AdmQueryCriteria> cascade = new ArrayList<>();
                AdmQueryCriteria admQueryCriteriaBd = new AdmQueryCriteria();
                admQueryCriteriaBd.setName(AdmBuilding.OBJ_TYPE);
                cascade.add(admQueryCriteriaBd);
                AdmQueryCriteria admQueryCriteriaFl = new AdmQueryCriteria();
                admQueryCriteriaFl.setName(AdmFloor.OBJ_TYPE);
                cascade.add(admQueryCriteriaFl);
                request.setCascade(cascade);
                request.setName(AdmEquipment.OBJ_TYPE);
            }
            ArrayNode arrayNode = JsonNodeFactory.instance.arrayNode();
            admEquipmentMap.keySet().stream().forEach(id -> arrayNode.add(id));
            String filter = "";
            if(StrUtil.isNotEmpty(request.getFilters())){
                filter = request.getFilters();
            }
            filter =  filter + ";id in "+arrayNode.toString();
            request.setFilters(filter);

            AdmResponse admResponse = equipmentService.query(request);
            if(CollUtil.isNotEmpty(admResponse.getContent())){
                //处理数据
                List<ObjectNode> objectNodeList = (List<ObjectNode>) admResponse.getContent();
                objectNodeList.stream().forEach(equip ->{
                    JsonNode building = equip.get("building");
                    JsonNode floor = equip.get("floor");
                    if(!JSONUtil.isNull(building)){
                        equip.put("buildingName", building.get("localName").textValue());
                    }
                    if(!JSONUtil.isNull(floor)){
                        equip.put("floorName", floor.get("localName").textValue());
                        equip.put("modelId", floor.get("modelId").textValue());
                    }
                });
            }
            return admResponse;
        }else{
            return AdmResponse.success();
        }

        /**  sql
         *  SELECT equipment.id,
         *        equipment.name,
         *        equipment.local_id,
         *        equipment.local_name,
         *        equipment.bim_id,
         *        equipment.bim_location,
         *        equipment.floor_id,
         *        equipment.building_id,
         *        equipment.cad_id,
         *        equipment.project_id,
         *        equipment.find_people,
         * 			 equipment.class_code,
         *        equipment.infos,
         * 			 JSON_EXTRACT(floor.infos, '$.modeId') as model_id,
         * 							 floor.local_name as floor_name,
         *                (SELECT building.local_name
         *                 FROM dt_object building
         *                 WHERE building.id = JSON_EXTRACT(equipment.infos, '$.buildingId') and building.obj_type = 'building') AS building_name,
         *
         *                (SELECT def_class.name
         *                 FROM dt_define_type def_class
         *                 WHERE def_class.code = equipment.class_code
         *                 LIMIT 1)                                               AS code_name
         *
         * from (	SELECT equipment.id,
         *                equipment.name,
         *                equipment.local_id,
         *                equipment.local_name,
         * 							 equipment.class_code,
         *                JSON_EXTRACT(equipment.infos, '$.bimId') bim_id,
         *                JSON_EXTRACT(equipment.infos, '$.bimLocation') bim_location,
         *                JSON_EXTRACT(equipment.infos, '$.floorId') floor_id,
         *                JSON_EXTRACT(equipment.infos, '$.buildingId') building_id,
         *                JSON_EXTRACT(equipment.infos, '$.cadId') cad_id,
         *                equipment.project_id,
         *                JSON_EXTRACT(equipment.infos, '$.findPeople') find_people,
         *                equipment.infos
         * 				FROM dt_object equipment
         * 				WHERE equipment.obj_type='equipment'
         * 					AND JSON_EXTRACT(equipment.infos, '$.bimId') IS NULL
         *           AND JSON_EXTRACT(equipment.infos, '$.modeId') IS NULL
         * 					AND JSON_EXTRACT(equipment.infos, '$.buildingId') IS NOT NULL
         *           AND JSON_EXTRACT(equipment.infos, '$.floorId') IS NOT NULL
         *           AND JSON_EXTRACT(equipment.infos, '$.bimLocation') IS NOT NULL
         * ) equipment	left join dt_object floor on fl
         */
    }

    /**
     * 设备信息点
     * 统计设备信息点与总数据占比
     */
    @PostMapping("/info-point")
    public AdmResponse infoPoint() {
        if(StrUtil.isEmpty(AdmContextUtil.toDmpContext().getProjectId())){
            return AdmResponse.failure(ResponseCode.A0400.getCode());
        }
        AdmInfoPoint infoPoint = new AdmInfoPoint();
        // 根据objType获取定义 获取采集的设备的classcode
        Set<String> objTypes = new HashSet<>(1);
        objTypes.add(AdmEquipment.OBJ_TYPE);
        List<Map<String, Object>> codes = DigitalObjectSimpleFacade.queryDefineInfoByObjType(AdmContextUtil.toDmpContext().getGroupCode(), AdmContextUtil.toDmpContext().getProjectId(), AdmCommonConstant.APP_ID,null, RequestData.builder().objTypes(objTypes).build());
        if(CollUtil.isNotEmpty(codes)) {
            Set<String> classCodeSet = new HashSet<String>(codes.size());
            codes.stream().forEach(stringObjectMap -> classCodeSet.add(stringObjectMap.get("code").toString()));

            //项目下所有已采集的动态信息点编码
            List<ObjectInfoDefine> dynamicInfoPointCodes = gatherDynamicInfoCode(false, classCodeSet, false);
            //项目下所有已采集静态信息点编码
            List<ObjectInfoDefine> staticInfoPointCodes = gatherStaticInfoCode(false, classCodeSet, false);
            //项目下所有的设备  分页查询
            AdmQueryCriteria admQueryCriteriaObj = new AdmQueryCriteria();
            admQueryCriteriaObj.setPageNumber(1);
            admQueryCriteriaObj.setPageSize(500);
            admQueryCriteriaObj.setName(AdmEquipment.OBJ_TYPE);

            //admQueryCriteriaObj.setProjection(Arrays.asList("id", "name", "localId", "localName", "cadId", "bimId", "bimLocation", "infos", "classCode", "equipSerial", "bimFamilyName", "bimFamilySymbol"));
            AdmResponse admResponse = equipmentService.query(admQueryCriteriaObj);

            Map<String, Integer> hashMap = new HashMap<>();
            List<AdmEquipment> admEquipmentList = (List<AdmEquipment>) admResponse.getContent();
            List<ObjectNode> projectEquipment = JsonNodeUtils.toListNode(admEquipmentList, null, null);
            calculate(dynamicInfoPointCodes, staticInfoPointCodes, projectEquipment, 0, hashMap);

            long page = admResponse.getTotal() / admResponse.getPageSize() + 1;
            if (page >= 2) {
                for (long i = 2; i <= page; i++) {
                    admQueryCriteriaObj.setPageNumber(Integer.parseInt(String.valueOf(i)));
                    admResponse = equipmentService.query(admQueryCriteriaObj);
                    admEquipmentList = (List<AdmEquipment>) admResponse.getContent();
                    projectEquipment = JsonNodeUtils.toListNode(admEquipmentList, null, null);
                    calculate(dynamicInfoPointCodes, staticInfoPointCodes, projectEquipment, 0, hashMap);
                }
            }
            infoPoint.setDynamicInfoPointCounts(dynamicInfoPointCodes.size());
            infoPoint.setStaticInfoPointCounts(staticInfoPointCodes.size());
            infoPoint.setDynamicInfoPoint(hashMap.get("dynamicInfoPoint"));
            infoPoint.setStaticInfoPoint(hashMap.get("staticInfoPoint"));
        }
        return AdmResponse.success(CollUtil.newArrayList(infoPoint));
    }

    /**
     * 设备已采集信息点
     * 统计设备信息点与需采集数据占比
     */
    @PostMapping("/gather-info-point")
    public AdmResponse gatherInfoPoint() {
        if(StrUtil.isEmpty(AdmContextUtil.toDmpContext().getProjectId())){
            return AdmResponse.failure(ResponseCode.A0400.getCode());
        }
        Integer controlInfoCounts = controlInfoCounts(AdmEquipment.OBJ_TYPE, false);
        AdmGatherInfoPoint gatherInfoPoint = new AdmGatherInfoPoint();
        gatherInfoPoint.setGatherInfoPointCounts(controlInfoCounts);
        // 根据objType获取定义 获取采集的设备的classcode
        Set<String> objTypes = new HashSet<>(1);
        objTypes.add(AdmEquipment.OBJ_TYPE);
        List<Map<String, Object>> codes = DigitalObjectSimpleFacade.queryDefineInfoByObjType(AdmContextUtil.toDmpContext().getGroupCode(), AdmContextUtil.toDmpContext().getProjectId(), AdmCommonConstant.APP_ID,null, RequestData.builder().objTypes(objTypes).build());
        if(CollUtil.isNotEmpty(codes)){
            Set<String> classCodeSet = new HashSet<String>(codes.size());
            codes.stream().forEach(stringObjectMap -> classCodeSet.add(stringObjectMap.get("code").toString()));

            //项目下所有已采集的动态信息点编码
            List<ObjectInfoDefine> gatherDynamicInfoCode = gatherDynamicInfoCode(true, classCodeSet, false);
            //项目下所有已采集静态信息点编码
            List<ObjectInfoDefine> gatherStaticInfoCode =  gatherStaticInfoCode(true, classCodeSet, false);

            //项目下所有的设备  分页查询
            AdmQueryCriteria admQueryCriteriaObj =  new AdmQueryCriteria();
            admQueryCriteriaObj.setPageNumber(1);
            admQueryCriteriaObj.setPageSize(500);
            admQueryCriteriaObj.setName(AdmEquipment.OBJ_TYPE);

            //admQueryCriteriaObj.setProjection(Arrays.asList("id","name","localId","localName","cadId","bimId","bimLocation","infos","classCode","equipSerial","bimFamilyName","bimFamilySymbol"));
            AdmResponse admResponse = equipmentService.query(admQueryCriteriaObj);

            Map<String,Integer> hashMap = new HashMap<>();
            List<AdmEquipment> admEquipmentList = (List<AdmEquipment>) admResponse.getContent();
            List<ObjectNode> projectEquipment = JsonNodeUtils.toListNode(admEquipmentList,null,null);
            calculate(gatherDynamicInfoCode, gatherStaticInfoCode, projectEquipment,0, hashMap);

            long page = admResponse.getTotal() / admResponse.getPageSize() + 1;
            if(page >= 2){
                for(long i = 2; i <= page; i++){
                    admQueryCriteriaObj.setPageNumber(Integer.parseInt(String.valueOf(i)));
                    admResponse = equipmentService.query(admQueryCriteriaObj);
                    admEquipmentList = (List<AdmEquipment>) admResponse.getContent();
                    projectEquipment = JsonNodeUtils.toListNode(admEquipmentList,null,null);
                    calculate(gatherDynamicInfoCode, gatherStaticInfoCode, projectEquipment,0, hashMap);
                }
            }
            gatherInfoPoint.setGatherCustomInfoPointCounts(hashMap.get("customInfoPoint"));
            gatherInfoPoint.setGatherDynamicInfoPointCounts(hashMap.get("dynamicInfoPoint"));
            gatherInfoPoint.setGatherStaticInfoPointCounts(hashMap.get("staticInfoPoint"));
        }
        return AdmResponse.success(CollUtil.newArrayList(gatherInfoPoint));
    }


    /**
     * 统计系统信息点与需采集数据占比
     */
    @PostMapping("/system-info-point")
    public AdmResponse systemInfoPoin() {
        AdmGatherInfoPoint gatherInfoPoint = new AdmGatherInfoPoint();
        Integer controlInfoCounts = controlInfoCounts(AdmSystem.OBJ_TYPE, true);
        gatherInfoPoint.setGatherInfoPointCounts(controlInfoCounts);
        // 根据objType获取定义 获取采集的设备的classcode
        Set<String> objTypes = new HashSet<>(1);
        objTypes.add(AdmSystem.OBJ_TYPE);
        List<Map<String, Object>> codes = DigitalObjectSimpleFacade.queryDefineInfoByObjType(AdmContextUtil.toDmpContext().getGroupCode(), AdmContextUtil.toDmpContext().getProjectId(), AdmCommonConstant.APP_ID,null, RequestData.builder().objTypes(objTypes).build());
        if(CollUtil.isNotEmpty(codes)){
            Set<String> classCodeSet = new HashSet<String>(codes.size());
            codes.stream().forEach(stringObjectMap -> classCodeSet.add(stringObjectMap.get("code").toString()));

            //项目下所有已采集的动态信息点编码
            List<ObjectInfoDefine> gatherDynamicInfoCode = gatherDynamicInfoCode(true, classCodeSet, true);
            //项目下所有已采集静态信息点编码
            List<ObjectInfoDefine> gatherStaticInfoCode =  gatherStaticInfoCode(true, classCodeSet, true);

            //项目下所有的设备  分页查询
            AdmQueryCriteria admQueryCriteriaObj =  new AdmQueryCriteria();
            admQueryCriteriaObj.setPageNumber(1);
            admQueryCriteriaObj.setPageSize(500);
            admQueryCriteriaObj.setName(AdmSystem.OBJ_TYPE);

            //admQueryCriteriaObj.setProjection(Arrays.asList("id","name","localId","localName","cadId","bimId","infos","classCode"));
            AdmResponse admResponse = systemService.query(admQueryCriteriaObj);

            Map<String,Integer> hashMap = new HashMap<>();
            List<AdmSystem> admSystemList = (List<AdmSystem>) admResponse.getContent();
            List<ObjectNode> projectEquipment = JsonNodeUtils.toListNode(admSystemList,null,null);
            calculate(gatherDynamicInfoCode, gatherStaticInfoCode, projectEquipment,1, hashMap);

            long page = admResponse.getTotal() / admResponse.getPageSize() + 1;
            if(page >= 2){
                for(long i = 2; i <= page; i++){
                    admQueryCriteriaObj.setPageNumber(Integer.parseInt(String.valueOf(i)));
                    admResponse = systemService.query(admQueryCriteriaObj);
                    admSystemList = (List<AdmSystem>) admResponse.getContent();
                    projectEquipment = JsonNodeUtils.toListNode(admSystemList,null,null);
                    calculate(gatherDynamicInfoCode, gatherStaticInfoCode, projectEquipment,1, hashMap);
                }
            }
            gatherInfoPoint.setGatherCustomInfoPointCounts(hashMap.get("customInfoPoint"));
            gatherInfoPoint.setGatherDynamicInfoPointCounts(hashMap.get("dynamicInfoPoint"));
            gatherInfoPoint.setGatherStaticInfoPointCounts(hashMap.get("staticInfoPoint"));
        }
        return AdmResponse.success(CollUtil.newArrayList(gatherInfoPoint));
    }


    /**
     * 台账中待删除的对象 数量统计
     */
    @PostMapping("/del-equip-comm-pro")
    public AdmResponse deleteObj(){
        QueryCriteria queryCriteria = new QueryCriteria();
        ObjectNode criteria = JsonNodeFactory.instance.objectNode();
        criteria.put("taskState", -1);
        criteria.put("objType","['equipment','component']");
        queryCriteria.setCriteria(criteria);
        queryCriteria.setOnlyCount(true);
        List<ObjectNode> euipCom = DigitalObjectFacade.query(AdmContextUtil.toDmpContext().getGroupCode(),AdmContextUtil.toDmpContext().getProjectId(),AdmCommonConstant.APP_ID,null, queryCriteria);
        if(CollUtil.isNotEmpty(euipCom)){
            return AdmResponse.success(euipCom);
        }else{
            return AdmResponse.success();
        }
    }

    /**
     * 项目下的所有设备类型以及名称
     *
     * @return 返回对象列表
     */
    @PostMapping("/type")
    public AdmResponse equipType(){
        RequestData requestData = new RequestData();
        if(StrUtil.isNotEmpty(AdmContextUtil.toDmpContext().getProjectId())){
            requestData.setProjectId(AdmContextUtil.toDmpContext().getProjectId());
        }
        requestData.setObjType(AdmEquipment.OBJ_TYPE);
        List<Map<String, Object>> result = DigitalObjectSimpleFacade.queryDefineInfoByObjType(AdmContextUtil.toDmpContext().getGroupCode(),AdmContextUtil.toDmpContext().getProjectId(),AdmContextUtil.toDmpContext().getAppId(),null,requestData);
        if(CollUtil.isNotEmpty(result)){
            return AdmResponse.success(result);
        }else{
            return AdmResponse.success();
        }
    }

    /**
     * 查询系统-设备类树
     * @return
     * @throws Exception
     */
    @GetMapping("/type/tree")
    public AdmResponse querySystemEquipCategory() throws Exception {
        // 组装上下文条件
        AdmDict request = AdmDict.builder().type(AdmDictCategoryEnum.SYSTEM_EQUIP.getValue()).build();
        return dictService.queryCategory(AdmContextUtil.toDmpContext(),request,AdmObjectType.class);
    }

    /**
     * 计算动态、静态信息点
     * num 0 设备， 1 系统
     */
    private void calculate(List<ObjectInfoDefine> dynamicInfoPointCodes, List<ObjectInfoDefine> staticInfoPointCodes, List<ObjectNode> objList, Integer num, Map<String, Integer> hashMap) {
        int dynamicInfoPoint = hashMap.get("dynamicInfoPoint") == null ? 0 : hashMap.get("dynamicInfoPoint");
        int staticInfoPoint = hashMap.get("staticInfoPoint") == null ? 0 : hashMap.get("staticInfoPoint");
        int customInfoPoint = hashMap.get("customInfoPoint") == null ? 0 : hashMap.get("customInfoPoint");

        if(CollUtil.isNotEmpty(objList)) {
            for (int i = 0; i < objList.size(); i++) {
                JsonNode jsonNode = objList.get(i);
                Iterator<ObjectInfoDefine> iterator1 = staticInfoPointCodes.iterator();
                while (iterator1.hasNext()) {
                    ObjectInfoDefine infoDefine = iterator1.next();
                    if(!jsonNode.get("classCode").textValue().equals(infoDefine.getClassCode())){
                        continue;
                    }
                    if (jsonNode.get("id") != null && "id".equals(infoDefine.getCode())) {
                        staticInfoPoint++;
                        iterator1.remove();
                        continue;
                    }
                    if (jsonNode.get("name") != null && "name".equals(infoDefine.getCode())) {
                        staticInfoPoint++;
                        iterator1.remove();
                        continue;
                    }
                    if (jsonNode.get("localId") != null && "localId".equals(infoDefine.getCode())) {
                        staticInfoPoint++;
                        iterator1.remove();
                        continue;
                    }
                    if (jsonNode.get("localName") != null && "localName".equals(infoDefine.getCode())) {
                        staticInfoPoint++;
                        iterator1.remove();
                        continue;
                    }
                    if (jsonNode.get("qrCode") != null && "qRCode".equals(infoDefine.getCode())) {
                        staticInfoPoint++;
                        iterator1.remove();
                        continue;
                    }
                    if (jsonNode.get("cADID") != null && "cADID".equals(infoDefine.getCode()) && num == 0) {
                        staticInfoPoint++;
                        iterator1.remove();
                    }
                    if (jsonNode.get("bimId") != null && "bimId".equals(infoDefine.getCode()) && num == 0) {
                        staticInfoPoint++;
                        iterator1.remove();
                        continue;
                    }
                    if (jsonNode.get("bimLocation") != null && "bimLocation".equals(infoDefine.getCode())) {
                        staticInfoPoint++;
                        iterator1.remove();
                        continue;
                    }
                    if (jsonNode.get("equipSerial") != null && "equipSerial".equals(infoDefine.getCode())) {
                        staticInfoPoint++;
                        iterator1.remove();
                        continue;
                    }
                    if (jsonNode.get("bimFamilyName") != null && "bimFamilyName".equals(infoDefine.getCode())) {
                        staticInfoPoint++;
                        iterator1.remove();
                        continue;
                    }
                    if (jsonNode.get("bimFamilySymbol") != null && "bimFamilySymbol".equals(infoDefine.getCode())) {
                        staticInfoPoint++;
                        iterator1.remove();
                        continue;
                    }
                }

                ObjectNode infos = (ObjectNode) jsonNode.get("infos");
                if (!JSONUtil.isNull(infos) && !infos.toString().equals("{}")) {
                    Map<String, Object> dynamic = calculateInfoPoints(infos.toString(), jsonNode.get("classCode").textValue(), dynamicInfoPointCodes);
                    Map<String, Object> staticMap = calculateInfoPoints(infos.toString(), jsonNode.get("classCode").textValue(), staticInfoPointCodes);
                    dynamicInfoPoint += Integer.parseInt(dynamic.get("counts").toString());
                    staticInfoPoint += Integer.parseInt(staticMap.get("counts").toString());
                    dynamicInfoPointCodes.remove(dynamic.get("next"));
                    staticInfoPointCodes.remove(staticMap.get("next"));
                }
            }
        }
        hashMap.put("dynamicInfoPoint", dynamicInfoPoint);
        hashMap.put("staticInfoPoint", staticInfoPoint);
        hashMap.put("customInfoPoint", customInfoPoint);
    }


    /**
     * 计算信息点
     * @param infos
     * @param classCode
     * @param infoPointCodes
     * @return
     */
    private Map<String,Object> calculateInfoPoints(String infos, String classCode, List<ObjectInfoDefine> infoPointCodes) {
        int counts = 0;
        Map<String,Object> hashMap = new HashMap<String,Object>();
        if(!infos.equals("{}")){
            Iterator<ObjectInfoDefine> iterator = infoPointCodes.iterator();
            while (iterator.hasNext()){
                ObjectInfoDefine nextInfo = iterator.next();
                if(infos.contains(nextInfo.getCode()) && classCode.equals(nextInfo.getClassCode())){
                    counts ++;
                    hashMap.put("next", nextInfo);
                    iterator.remove();
                }
            }
        }
        hashMap.put("counts", counts);
        return hashMap;
    }

    /**
     * 根据对象分类查询信息的总数
     * @param objtype
     * @return
     */
    private Integer controlInfoCounts(String objtype, Boolean common){
        AdmQueryCriteria admQueryCriteria = new AdmQueryCriteria();
        admQueryCriteria.setOnlyCount(true);
        if(common){
            admQueryCriteria.setFilters(" projectId = '0' and groupCode = '0' ");
        }
        AdmResponse response = dictService.doQueryObjectInfo(AdmContextUtil.toDmpContext(), admQueryCriteria, objtype, AdmObjectInfo.class);
        return response.getTotal().intValue();
    }

    /** 项目下所有已采集的动态信息点编码
     * common flase 全部  true 通用
     */
    private List<ObjectInfoDefine> gatherDynamicInfoCode(Boolean visible, Set<String> classCodeSet, Boolean common){
        //获取信息点
        AdmQueryCriteria admQueryCriteria = new AdmQueryCriteria();
        //静态信息点
        String filters = " category != 'STATIC'";
        if(visible){
            filters = filters + " and valid = '1' ";
        }
        if(common){
            filters = filters +" and projectId = '0' and groupCode = '0' ";
        }
        filters = filters +" and classCode in ['"+StrUtil.join("','",classCodeSet)+"']";
        admQueryCriteria.setFilters(filters);
        QueryCriteria queryCriteria = AdmQueryCriteriaHelper.toDmpCriteria(admQueryCriteria);
        queryCriteria.setOnlyCount(false);
        List<ObjectInfoDefine> staticInfoCode = DigitalObjectInfoFacade.query(AdmContextUtil.toDmpContext().getGroupCode(), AdmContextUtil.toDmpContext().getProjectId(), AdmCommonConstant.APP_ID,null,queryCriteria);
        return staticInfoCode;
    }

    /** 项目下所有已采集静态信息点编码
     * common flase 全部  true 通用
     */
    private List<ObjectInfoDefine> gatherStaticInfoCode(Boolean visible, Set<String> classCodeSet, Boolean common){
        //获取信息点
        QueryCriteria queryCriteria = new QueryCriteria();
        ObjectNode criteria = JsonNodeFactory.instance.objectNode();
        ArrayNode arrayNode = criteria.putObject("classCode").putArray("$in");
        classCodeSet.stream().forEach(classCode -> arrayNode.add(classCode));
        //静态信息点
        criteria.put("category","STATIC");
        if(visible){
            criteria.put("valid", "1");
        }else{
            criteria.remove("valid");
        }
        if(common){
            criteria.put("projectId", "0");
            criteria.put("groupCode", "0");
        }
        queryCriteria.setOnlyCount(false);
        queryCriteria.setCriteria(criteria);
        List<ObjectInfoDefine> staticInfoCode = DigitalObjectInfoFacade.query(AdmContextUtil.toDmpContext().getGroupCode(), AdmContextUtil.toDmpContext().getProjectId(), AdmCommonConstant.APP_ID,null,queryCriteria);
        return staticInfoCode;
    }


    /**
     * 处理设备属性文件 -> 设备的信息点
     * @param equip
     * @param attribute
     */
    private void dealTaskFiles(AdmEquipment equip, String attribute, List<AdmTaskPic> upTarget){
        Map<String, Object> infos =  equip.getInfos();
        boolean containsKey1 = infos.containsKey(attribute);
        if (containsKey1) {
            if (infos.get(attribute) != null && StrUtil.isNotEmpty(infos.get(attribute).toString())){
                List<AdmTaskPic> list = JSONUtil.toList(infos.get(attribute).toString(), AdmTaskPic.class);
                list.addAll(upTarget);
                infos.put(attribute, list);
            }else {
                infos.put(attribute, upTarget);
            }
        } else {
            infos.put(attribute, upTarget);
        }
    }
}
