package com.persagy.proxy.relation.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.persagy.dmp.basic.model.QueryCriteria;
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.InstanceUrlParam;
import com.persagy.proxy.common.entity.RelationDTO;
import org.springframework.beans.factory.annotation.Autowired;
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.util.ArrayList;
import java.util.List;

/**
 * @description: 021关系-楼层的贯通
 * @author:lgy
 * @data:2021/9/13 11:02
 */
@RestController
@RequestMapping("/rel/fl-through-fl")
public class RelationFlThroughFlController {

    private static final String GRAPH_CODE = "ThroughRelationship";
    private static final String REL_CODE = "Fl2Fl";

    @Autowired
    private IAdmRelationService service;
    /**
     * 创建楼层的贯通关系
     * @param param
     * @return
     * @throws Exception
     */
    @PostMapping(value = {"/link"})
    public AdmResponse create(@RequestBody JSONObject param) throws Exception {
        String floorId = param.getString("floorId");
        String floorOtherId = param.getString("floorOtherId");
        if(!StrUtil.isAllNotEmpty(floorId,floorOtherId)) {
            return AdmResponse.failure("必填项：FloorId（楼层id）、FloorOtherId（其他楼层id）");
        }
        // 创建关系对象
        List<RelationDTO> voList = new ArrayList<>();
        RelationDTO relation = RelationDTO.builder().graphCode(GRAPH_CODE)
                .relCode(REL_CODE).objFrom(floorId).objTo(floorOtherId).build();
        voList.add(relation);
        service.doSave(AdmContextUtil.toDmpContext(), voList);
        return AdmResponse.success();
    }
    /**
     * 根据对象删除关系
     * 根据对象删除楼层的贯通关系，只针对一个对象
     * @param   param      对象
     * @return             删除的结果信息
     */
    @PostMapping("/unlink")
    public AdmResponse delete(@RequestBody JSONObject param) throws Exception {
        if(CollUtil.isEmpty(param)) {
            return AdmResponse.failure("必填项：FloorId（楼层id）、FloorOtherId(其他楼层id)");
        }
        String floorId = param.getString("floorId");
        String floorOtherId = param.getString("floorOtherId");
        if(!StrUtil.isAllNotEmpty(floorId,floorOtherId)) {
            return AdmResponse.failure("必填项：FloorId（楼层id）、FloorOtherId(其他楼层id)");
        }
        deleteById(AdmContextUtil.toDmpContext(), floorId, floorOtherId);
        return AdmResponse.success();
    }

    /**
     * 通过楼层Id删除
     * @param context
     * @param fromId
     * @param toId
     */
    private void deleteById(InstanceUrlParam context, String fromId, String toId) {
        // 都为空不处理
        if(StrUtil.isAllBlank(fromId, toId)) {
            return;
        }
        // 关系条件
        ObjectNode node = JsonNodeFactory.instance.objectNode();
        node.put("graphCode", GRAPH_CODE);
        node.put("relCode", REL_CODE);
        if(StrUtil.isNotBlank(fromId)) {
            node.put("objFrom", fromId);
        }
        if(StrUtil.isNotBlank(toId)) {
            node.put("objTo",toId);
        }
        // 执行删除
        QueryCriteria criteria = new QueryCriteria();
        criteria.setCriteria(node);
        service.doDelete(context, criteria);
    }

    /**
     * 创建楼层的贯通关系
     * 楼层的贯通，楼层一对多
     * @param param 楼层和其他楼层列表关系对象r
     * @return
     * @throws Exception
     */
    @PostMapping("/link-or")
    public AdmResponse createFloorOtherIdList(@RequestBody JSONObject param) {
        String floorId = param.getString("floorId");
        JSONArray floorOtherIdList = param.getJSONArray("floorOtherIdList");
        if(StrUtil.isBlank(floorId)) {
            return AdmResponse.failure("必填项：FloorId（楼层id）,此方法会覆盖以前的记录");
        }
        InstanceUrlParam context = AdmContextUtil.toDmpContext();
        // 先删除floorId的所有关系
        deleteById(context, floorId, null);
        deleteById(context, null, floorId);
        // 如果没有待添加的，返回
        if(CollUtil.isEmpty(floorOtherIdList)) {
            return AdmResponse.success();
        }
        // 创建关系对象.先删除，后添加
        List<RelationDTO> voList = new ArrayList<>();
        for(int i = 0;i < floorOtherIdList.size();i++) {
            String floorOtherId = floorOtherIdList.getString(i);
            if(StrUtil.isBlank(floorOtherId)) {
                continue;
            }
            // 创建关系对象
            RelationDTO relation = RelationDTO.builder().graphCode(GRAPH_CODE)
                    .relCode(REL_CODE).objFrom(floorId).objTo(floorOtherId).build();
            voList.add(relation);
        }
        // 组装上下文条件
        service.doSave(context, voList);
        return AdmResponse.success();
    }

    /**
     * 楼层的贯通，其他楼层一对多
     * @param param 楼层和其他楼层列表关系对象r
     * @return
     * @throws Exception
     */
    @PostMapping("/link-fl")
    public AdmResponse createFloorIdList(@RequestBody JSONObject param) {
        String floorOtherId = param.getString("floorOtherId");
        JSONArray floorIdList = param.getJSONArray("floorIdList");
        if(StrUtil.isBlank(floorOtherId)) {
            return AdmResponse.failure("必填项：FloorOtherId（其他楼层id），测方法会覆盖以前的记录");
        }
        InstanceUrlParam context = AdmContextUtil.toDmpContext();
        // 先删除floorOtherId的所有关系
        deleteById(context, floorOtherId, null);
        deleteById(context, null, floorOtherId);
        // 如果没有待添加的，返回
        if(CollUtil.isEmpty(floorIdList)) {
            return AdmResponse.success();
        }
        // 创建关系对象.先删除，后添加
        List<RelationDTO> voList = new ArrayList<>();
        for(int i = 0;i < floorIdList.size();i++) {
            String floorId = floorIdList.getString(i);
            if(StrUtil.isBlank(floorId)) {
                continue;
            }
            // 创建关系对象
            RelationDTO relation = RelationDTO.builder().graphCode(GRAPH_CODE)
                    .relCode(REL_CODE).objFrom(floorId).objTo(floorOtherId).build();
            voList.add(relation);
        }
        // 组装上下文条件
        service.doSave(context, voList);
        return AdmResponse.success();
    }

}
