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;

/**
 * ADM 关系 EqInSp API
 * @author Charlie Yu
 * @date 2021-08-16
 */
@RestController
@RequestMapping("/rel/eq-in-sp-base")
public class RelationEqInSpController {

    @Autowired
    private IAdmRelationService service;

    /**
     * 创建设备所在业务空间关系
     * @param type
     * @param param
     * @return
     * @throws Exception
     */
    @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, "MechInArch", "Eq2Sp", type, equipId, spaceId));
        }
        service.doSave(AdmContextUtil.toDmpContext(), voList);
        return AdmResponse.success();
    }

    /**
     * 创建设备所在业务空间关系
     * @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, "MechInArch", "Eq2Sp", type, equipId, spaceId));
        }
        service.doSave(AdmContextUtil.toDmpContext(), voList);
        return AdmResponse.success();
    }

    /**
     * 根据对象删除设备所在业务空间关系
     * @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", "MechInArch");
            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();
    }
}
