package com.persagy.proxy.relation.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.persagy.dmp.basic.model.QueryCriteria;
import com.persagy.dmp.basic.utils.QueryCriteriaHelper;
import com.persagy.dmp.common.helper.SpringHelper;
import com.persagy.dmp.digital.entity.ObjectRelation;
import com.persagy.proxy.adm.constant.AdmRelationTypeEnum;
import com.persagy.proxy.relation.model.ShInBdList;
import com.persagy.proxy.adm.request.AdmResponse;
import com.persagy.proxy.adm.service.IAdmRelationService;
import com.persagy.proxy.adm.utils.AdmContextUtil;
import com.persagy.proxy.common.entity.RelationDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * 关系-竖井所在建筑
 * @author zhangwencheng
 */
@Slf4j
@RestController
@RequestMapping("/rel/sh-in-bd")
public class RelationShInBdController {

    @Autowired
    private IAdmRelationService service;

    /**
     * 创建竖井所在建筑关系
     * @param shInBdList
     * @return
     */
    @PostMapping("link-bd")
    public AdmResponse createBd(@RequestBody ShInBdList shInBdList) throws IOException {
        log.info("创建系统所在建筑关系link-bd");
        List<String> buildingIdList = shInBdList.getBuildingIdList();
        String shaftId = shInBdList.getShaftId();
        // 1.检验输入参数
        if(CollectionUtils.isEmpty(buildingIdList)|| StringUtils.isEmpty(shaftId)){
            return AdmResponse.failure("必填项：shaftId（竖井id）、BuildingIdList（建筑id列表）");
        }
        List<RelationDTO> voList = new ArrayList<>();
        String graphCode = AdmRelationTypeEnum.BD2SH_ARCHSUBSET.getGraphCode();
        String relCode = AdmRelationTypeEnum.BD2SH_ARCHSUBSET.getRelCode();
        // 2.根据图类型,边类型,建筑id数组,竖井id数组查询关系
        QueryCriteria criteria = new QueryCriteria();
        ObjectMapper objectMapper = SpringHelper.getBean(ObjectMapper.class);
        ObjectNode queryObj = objectMapper.createObjectNode();
        //queryObj.set("objFrom",objectMapper.readTree(objectMapper.writeValueAsString(buildingIdList)));
        queryObj.put("objTo",shaftId);
        queryObj.put("graphCode",graphCode);
        queryObj.put("relCode",relCode);
        queryObj.put("valid",Boolean.TRUE);
        criteria.setCriteria(queryObj);
        List<ObjectRelation> relations = service.queryByCondition(AdmContextUtil.toDmpContext(), criteria);
        Set<String> havedBuildIds = CollUtil.newHashSet(CollUtil.isNotEmpty(relations),
                relations.stream().map(ObjectRelation::getObjFrom).collect(Collectors.toSet()));
        // 3.新增新的关系
        for (String buildingId : buildingIdList) {
            if (havedBuildIds.contains(buildingId)){
                continue;
            }
            RelationDTO relation = RelationDTO.builder().graphCode(graphCode).relCode(relCode)
                    .objFrom(buildingId).objTo(shaftId).build();
            voList.add(relation);
        }
        service.doSave(AdmContextUtil.toDmpContext(), voList);
        // 4.删除旧的关系
        Set<String> deleteRelationIds = new HashSet<>();
        if (CollUtil.isNotEmpty(relations)){
            Map<String, List<ObjectRelation>> buildMap = relations.stream()
                    .collect(Collectors.groupingBy(ObjectRelation::getObjFrom));
            Set<Map.Entry<String, List<ObjectRelation>>> entries = buildMap.entrySet();
            for (Map.Entry<String, List<ObjectRelation>> entry : entries) {
                if (buildingIdList.contains(entry.getKey())
                        || CollUtil.isEmpty(entry.getValue())){
                    continue;
                }
                // 需删除的关系
                deleteRelationIds
                        .addAll(entry.getValue().stream().map(ObjectRelation::getId).collect(Collectors.toSet()));
            }
        }
        if (CollUtil.isNotEmpty(deleteRelationIds)){
            QueryCriteria deleteParam = new QueryCriteria();
            ObjectNode deleteObj = objectMapper.createObjectNode();
            deleteObj.set("id",objectMapper.readTree(objectMapper.writeValueAsString(deleteRelationIds)));
            deleteParam.setCriteria(deleteObj);
            service.doDelete(AdmContextUtil.toDmpContext(),deleteParam);
        }
        return AdmResponse.success();
    }

}
