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.proxy.adm.constant.AdmRelationTypeEnum;
import com.persagy.proxy.relation.model.TnInSpBase;
import com.persagy.proxy.relation.model.TnInSpBaseList;
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/tn-in-sp-base")
public class RelationTnInSpController {

    @Autowired
    private IAdmRelationService service;

    /**
     * 创建租户所租用的业务空间关系
     *
     * @param tnInSpBase 租户和业务空间的关系对象
     * @return 创建的结果信息
     */
    @PostMapping("/link")
    public AdmResponse create( @RequestBody AdmCreateRequest<TnInSpBase> tnInSpBase) {
        List<TnInSpBase> content = tnInSpBase.getContent();
        if(CollectionUtils.isEmpty(content)){
            return AdmResponse.failure("content不能为空");
        }
        AdmRelationTypeEnum typeEnum = AdmRelationTypeEnum.TN2SP;
        String graphCode = typeEnum.getGraphCode();
        String relCode = typeEnum.getRelCode();
        List<RelationDTO> voList = new ArrayList<>();
        for (TnInSpBase inSpBase : content) {
            String spaceId = inSpBase.getSpaceId();
            String tenantId = inSpBase.getTenantId();
            String objectType = inSpBase.getObjectType();
            if(StrUtil.isEmpty(spaceId)||StrUtil.isBlank(tenantId)){
                return AdmResponse.failure("必填项：tenantId（租户Id）、spaceIdList（空间id）");
            }
            RelationDTO relation = new RelationDTO(null, graphCode, relCode, objectType, tenantId, spaceId);
            voList.add(relation);
        }
        service.doSave(AdmContextUtil.toDmpContext(), voList);
        return AdmResponse.success();
    }


    @PostMapping("/unlink")
    public AdmResponse delete(@RequestParam(value = "type",required = false) String type,
                              @RequestBody List<TnInSpBase> tnInSpBases) {
        AdmRelationTypeEnum typeEnum = AdmRelationTypeEnum.TN2SP;
        String graphCode = typeEnum.getGraphCode();
        String relCode = typeEnum.getRelCode();
        if(CollectionUtils.isEmpty(tnInSpBases)){
            return AdmResponse.failure("tnInSpBases不能为空");
        }
        List<QueryCriteria> queryCriteriaList = new ArrayList<>();
        for (TnInSpBase tnInSpBase : tnInSpBases) {
            String tenantId = tnInSpBase.getTenantId();
            String spaceId = tnInSpBase.getSpaceId();
            if (StrUtil.isBlank(spaceId) || StrUtil.isEmpty(tenantId)) {
                return AdmResponse.failure("必填项：tenantId（租户Id）、spaceId（空间id）");
            }
            QueryCriteria criteria = new QueryCriteria();
            ObjectNode node = JsonNodeFactory.instance.objectNode();
            node.put("graphCode", graphCode);
            node.put("relCode", relCode);
            node.put("relValue", type);
            node.put("objFrom", tenantId);
            node.put("objTo", spaceId);
            criteria.setCriteria(node);
            queryCriteriaList.add(criteria);
        }
        InstanceUrlParam context = AdmContextUtil.toDmpContext();
        for (QueryCriteria queryCriteria : queryCriteriaList) {
            //问题：如何调用一次接口，如何保证一起成功
            service.doDelete(context, queryCriteria);
        }
        return AdmResponse.success();
    }

    /**
     * 创建租户所租用的业务空间关系
     *
     * @param    tnInSpBaseList    租户和业务空间的关系对象
     * @return                  创建的结果信息
     */
    @PostMapping("/link-sp")
    public AdmResponse createSp(@RequestParam(value = "type",required = false) String type,
                                @RequestBody TnInSpBaseList tnInSpBaseList) {
        List<String> spaceIdList = tnInSpBaseList.getSpaceIdList();
        String tenantId = tnInSpBaseList.getTenantId();
        if(CollectionUtils.isEmpty(spaceIdList)||StrUtil.isBlank(tenantId)){
            return AdmResponse.failure("必填项：tenantId（租户Id）、spaceIdList（空间id）");
        }
        InstanceUrlParam context = AdmContextUtil.toDmpContext();
        AdmRelationTypeEnum typeEnum = AdmRelationTypeEnum.TN2SP;
        String graphCode = typeEnum.getGraphCode();
        String relCode = typeEnum.getRelCode();
        deleteByTenantId(tenantId,typeEnum,context);
        List<RelationDTO> voList = new ArrayList<>();
        for (String spaceId : spaceIdList) {
            RelationDTO relation = new RelationDTO(null, graphCode, relCode, type, tenantId, spaceId);
            voList.add(relation);
        }
        service.doSave(context, voList);
        return AdmResponse.success();
    }

    //根据租户Id删除
    private void deleteByTenantId(String tenantId,AdmRelationTypeEnum typeEnum,InstanceUrlParam context) {
        QueryCriteria criteria = new QueryCriteria();
        ObjectNode node = JsonNodeFactory.instance.objectNode();
        node.put("graphCode", typeEnum.getGraphCode());
        node.put("relCode", typeEnum.getRelCode());
//        node.put("relValue", type);
        node.put("objFrom", tenantId);
//        node.put("objTo", spaceId);
        criteria.setCriteria(node);
        service.doDelete(context, criteria);
    }
}
