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.dmp.digital.entity.ObjectRelation;
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.client.DmpRwdClient;
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:028、关系-系统服务于竖井
 * @author:lgy
 * @data:2021/9/26 10:19
 */
@RestController
@RequestMapping("/rel/sy-for-sh")
public class RelationSyForShController {

    @Autowired
    private IAdmRelationService service;
    @Autowired
    DmpRwdClient rwdClient;

    /**
     * 默认图类型
     */
    public static String DEFAULT_GRAPH_CODE = "MechForArch";
    /**
     * 默认边类型
     */
    public static String DEFAULT_REL_CODE = "Sy2Sh";

    /**
     * 创建系统服务于竖井关系
     * @param param
     * @return
     * @throws Exception
     */
    @PostMapping(value = {"/link"})
    public AdmResponse create(@RequestBody JSONObject param) throws Exception {
        String sysId = param.getString("sysId");
        String shaftId = param.getString("shaftId");
        if(!StrUtil.isAllNotEmpty(shaftId,sysId)) {
            return AdmResponse.failure("必填项：SysId（系统id）、ShaftId（竖井id）");
        }
        // 创建关系对象
        List<RelationDTO> voList = new ArrayList<>();
        voList.add(new RelationDTO(null, DEFAULT_GRAPH_CODE, DEFAULT_REL_CODE, null, sysId , shaftId));
        // 组装上下文条件
        InstanceUrlParam context = AdmContextUtil.toDmpContext();
        service.doSave(context, voList);
        return AdmResponse.success();
    }
    /**
     * 根据对象删除系统服务于竖井的关系，只针对一个对象
     * @param    param    对象
     * @return                       删除的结果信息
     */
    @PostMapping("/unlink")
    public AdmResponse delete(@RequestBody JSONObject param) throws Exception {
        if(CollUtil.isEmpty(param)) {
            return AdmResponse.success();
        }
        // 组装上下文条件
        InstanceUrlParam context = AdmContextUtil.toDmpContext();
        // 组装条件
        QueryCriteria criteria = new QueryCriteria();
        String sysId = param.getString("sysId");
        String shaftId = param.getString("shaftId");
        if(!StrUtil.isAllNotEmpty(shaftId,sysId)) {
            return AdmResponse.failure("必填项：SysId（系统id）、ShaftId（竖井id）");
        }
        ObjectNode node = JsonNodeFactory.instance.objectNode();
        node.put("graphCode", DEFAULT_GRAPH_CODE);
        node.put("relCode", DEFAULT_REL_CODE);
        node.put("objFrom", sysId);
        node.put("objTo",shaftId);
        criteria.setCriteria(node);
        service.doDelete(context, criteria);
        return AdmResponse.success();
    }
    /**
     * 创建系统服务于楼层，系统一对多
     * @param   param
     * @return                       创建的结果信息
     */
    @PostMapping("/link-sh")
    public AdmResponse createSh(@RequestBody JSONObject param) {
        String sysId = param.getString("sysId");
        JSONArray shaftIdList = param.getJSONArray("shaftIdList");
        if(StrUtil.isBlank(sysId) || CollUtil.isEmpty(shaftIdList)) {
            return AdmResponse.failure("必填项：ShaftIdList（竖井id列表）、SysId（系统id），测方法会覆盖以前的记录");
        }
        // 创建关系对象.先删除，后添加
        InstanceUrlParam context = AdmContextUtil.toDmpContext();
        QueryCriteria queryRequestTmp = new QueryCriteria();
        ObjectNode nodeTmp = JsonNodeFactory.instance.objectNode();
        nodeTmp.put("graphCode", DEFAULT_GRAPH_CODE);
        nodeTmp.put("relCode", DEFAULT_REL_CODE);
        nodeTmp.put("objFrom", sysId);
        queryRequestTmp.setCriteria(nodeTmp);
        //关系之前的关系，并且删除
        List<ObjectRelation> objectRelations = service.queryByCondition(context, queryRequestTmp);
        for (ObjectRelation objectRelation : objectRelations) {
            QueryCriteria queryRequest = new QueryCriteria();
            ObjectNode node = JsonNodeFactory.instance.objectNode();
            node.put("graphCode", objectRelation.getGraphCode());
            node.put("relCode", objectRelation.getRelCode());
            node.put("relValue", objectRelation.getRelValue());
            node.put("objFrom", objectRelation.getObjFrom());
            node.put("objTo", objectRelation.getObjTo());
            queryRequest.setCriteria(node);
            service.doDelete(context, queryRequest);
        }
        List<RelationDTO> voList = new ArrayList<>();
        for(int i = 0;i < shaftIdList.size();i++) {
            String shaftId = shaftIdList.getString(i);
            if(StrUtil.isBlank(shaftId)) {
                continue;
            }
            voList.add(new RelationDTO(null, DEFAULT_GRAPH_CODE, DEFAULT_REL_CODE, null, sysId, shaftId));
        }
        // 组装上下文条件
        service.doSave(context, voList);
        return AdmResponse.success();
    }
    /**
     * 服务于竖井的系统，竖井一对多
     * @param   param
     * @return                       创建的结果信息
     */
    @PostMapping("/link-sy")
    public AdmResponse createSy(@RequestBody JSONObject param) throws Exception {
        String shaftId = param.getString("shaftId");
        JSONArray sysIdList = param.getJSONArray("sysIdList");
        if (StrUtil.isBlank(shaftId) || CollUtil.isEmpty(sysIdList)) {
            return AdmResponse.failure("必填项：ShaftId（竖井id）、sysIdList（系统id列表），测方法会覆盖以前的记录");
        }
        // 创建关系对象.先删除，后添加
        InstanceUrlParam context = AdmContextUtil.toDmpContext();
        QueryCriteria queryRequestTmp = new QueryCriteria();
        ObjectNode nodeTmp = JsonNodeFactory.instance.objectNode();
        nodeTmp.put("graphCode", DEFAULT_GRAPH_CODE);
        nodeTmp.put("relCode", DEFAULT_REL_CODE);
        nodeTmp.put("objTo", shaftId);
        queryRequestTmp.setCriteria(nodeTmp);
        //关系之前的关系，并且删除
        List<ObjectRelation> objectRelations = service.queryByCondition(context, queryRequestTmp);
        for (ObjectRelation objectRelation : objectRelations) {
            QueryCriteria queryRequest = new QueryCriteria();
            ObjectNode node = JsonNodeFactory.instance.objectNode();
            node.put("graphCode", objectRelation.getGraphCode());
            node.put("relCode", objectRelation.getRelCode());
            node.put("relValue", objectRelation.getRelValue());
            node.put("objFrom", objectRelation.getObjFrom());
            node.put("objTo", objectRelation.getObjTo());
            queryRequest.setCriteria(node);
            service.doDelete(context, queryRequest);
        }
        List<RelationDTO> voList = new ArrayList<>();
        for (int i = 0; i < sysIdList.size(); i++) {
            String sysId = sysIdList.getString(i);
            if (StrUtil.isBlank(sysId)) {
                continue;
            }
            voList.add(new RelationDTO(null, DEFAULT_GRAPH_CODE, DEFAULT_REL_CODE, null, sysId, shaftId));
        }
        // 组装上下文条件
        service.doSave(context, voList);
        return AdmResponse.success();
    }
}
