package com.persagy.proxy.adm.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.persagy.dmp.basic.model.QueryCriteria;
import com.persagy.dmp.basic.utils.JsonNodeUtils;
import com.persagy.dmp.common.context.AppContext;
import com.persagy.dmp.digital.client.DigitalRelationFacade;
import com.persagy.dmp.digital.entity.ObjectRelation;
import com.persagy.proxy.adm.service.IAdmRelationService;
import com.persagy.proxy.common.client.DmpRwdClient;
import com.persagy.proxy.common.entity.InstanceUrlParam;
import com.persagy.proxy.common.entity.RelationDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * ADM 关系 通用 Service
 * @author Charlie Yu
 * @date 2021-08-16
 */
@Slf4j
@Service
public class AdmRelationServiceImpl implements IAdmRelationService {

    @Autowired
    private DmpRwdClient rwdClient;
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void doSave(InstanceUrlParam param, List<RelationDTO> voList) {
        if(CollUtil.isEmpty(voList)) {
            return;
        }
        List<ObjectNode> nodeList = JsonNodeUtils.toListNode(voList, null, null);
        DigitalRelationFacade.create(param.getGroupCode(), param.getProjectId(),
                param.getAppId(), null, nodeList);
    }

    @Override
    public void doDelete(InstanceUrlParam param, QueryCriteria criteria) {
    	param.setGroupCode(AppContext.getContext().getGroupCode());
    	param.setProjectId(AppContext.getContext().getProjectId());
    	
        if(criteria == null) {
            return;
        }
        JSONObject cond = null;
        try {
            String json = objectMapper.writeValueAsString(criteria);
            cond = JSONObject.parseObject(json);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(), e);
        }
        if(cond == null) {
            return;
        }
        rwdClient.deleteRelation(param, cond);
    }

    @Override
    public List<ObjectRelation> queryByCondition(InstanceUrlParam param, QueryCriteria criteria) {
        if(criteria == null) {
            return null;
        }
        return DigitalRelationFacade.query(param.getGroupCode(), param.getProjectId(),
                param.getAppId(), null, criteria);
    }
}
