package com.persagy.proxy.relation.controller;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
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.constant.AdmRelationTypeEnum;
import com.persagy.proxy.relation.model.SpInSyBaseList;
import com.persagy.proxy.relation.model.SyInSpBase;
import com.persagy.proxy.relation.model.SyInSpBaseList;
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
 * 关系-系统所在业务空间-033
 */
@Slf4j
@RestController
@RequestMapping("/rel/sy-in-sp-base")
public class RelationSyInSpController {

    @Autowired
    private IAdmRelationService service;

    @PostMapping("/link-list")
    public AdmResponse create(@RequestBody AdmCreateRequest<SyInSpBase> syInSpBase) {
        List<SyInSpBase> syInSpBases = syInSpBase.getContent();
        List<RelationDTO> voList = new ArrayList<>();
        AdmRelationTypeEnum typeEnum = AdmRelationTypeEnum.SY2SP;
        String graphCode = typeEnum.getGraphCode();
        String relCode = typeEnum.getRelCode();
        for (SyInSpBase inSpBase : syInSpBases) {
            String spaceId = inSpBase.getSpaceId();
            String sysId = inSpBase.getSysId();
            String objectType = inSpBase.getObjectType();
            if (StrUtil.isBlank(spaceId) || StrUtil.isBlank(sysId) ) {
                return AdmResponse.failure("必填项：SysId（系统id）、spaceId（空间id）");
            }
            RelationDTO relation = new RelationDTO(null, graphCode, relCode, objectType, sysId, spaceId);
            voList.add(relation);
        }
        service.doSave(AdmContextUtil.toDmpContext(), voList);
        return AdmResponse.success();
    }

    /**
     * 处理所有空间分区和系统关系 系统所在的业务空间关系，空间分区一对多，累计叠加，不覆盖
     */
    @PostMapping(value = "/link-sp-sys")
    public AdmResponse createsSpSys( @RequestBody JSONObject param) {
        //JSONObject rSyIn = param.getJSONObject("rSyInSpBase");
        String type = param.getString("type");
        SpInSyBaseList rSyInSpBase = JSON.toJavaObject(param, SpInSyBaseList.class);
        String spaceId = rSyInSpBase.getSpaceId();
        List<String> sysIdList = rSyInSpBase.getSysIdList();
        if (StrUtil.isBlank(spaceId) || CollectionUtils.isEmpty(sysIdList)) {
            return AdmResponse.failure("必填项：SysId（系统id）、spaceId（空间id）");
        }
        List<RelationDTO> voList = new ArrayList<>();
        AdmRelationTypeEnum typeEnum = AdmRelationTypeEnum.SY2SP;
        String graphCode = typeEnum.getGraphCode();
        String relCode = typeEnum.getRelCode();
        for (String sysId : sysIdList) {
            RelationDTO relation = new RelationDTO(null, graphCode, relCode, type, sysId, spaceId);
            voList.add(relation);
        }
        service.doSave(AdmContextUtil.toDmpContext(), voList);
        return AdmResponse.success();
    }

    /**
     * 创建系统所在业务空间关系
     * 系统所在业务空间关系，系统一对多，不覆盖
     *
     * @param param 系统和业务空间的关系对象
     * @return 创建的结果信息
     */
    @PostMapping(value = "/link-sy-sps")
    public AdmResponse createSySps( @RequestBody JSONObject param) {
        //JSONObject rSyIn = param.getJSONObject("rSyInSpBase");
        String type = param.getString("type");
        SyInSpBaseList  syInSpBaseList= JSON.toJavaObject(param, SyInSpBaseList.class);
        List<String> spaceIdList = syInSpBaseList.getSpaceIdList();
        String sysId = syInSpBaseList.getSysId();
        List<RelationDTO> voList = new ArrayList<>();
        AdmRelationTypeEnum typeEnum = AdmRelationTypeEnum.SY2SP;
        String graphCode = typeEnum.getGraphCode();
        String relCode = typeEnum.getRelCode();
        for (String spaceId : spaceIdList) {
            if (StrUtil.isBlank(spaceId) || StrUtil.isEmpty(sysId)) {
                return AdmResponse.failure("必填项：SysId（系统id）、spaceId（空间id）");
            }
            RelationDTO relation = new RelationDTO(null, graphCode, relCode, type, sysId, spaceId);
            voList.add(relation);
        }
        service.doSave(AdmContextUtil.toDmpContext(), voList);
        return AdmResponse.success();
    }

    /**
     * 根据对象删除系统所在业务空间关系
     *
     * @param
     * @return 删除的结果信息
     */
    @PostMapping("/unlink-list")
    public AdmResponse delete(@RequestParam(value = "type",required = false) String type, @RequestBody JSONArray param) {
        //JSONArray jsonArray = param.getJSONArray("rSyInSpBase");
        List<SyInSpBase> syInSpBases = JSONArray.parseArray(param.toJSONString(),SyInSpBase.class);
        //String type = param.getString("type");
        AdmRelationTypeEnum typeEnum = AdmRelationTypeEnum.SY2SP;
        String graphCode = typeEnum.getGraphCode();
        String relCode = typeEnum.getRelCode();
        List<QueryCriteria> queryCriteriaList = new ArrayList<>();
        if(CollectionUtils.isEmpty(syInSpBases)){
            return AdmResponse.failure("必填项：syInSpBases");
        }
        for (SyInSpBase syInSpBase : syInSpBases) {
            String sysId = syInSpBase.getSysId();
            String spaceId = syInSpBase.getSpaceId();
            if (StrUtil.isBlank(spaceId) || StrUtil.isEmpty(sysId)) {
                return AdmResponse.failure("必填项：SysId（系统id）、spaceId（空间id）");
            }
            QueryCriteria criteria = new QueryCriteria();
            ObjectNode node = JsonNodeFactory.instance.objectNode();
            node.put("graphCode", graphCode);
            node.put("relCode", relCode);
            node.put("objFrom", sysId);
            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();
    }
}
