/*
 * 文 件 名:  BoundaryObjServiceImpl
 * 版    权:  华设设计集团股份有限公司
 * 描    述:  <描述>
 * 修 改 人:  lvwenbin
 * 修改时间:  2025/1/13
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */
package com.ruoyi.ems.service.impl;

import com.huashe.common.exception.Assert;
import com.huashe.common.exception.BusinessException;
import com.ruoyi.ems.domain.Area;
import com.ruoyi.ems.domain.ElecMeterH;
import com.ruoyi.ems.domain.EmsFacs;
import com.ruoyi.ems.domain.EnergyMeter;
import com.ruoyi.ems.domain.MeterBoundaryRel;
import com.ruoyi.ems.enums.MeterObjType;
import com.ruoyi.ems.model.BoundaryObj;
import com.ruoyi.ems.model.QueryMeter;
import com.ruoyi.ems.service.IAreaService;
import com.ruoyi.ems.service.IBoundaryObjService;
import com.ruoyi.ems.service.IElecMeterHService;
import com.ruoyi.ems.service.IEmsFacsService;
import com.ruoyi.ems.service.IMeterBoundaryRelService;
import com.ruoyi.ems.util.AreaUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <一句话功能简述>
 * <功能详细描述>
 *
 * @author lvwenbin
 * @version [版本号, 2025/1/13]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Service
public class BoundaryObjServiceImpl implements IBoundaryObjService {
    private static final Logger log = LoggerFactory.getLogger(BoundaryObjServiceImpl.class);

    // 注入区域服务
    @Autowired
    private IAreaService areaService;

    // 注入设施服务
    @Autowired
    private IEmsFacsService facsService;

    // 注入电表数据服务
    @Autowired
    private IElecMeterHService elecMeterHService;

    // 注入边界对象关系服务
    @Autowired
    private IMeterBoundaryRelService boundaryRelService;

    /**
     * 根据区域编码、对象类型和对象代码获取边界对象
     *
     * @param areaCode 区域编码
     * @return 边界对象
     */
    @Override
    public BoundaryObj getBoundaryByArea(String areaCode, Integer meterCls) {
        BoundaryObj boundaryObj = null;

        try {
            // 查询电表绑定关系
            List<MeterBoundaryRel> relList = boundaryRelService.selectRelByObj(null, MeterObjType.METER_AREA.getType(),
                meterCls);
            Map<String, Set<MeterBoundaryRel>> relMap = relList.stream()
                .collect(Collectors.groupingBy(MeterBoundaryRel::getBoundaryObj, Collectors.toSet()));

            // 根据区域编码获取根节点
            Area rootArea = areaService.selectAreaByCode(areaCode);
            Assert.notNull(rootArea, -1, "区域不存在");
            // 下级区域递归
            List<Area> subList = areaService.selectAreaTree(areaCode, true);

            // 递归转换
            boundaryObj = recursionConvert(rootArea, subList, relMap);
        }
        catch (BusinessException e) {
            log.debug(e.getMessage());
        }

        return boundaryObj;
    }

    @Override
    public List<ElecMeterH> getMeterStaByArea(QueryMeter queryMeter) {
        return Collections.emptyList();
    }




    /**
     * 递归构造边界-绑定电表 的树结构
     *
     * @param parentArea 根区域
     * @param subList    子区列表
     * @param relMap     关联电表集合
     * @return 边界树结构对象
     */
    private BoundaryObj recursionConvert(Area parentArea, List<?> subList, Map<String, Set<MeterBoundaryRel>> relMap) {
        BoundaryObj boundaryObj = new BoundaryObj();
        boundaryObj.setObjType(MeterObjType.METER_AREA.getType());
        boundaryObj.setObjCode(parentArea.getAreaCode());
        boundaryObj.setObjName(parentArea.getAreaName());

        // 设置直接绑定的电表
        Set<MeterBoundaryRel> relSet = relMap.get(parentArea.getAreaCode());

        if (CollectionUtils.isNotEmpty(relSet)) {
            Set<String> bindDevs = relSet.stream().map(MeterBoundaryRel::getMeterDevice).collect(Collectors.toSet());
            boundaryObj.setBindMeterDevs(bindDevs);
        }

        List<BoundaryObj> subObjs = new ArrayList<>();
        boundaryObj.setChildren(subObjs);

        if (CollectionUtils.isNotEmpty(subList)) {
            // 递归封装子区边界对象
            for (Object obj : subList) {
                Area area = (Area) obj;
                BoundaryObj sonObj = recursionConvert(area, area.getChildren(), relMap);
                subObjs.add(sonObj);
            }

            // 设置子区绑定电表
            boundaryObj.setSubMeterDevs(getSubElecMeterDev(subList, relMap));
        }

        return boundaryObj;
    }

    /**
     * 获取子区绑定的电表
     *
     * @param subList 子区对象
     * @param relMap  关联电表集合
     * @return 子区绑定电表集合
     */
    private Set<String> getSubElecMeterDev(List<?> subList, Map<String, Set<MeterBoundaryRel>> relMap) {
        Set<String> subRelSet = new HashSet<>();

        for (Object obj : subList) {
            Area area = (Area) obj;

            Set<MeterBoundaryRel> tempSubrelSet = relMap.get(area.getAreaCode());

            // 场景1：直接绑定在子区对象的电表
            if (CollectionUtils.isNotEmpty(tempSubrelSet)) {
                Set<String> bindDevs = tempSubrelSet.stream().map(MeterBoundaryRel::getMeterDevice)
                    .collect(Collectors.toSet());
                subRelSet.addAll(bindDevs);
            }
            // 场景2：绑定在子区下属区域的电表
            else {
                List<?> subSubList = area.getChildren();

                if (CollectionUtils.isNotEmpty(subSubList)) {
                    subRelSet.addAll(getSubElecMeterDev(subSubList, relMap));
                }
            }
        }

        return subRelSet;
    }
}