package com.persagy.proxy.relation.controller;

import cn.hutool.core.util.StrUtil;
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.common.constant.CommonConstant;
import com.persagy.proxy.adm.constant.AdmRelationTypeEnum;
import com.persagy.proxy.adm.request.AdmCreateResponse;
import com.persagy.proxy.relation.model.SiInSpBase;
import com.persagy.proxy.relation.model.SiInSpBaseList;
import com.persagy.proxy.adm.request.AdmCreateRequest;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

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


/**
 * @author zhangwencheng
 * 业务空间内的元空间
 */

@Slf4j
@RestController
@RequestMapping("/rel/si-in-sp-base")
public class RelationSpInSiController {

    @Autowired
    private IAdmRelationService service;

    /**
     * 创建业务空间内的元空间关系
     *
     * @param siInSpBaseRequest 元空间内的业务空间关系对象
     * @return 创建的结果信息
     */
    @PostMapping("/link-list")
    public AdmResponse create(@RequestParam(value = "type",required = false) String type,
                              @RequestBody AdmCreateRequest<SiInSpBase> siInSpBaseRequest) {
        List<SiInSpBase> content = siInSpBaseRequest.getContent();
        if (CollectionUtils.isEmpty(content)) {
            return AdmResponse.failure("content不能为空");
        }
        List<RelationDTO> voList = new ArrayList<>();
        AdmRelationTypeEnum typeEnum = AdmRelationTypeEnum.SP2SI;
        String graphCode = typeEnum.getGraphCode();
        String relCode = typeEnum.getRelCode();
        for (SiInSpBase siInSpBase : content) {
            String ispaceId = siInSpBase.getIspaceId();
            String spaceId = siInSpBase.getSpaceId();
            if (StrUtil.isBlank(type)){
                type = siInSpBase.getClassCode();
            }
            if (StrUtil.isEmpty(spaceId) || StrUtil.isBlank(ispaceId)) {
                return AdmResponse.failure("必填项：ispaceId（元空间id）、spaceId（空间id）");
            }
            RelationDTO relation = new RelationDTO(StrUtil.format(CommonConstant.DEFAULT_GRAPH_ID_FORMAT,graphCode),
                    graphCode, relCode, type, spaceId, ispaceId);
            voList.add(relation);
        }
        service.doSave(AdmContextUtil.toDmpContext(), voList);
        return AdmResponse.success();
    }

    /**
     * 创建业务空间内的元空间关系-此方法会覆盖以前的记录
     *
     * @param siInSpBaseList 业务空间和元空间的关系对象
     * @return 创建的结果信息
     */
    @PostMapping("/link-sp")
    public AdmCreateResponse createSp(@RequestParam(value = "type", required = false) String type,
                                      @RequestBody SiInSpBaseList siInSpBaseList) {
        List<String> ispaceIdList = siInSpBaseList.getIspaceIdList();
        String spaceId = siInSpBaseList.getSpaceId();
        if (StrUtil.isEmpty(spaceId) || CollectionUtils.isEmpty(ispaceIdList)) {
           // return AdmResponse.failure("必填项：ispaceIdList（元空间id）、spaceId（空间id）");
            return AdmCreateResponse.success();
        }
        InstanceUrlParam context = AdmContextUtil.toDmpContext();
        AdmRelationTypeEnum typeEnum = AdmRelationTypeEnum.SP2SI;
        String graphCode = typeEnum.getGraphCode();
        String relCode = typeEnum.getRelCode();
        deleteBySpaceId(spaceId, context, typeEnum, type);
        List<RelationDTO> voList = new ArrayList<>();
        for (String ispaceId : ispaceIdList) {
            RelationDTO relation = new RelationDTO(null, graphCode, relCode, type, spaceId, ispaceId);
            voList.add(relation);
        }
        service.doSave(context, voList);
        return AdmCreateResponse.success(voList);
    }

