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.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:设备服务于业务空间
 * 018、关系-设备服务于业务空间
 * @author:lgy
 * @data:2021/9/1 10:23
 */
@RestController
@RequestMapping("/rel/eq-for-sp-base")
public class RelationEqForSpConreoller {

    @Autowired
    private IAdmRelationService service;

    /**
     * create 创建设备服务于业务空间关系
     * @param projectId projectId
     * @param type type
     * @param param param
     * @return {@link com.persagy.proxy.adm.request.AdmResponse}
     * @author lgy
     * @date 2021/9/1 10:28
     */
    @PostMapping("/link-list")
    public AdmResponse create(@RequestParam(value = "type", required = false) String type,
                              @RequestBody JSONObject param) throws Exception {

        JSONArray content = param == null ? null : param.getJSONArray("content");
        if(CollUtil.isEmpty(content)) {
            return AdmResponse.success();
        }
        // 创建关系对象
        List<RelationDTO> voList = new ArrayList<>();
        for(int i = 0;i < content.size();i++) {
            JSONObject para = content.getJSONObject(i);
            String equipId = para.getString("equipId");
            String spaceId = para.getString("spaceId");
            if(StrUtil.isBlank(equipId) || StrUtil.isBlank(spaceId)) {
                return AdmResponse.failure("必填项：EquipId（设备id）、SpaceId（业务空间id）");
            }
            // 创建关系对象 - 参考(datasyn中DataCenterSync.kt)
            voList.add(new RelationDTO(null, "MechForArch", "Eq2Sp", type, equipId, spaceId));
        }
        service.doSave(AdmContextUtil.toDmpContext(), voList);
        return AdmResponse.success();
    }


    /**
     * 创建服务于业务空间的设备关系
     * 服务于业务空间的设备，业务空间一对多,累计添加不会覆盖以前记(必填项：EquipIdList（设备id列表）、SpaceId（业务空间id))
     * @param type
     * @param param
     * @return
     * @throws Exception
     */
    @PostMapping("/link-eq-sp")
    public AdmResponse createEq(@RequestParam(value = "type", required = false) String type,
                                @RequestBody JSONObject param) throws Exception {
        String spaceId = param.getString("spaceId");
        JSONArray equipIdList = param.getJSONArray("equipIdList");
        if(StrUtil.isBlank(spaceId) || CollUtil.isEmpty(equipIdList)) {
            return AdmResponse.failure("必填项：EquipId（设备id）、SpaceId（业务空间id）");
        }
        // 创建关系对象
        List<RelationDTO> voList = new ArrayList<>();
        for(int i = 0;i < equipIdList.size();i++) {
            String equipId = equipIdList.getString(i);
            if(StrUtil.isBlank(equipId)) {
                continue;
            }
            // 创建关系对象 - 参考(datasyn中DataCenterSync.kt)
            voList.add(new RelationDTO(null, "MechForArch", "Eq2Sp", type, equipId, spaceId));
        }
        service.doSave(AdmContextUtil.toDmpContext(), voList);
        return AdmResponse.success();
    }

    /**
     * 根据对象删除关系
     * 根据对象删除设备服务于业务空间关系(必填项：EquipId（设备id）、SpaceId（业务空间id）)
     * @param type
     * @param param
     * @return
     * @throws Exception
     */
    @PostMapping("/unlink-list")
    public AdmResponse delete(@RequestParam(value = "type", required = false) String type,
                              @RequestBody JSONArray param) throws Exception {
        if(CollUtil.isEmpty(param)) {
            return AdmResponse.success();
        }
        // 组装上下文条件
        InstanceUrlParam context = AdmContextUtil.toDmpContext();
        // 组装条件
        QueryCriteria criteria = new QueryCriteria();
        for(int i = 0;i < param.size();i++) {
            JSONObject para = param.getJSONObject(i);
            String equipId = para.getString("equipId");
            String spaceId = para.getString("spaceId");
            if(StrUtil.isBlank(equipId) || StrUtil.isBlank(spaceId)) {
                return AdmResponse.failure("必填项：EquipId（设备id）、SpaceId（业务空间id）");
            }
            ObjectNode node = JsonNodeFactory.instance.objectNode();
            node.put("graphCode", "MechForArch");
            node.put("relCode", "Eq2Sp");
            node.put("relValue", type);
            node.put("objFrom", equipId);
            node.put("objTo", spaceId);
            criteria.setCriteria(node);
            service.doDelete(context, criteria);
        }
        return AdmResponse.success();
    }
}
