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.BdForEqList;
import com.persagy.proxy.relation.model.EqForBd;
import com.persagy.proxy.relation.model.EqForBdList;
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.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

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

/**
 * 设备服务于建筑
 *
 * @author zhangwencheng
 */
@RestController
@RequestMapping("/rel/eq-for-bd")
public class RelationEqForBdController {

    @Autowired
    private IAdmRelationService service;

    /**
     * 创建设备服务于建筑关系
     * 必填项：EquipId（设备id）、BuildingId（建筑id）
     *
     * @param eq2Bd 设备和建筑的关系对象
     * @return 创建的结果信息
     */
    @PostMapping("/link")
    public AdmResponse create(@RequestBody EqForBd eq2Bd) {
        String buildingId = eq2Bd.getBuildingId();
        String equipId = eq2Bd.getEquipId();
        //检验输入参数
        if (StrUtil.isEmpty(buildingId) || StrUtil.isEmpty(equipId)) {
            return AdmResponse.failure("必填项：equipId（设备id）、buildingId（建筑id列表）");
        }
        List<RelationDTO> voList = new ArrayList<>();
        AdmRelationTypeEnum typeEnum = AdmRelationTypeEnum.EQ2BD;
        String graphCode = typeEnum.getGraphCode();
        String relCode = typeEnum.getRelCode();
        RelationDTO relation = new RelationDTO(null, graphCode, relCode, "", equipId, buildingId);
        voList.add(relation);
        service.doSave(AdmContextUtil.toDmpContext(), voList);
        return AdmResponse.success();
    }

    /**
     * 设备服务于建筑，设备一对多
     * 必填项：BuildingIdList（建筑id列表）、EquipId（设备id）,测方法会覆盖以前的记录
     *
     * @param eqForBdList
     * @return 创建的结果信息
     */
    @PostMapping("link-bd")
    public AdmResponse createBd(@RequestBody EqForBdList eqForBdList) {
        List<String> buildingIdList = eqForBdList.getBuildingIdList();
        String equipId = eqForBdList.getEquipId();
        //检验输入参数
        if (CollectionUtils.isEmpty(buildingIdList) || StrUtil.isEmpty(equipId)) {
            return AdmResponse.failure("必填项：equipId（设备id）、buildingIdList（建筑id列表）");
        }
        AdmRelationTypeEnum typeEnum = AdmRelationTypeEnum.EQ2BD;
        String graphCode = typeEnum.getGraphCode();
        String relCode = typeEnum.getRelCode();
        List<RelationDTO> voList = new ArrayList<>();
        InstanceUrlParam context = AdmContextUtil.toDmpContext();
        //根据设备删除以前信息
        deleteByEquipId(equipId, typeEnum, context);
        for (String buildingId : buildingIdList) {
            RelationDTO relation = new RelationDTO(null, graphCode, relCode, null, equipId, buildingId);
            voList.add(relation);
        }
        service.doSave(context, voList);
        return AdmResponse.success();
    }

    /**
     * 根据设备Id删除信息
     *
     * @param equipId
     * @param typeEnum
     * @param context
     */
    private void deleteByEquipId(String equipId, 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("objFrom", equipId);
        criteria.setCriteria(node);
        service.doDelete(context, criteria);
    }

    /**
     * 服务于建筑的设备，建筑一对多
     * 必填项：EquipIdList（设备id列表）、BuildingId（建筑id）
     *
     * @param bdForEqList 设备和建筑关系对象
     * @return 创建的结果信息
     */
    @PostMapping("link-sy")
    public AdmResponse createSy(@RequestBody BdForEqList bdForEqList) {
        String buildingId = bdForEqList.getBuildingId();
        List<String> equipIdList = bdForEqList.getEquipIdList();
        //检验输入参数
        if (CollectionUtils.isEmpty(equipIdList) || StrUtil.isEmpty(buildingId)) {
            return AdmResponse.failure("必填项：equipIdList（设备id列表）、buildingId（建筑id）");
        }
        AdmRelationTypeEnum typeEnum = AdmRelationTypeEnum.EQ2BD;
        String graphCode = typeEnum.getGraphCode();
        String relCode = typeEnum.getRelCode();
        List<RelationDTO> voList = new ArrayList<>();
        InstanceUrlParam context = AdmContextUtil.toDmpContext();
        deleteByBuildId(buildingId, typeEnum, context);
        for (String equipId : equipIdList) {
            RelationDTO relation = new RelationDTO(null, graphCode, relCode, null, equipId, buildingId);
            voList.add(relation);
        }
        service.doSave(context, voList);
        return AdmResponse.success();
    }

    /**
     * 根据建筑Id删除设备和建筑关系
     *
     * @param buildingId
     * @param typeEnum
     * @param context
     */
    private void deleteByBuildId(String buildingId, 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("objTo", buildingId);
        criteria.setCriteria(node);
        service.doDelete(context, criteria);
    }

    /**
     * 根据对象删除设备服务于建筑的关系，只针对一个对象
     * 必填项：EquipId（设备id）、BuildingId(建筑id)
     *
     * @param eqForBd 对象
     * @return 删除的结果信息
     */
    @PostMapping("/unlink")
    public AdmResponse delete(@RequestBody EqForBd eqForBd) {
        String equipId = eqForBd.getEquipId();
        String buildingId = eqForBd.getBuildingId();
        //检验输入参数
        if (StrUtil.isEmpty(equipId) || StrUtil.isEmpty(buildingId)) {
            return AdmResponse.failure("必填项：equipId（设备id）、buildingId（建筑id）");
        }
        InstanceUrlParam context = AdmContextUtil.toDmpContext();
        AdmRelationTypeEnum typeEnum = AdmRelationTypeEnum.EQ2BD;
        String graphCode = typeEnum.getGraphCode();
        String relCode = typeEnum.getRelCode();
        QueryCriteria criteria = new QueryCriteria();
        ObjectNode node = JsonNodeFactory.instance.objectNode();
        node.put("graphCode", graphCode);
        node.put("relCode", relCode);
        node.put("objTo", buildingId);
        node.put("objFrom", equipId);
        criteria.setCriteria(node);
        service.doDelete(context, criteria);
        return AdmResponse.success();
    }
}