    /**
     * 删除信息
     *
     * @param spaceId
     * @param context
     * @param typeEnum
     */
    private void deleteBySpaceId(String spaceId, InstanceUrlParam context, AdmRelationTypeEnum typeEnum, String zoneType) {
        QueryCriteria criteria = new QueryCriteria();
        ObjectNode node = JsonNodeFactory.instance.objectNode();
        node.put("graphCode", typeEnum.getGraphCode());
        node.put("relCode", typeEnum.getRelCode());
        node.put("objFrom", spaceId);
        node.put("relValue", zoneType);
        criteria.setCriteria(node);
        service.doDelete(context, criteria);
    }


    /**
     * 业务空间内的元空间，业务空间一对多,累计添加不会覆盖以前记录
     *
     * @param       siInSpBaseList  业务空间和元空间的关系对象
     * @return                  创建的结果信息
     */
    @PostMapping("/link-si-sp")
    public AdmResponse createSpSi(@RequestParam(value = "type",required = false) String type,
                                  @RequestBody SiInSpBaseList siInSpBaseList){
        List<String> ispaceIdList = siInSpBaseList.getIspaceIdList();
        String spaceId = siInSpBaseList.getSpaceId();
        if (StrUtil.isEmpty(spaceId) || CollectionUtils.isEmpty(ispaceIdList)) {
            return AdmResponse.failure("必填项：ispaceIdList（元空间id）、spaceId（空间id）");
        }
        InstanceUrlParam context = AdmContextUtil.toDmpContext();
        AdmRelationTypeEnum typeEnum = AdmRelationTypeEnum.SP2SI;
        String graphCode = typeEnum.getGraphCode();
        String relCode = typeEnum.getRelCode();
        List<RelationDTO> voList = new ArrayList<>();
        for (String ispaceId : ispaceIdList) {
            RelationDTO relation = new RelationDTO(null, graphCode, relCode, siInSpBaseList.getZoneType(), spaceId, ispaceId);
            voList.add(relation);
        }
        service.doSave(context, voList);
        return  AdmResponse.success();
    }

    /**
     * 根据对象删除业务空间内的元空间关系
     *
     * @param    siInSpBases    对象
     * @return                  删除的结果信息
     */
    @PostMapping("/unlink")
    public AdmResponse delete(@RequestParam(value = "type",required = false)  String type,
                              @RequestBody List<SiInSpBase> siInSpBases) {
        if(CollectionUtils.isEmpty(siInSpBases)){
            return AdmResponse.failure("必填项：siInSpBases不能为空");
        }
        AdmRelationTypeEnum typeEnum = AdmRelationTypeEnum.SP2SI;
        String graphCode = typeEnum.getGraphCode();
        String relCode = typeEnum.getRelCode();
        List<QueryCriteria> queryCriteriaList = new ArrayList<>();
        for (SiInSpBase siInSpBase : siInSpBases) {
            String spaceId = siInSpBase.getSpaceId();
            String ispaceId = siInSpBase.getIspaceId();
            String objectType = siInSpBase.getObjectType();
            if (StrUtil.isBlank(spaceId) || StrUtil.isEmpty(ispaceId)) {
                return AdmResponse.failure("必填项：ispaceId（元空间）、spaceId（空间id）");
            }
            QueryCriteria criteria = new QueryCriteria();
            ObjectNode node = JsonNodeFactory.instance.objectNode();
            node.put("graphCode", graphCode);
            node.put("relCode", relCode);
            node.put("relValue", objectType);
            node.put("objFrom", spaceId);
            node.put("objTo", ispaceId);
            criteria.setCriteria(node);
            queryCriteriaList.add(criteria);
        }
        InstanceUrlParam context = AdmContextUtil.toDmpContext();
        for (QueryCriteria queryCriteria : queryCriteriaList) {
            service.doDelete(context, queryCriteria);
        }
        return  AdmResponse.success();
    }
}
