package com.persagy.proxy.relation.controller;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.persagy.dmp.basic.model.QueryCriteria;
import com.persagy.dmp.common.context.AppContext;
import com.persagy.proxy.adm.constant.AdmRelationTypeEnum;
import com.persagy.proxy.object.model.AdmSpace;
import com.persagy.proxy.relation.model.UpDataFloorAndBuilding;
import com.persagy.proxy.adm.request.AdmQueryCriteria;
import com.persagy.proxy.adm.request.AdmResponse;
import com.persagy.proxy.adm.service.IAdmRelationService;
import com.persagy.proxy.object.service.IAdmSpaceService;
import com.persagy.proxy.adm.utils.AdmContextUtil;
import com.persagy.proxy.common.entity.InstanceUrlParam;
import com.persagy.proxy.common.entity.RelationDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 关系-修改对象的建筑楼层信息
 *
 * @author zhangwencheng
 */

@RestController
@RequestMapping("/update-relationship")
public class RelationFlAndBuController {

    @Autowired
    private IAdmRelationService service;

    @Autowired
    private IAdmSpaceService spaceService;

    /**
     * 修改空间和楼层建筑的关系
     * spaceId 业务空间id,id 楼层或建筑id,type  业务空间的类型
     * 
     * @param upDataFloorAndBuildings
     * @return
     */
    @PostMapping("/update-sp")
    public AdmResponse spFloorAndBuilding(@RequestBody List<UpDataFloorAndBuilding> upDataFloorAndBuildings) {
        if (CollectionUtils.isEmpty(upDataFloorAndBuildings)) {
            return AdmResponse.failure("不可以传入空数据");
        }
        
        AdmRelationTypeEnum bd2sp = AdmRelationTypeEnum.BD2SP;
        AdmRelationTypeEnum fl2sp = AdmRelationTypeEnum.FL2SP;
        List<RelationDTO> voList = new ArrayList<>();
        List<String> idList = new ArrayList<>();
        InstanceUrlParam context = AdmContextUtil.toDmpContext();
        for (UpDataFloorAndBuilding upDataFloorAndBuilding : upDataFloorAndBuildings) {
            String id = upDataFloorAndBuilding.getId();
            String spaceId = upDataFloorAndBuilding.getSpaceId();
            idList.add(spaceId);
            if (StrUtil.isBlank(id)) {
            	deleteByObjId(null, spaceId, null, bd2sp, context);
                deleteByObjId(null, spaceId, null, fl2sp, context);
			} else {
				if (id.startsWith("Bd")) {
	                deleteByObjId(null, spaceId, null, bd2sp, context);
	                RelationDTO relation = new RelationDTO(null, bd2sp.getGraphCode(), bd2sp.getRelCode(), null, id, spaceId);
	                voList.add(relation);
	            } else if (id.startsWith("Fl")) {
	                deleteByObjId(null, spaceId, null, fl2sp, context);
	                RelationDTO relation = new RelationDTO(null, fl2sp.getGraphCode(), fl2sp.getRelCode(), null, id, spaceId);
	                voList.add(relation);
	            }
			}
        }
        if (!CollectionUtils.isEmpty(voList)) {
            service.doSave(context, voList);
        }
        
        String filter = " id in ('" + StrUtil.join("','", idList) + "') ";
        AdmQueryCriteria criteria = new AdmQueryCriteria();
        criteria.setFilters(filter);
        AdmResponse rs = spaceService.query(criteria);
        List<AdmSpace> spaces = (List<AdmSpace>) rs.getContent();
        Map<String, AdmSpace> admSpaceMap = spaces.stream().collect(Collectors.toMap(AdmSpace::getId, Function.identity()));
        List<AdmSpace> updateSpace = new ArrayList<>();
        for (UpDataFloorAndBuilding upDataFloorAndBuilding : upDataFloorAndBuildings) {
            String spaceId = upDataFloorAndBuilding.getSpaceId();
            AdmSpace admSpace = admSpaceMap.get(spaceId);
            if (Objects.isNull(admSpace)) {
                continue;
            }
            String id = upDataFloorAndBuilding.getId();
            if (StrUtil.isNotBlank(id)) {
            	if (id.startsWith("Bd")) {
                    admSpace.setBuildingId(id);
                    updateSpace.add(admSpace);
                } else if (id.startsWith("Fl")) {
                    admSpace.setFloorId(id);
                    updateSpace.add(admSpace);
                }
			}
        }
        //更新空间
        if (!CollectionUtils.isEmpty(updateSpace)) {
            spaceService.doUpdate(context, AdmSpace.class, updateSpace);
        }

        return AdmResponse.success();
    }

    /**
     * 删除对象关系
     *
     * @param objFrom
     * @param objTo
     * @param type
     * @param typeEnum
     * @param context
     */
    private void deleteByObjId(String objFrom, String objTo, String type, AdmRelationTypeEnum typeEnum, InstanceUrlParam context) {
        QueryCriteria criteria = new QueryCriteria();
        ObjectNode node = JsonNodeFactory.instance.objectNode();
        node.put("graphCode", typeEnum.getGraphCode());
        node.put("relCode", typeEnum.getRelCode());
        if (StrUtil.isNotBlank(type)) {
        	node.put("relValue", type);
		}
        if (StrUtil.isNotBlank(objFrom)) {
        	node.put("objFrom", objFrom);
		}
        if (StrUtil.isNotBlank(objTo)) {
        	node.put("objTo", objTo);
		}
        criteria.setCriteria(node);
        service.doDelete(context, criteria);
    }
}
