package com.ruoyi.ems.service.impl;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.ems.domain.Area;
import com.ruoyi.ems.domain.AreaBuilding;
import com.ruoyi.ems.domain.AreaBuildingZoning;
import com.ruoyi.ems.domain.EmsDevice;
import com.ruoyi.ems.domain.EmsFacs;
import com.ruoyi.ems.domain.common.AreaTier;
import com.ruoyi.ems.domain.vo.QueryDevice;
import com.ruoyi.ems.domain.vo.TreeEntity;
import com.ruoyi.ems.mapper.EmsDeviceMapper;
import com.ruoyi.ems.service.IAreaBuildingService;
import com.ruoyi.ems.service.IAreaBuildingZoningService;
import com.ruoyi.ems.service.IAreaService;
import com.ruoyi.ems.service.IEmsDeviceService;
import com.ruoyi.ems.service.IEmsFacsService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 能源设备Service业务层处理
 *
 * @author ruoyi
 * @date 2024-07-10
 */
@Service
public class EmsDeviceServiceImpl implements IEmsDeviceService {
    @Autowired
    private EmsDeviceMapper emsDeviceMapper;

    @Autowired
    private IAreaService areaService;

    @Autowired
    private IAreaBuildingService buildingService;

    @Autowired
    private IAreaBuildingZoningService zoningService;

    @Autowired
    private IEmsFacsService facsService;

    /**
     * 查询能源设备
     *
     * @param id 能源设备主键
     * @return 能源设备
     */
    @Override
    public EmsDevice selectEmsDeviceById(Long id) {
        EmsDevice emsDevice = emsDeviceMapper.selectEmsDeviceById(id);

        if (null != emsDevice) {
            fillAreaName(emsDevice);
        }

        return emsDevice;
    }

    @Override
    public EmsDevice selectByCode(String code) {
        EmsDevice emsDevice = emsDeviceMapper.selectEmsDeviceByCode(code);

        if (null != emsDevice) {
            fillAreaName(emsDevice);
        }

        return emsDevice;
    }

    /**
     * 查询能源设备列表
     *
     * @param emsDevice 能源设备
     * @return 能源设备
     */
    @Override
    public List<EmsDevice> selectEmsDeviceList(EmsDevice emsDevice) {
        List<EmsDevice> list = emsDeviceMapper.selectEmsDeviceList(emsDevice);

        if (CollectionUtils.isNotEmpty(list)) {
            for (EmsDevice device : list) {
                fillAreaName(device);
            }
        }

        return list;
    }

    /**
     * 查询能源设备列表
     *
     * @param queryDevice 能源设备
     * @return 能源设备
     */
    @Override
    public List<EmsDevice> selectByAreaTree(QueryDevice queryDevice) {
        List<EmsDevice> list = emsDeviceMapper.selectByAreaTree(queryDevice);

        if (CollectionUtils.isNotEmpty(list)) {
            for (EmsDevice device : list) {
                fillAreaName(device);
            }
        }

        return list;
    }

    /**
     * 根据设施获取设备树结构
     *
     * @param areaCode 区域编码
     * @return 设备树结构
     */
    @Override
    public List<TreeEntity> getTreeByFacs(String areaCode) {
        List<TreeEntity> retList = new ArrayList<>();
        List<Area> areas = areaService.selectAreaList(new Area());
        List<AreaBuilding> buildings = buildingService.selectAreaBuildingList(new AreaBuilding());
        List<AreaBuildingZoning> zonings = zoningService.selectAreaBuildingZoningList(new AreaBuildingZoning());

        if (StringUtils.isEmpty(areaCode)) {
            if (CollectionUtils.isNotEmpty(areas)) {
                for (Area area : areas) {
                    List<EmsFacs> facsList = facsService.selectFacsByArea(area.getAreaCode());

                    TreeEntity entity = new TreeEntity();
                    entity.setId(area.getAreaCode());
                    entity.setLabel(area.getAreaName());
                    entity.setChildren(buildFacsDevSub(facsList, areas, buildings, zonings));
                    entity.setTier("Area");
                    retList.add(entity);
                }
            }
        }
        else {
            Area area = areaService.selectAreaByCode(areaCode);

            if (null != area) {
                List<EmsFacs> facsList = facsService.selectFacsByArea(area.getAreaCode());

                TreeEntity entity = new TreeEntity();
                entity.setId(area.getAreaCode());
                entity.setLabel(area.getAreaName());
                entity.setChildren(buildFacsDevSub(facsList, areas, buildings, zonings));
                entity.setTier("Area");
                retList.add(entity);
            }
        }

        return retList;
    }

    private List<TreeEntity> buildFacsDevSub(List<EmsFacs> facsList, List<Area> areas, List<AreaBuilding> buildings,
        List<AreaBuildingZoning> zonings) {
        List<TreeEntity> retList = new ArrayList<>();
        Map<String, Area> areaMap = areas.stream().collect(Collectors.toMap(Area::getAreaCode, Function.identity()));
        Map<String, AreaBuilding> buildingMap = buildings.stream()
            .collect(Collectors.toMap(AreaBuilding::getBldgCode, Function.identity()));
        Map<String, AreaBuildingZoning> zoningMap = zonings.stream()
            .collect(Collectors.toMap(AreaBuildingZoning::getZoningCode, Function.identity()));

        for (EmsFacs facs : facsList) {
            boolean hasSub = false;
            List<TreeEntity> subList = new ArrayList<>();

            EmsDevice param = new EmsDevice();
            param.setRefFacs(facs.getFacsCode());
            List<EmsDevice> devices = emsDeviceMapper.selectEmsDeviceList(param);

            for (EmsDevice device : devices) {
                hasSub = true;
                String namePrefix = "";
                if (StringUtils.equals(AreaTier.Area.name(), device.getAreaType())) {
                    namePrefix = areaMap.get(device.getRefArea()).getShortName();
                }
                else if (StringUtils.equals(AreaTier.Building.name(), device.getAreaType())) {
                    namePrefix = buildingMap.get(device.getRefArea()).getBldgName();
                }
                else if (StringUtils.equals(AreaTier.Zoning.name(), device.getAreaType())) {
                    AreaBuildingZoning zoning = zoningMap.get(device.getRefArea());
                    AreaBuilding building = zoning != null ? buildingMap.get(zoning.getBldgCode()) : null;
                    namePrefix = (building != null ? building.getBldgName() : "") + "/" + (zoning != null ?
                        zoning.getZoningName() : "");
                }

                String label = StringUtils.isNotBlank(namePrefix) ?
                    namePrefix + " - " + device.getDeviceName() :
                    device.getDeviceName();

                TreeEntity entity = new TreeEntity();
                entity.setId(device.getDeviceCode());
                entity.setLabel(label);
                entity.setTier("Device");
                subList.add(entity);
            }

            TreeEntity entity = new TreeEntity();
            entity.setId(facs.getFacsCode());
            entity.setLabel(facs.getFacsName());
            entity.setTier("Facs");
            entity.setChildren(subList);

            if (hasSub) {
                retList.add(entity);
            }
        }

        return retList;
    }

    /**
     * 新增能源设备
     *
     * @param emsDevice 能源设备
     * @return 结果
     */
    @Override
    public int insertEmsDevice(EmsDevice emsDevice) {
        emsDevice.setCreateTime(DateUtils.getNowDate());
        return emsDeviceMapper.insertEmsDevice(emsDevice);
    }

    /**
     * 修改能源设备
     *
     * @param emsDevice 能源设备
     * @return 结果
     */
    @Override
    public int updateEmsDevice(EmsDevice emsDevice) {
        emsDevice.setUpdateTime(DateUtils.getNowDate());
        return emsDeviceMapper.updateEmsDevice(emsDevice);
    }

    /**
     * 批量删除能源设备
     *
     * @param ids 需要删除的能源设备主键
     * @return 结果
     */
    @Override
    public int deleteEmsDeviceByIds(Long[] ids) {
        return emsDeviceMapper.deleteEmsDeviceByIds(ids);
    }

    /**
     * 删除能源设备信息
     *
     * @param id 能源设备主键
     * @return 结果
     */
    @Override
    public int deleteEmsDeviceById(Long id) {
        return emsDeviceMapper.deleteEmsDeviceById(id);
    }

    public void fillAreaName(EmsDevice emsDevice) {
        if (StringUtils.equals(emsDevice.getAreaType(), AreaTier.Area.name())) {
            Area area = areaService.selectAreaByCode(emsDevice.getRefArea());

            if (null != area) {
                emsDevice.setRefAreaName(area.getAreaName());
                emsDevice.setAreaPath(null != area.getShortName() ? area.getShortName() : area.getAreaName());
            }
            else {
                emsDevice.setRefAreaName("未知");
                emsDevice.setAreaPath("未知/");
            }
        }
        else if (StringUtils.equals(emsDevice.getAreaType(), AreaTier.Building.name())) {
            AreaBuilding building = buildingService.selectAreaBuildingByCode(emsDevice.getRefArea());

            if (null != building) {
                emsDevice.setRefAreaName(building.getBldgName());
                emsDevice.setAreaPath(building.getAreaShortName() + "/" + building.getBldgName());
            }
            else {
                emsDevice.setRefAreaName("未知");
                emsDevice.setAreaPath("未知/");
            }
        }
        else if (StringUtils.equals(emsDevice.getAreaType(), AreaTier.Zoning.name())) {
            AreaBuildingZoning zoning = zoningService.selectAreaBuildingZoningByCode(emsDevice.getRefArea());

            if (null != zoning) {
                emsDevice.setRefAreaName(zoning.getZoningName());

                AreaBuilding building = buildingService.selectAreaBuildingByCode(zoning.getBldgCode());

                if (null != building) {
                    emsDevice.setAreaPath(
                        building.getAreaShortName() + "/" + building.getBldgName() + "/" + zoning.getZoningName());
                }
                else {
                    emsDevice.setAreaPath("未知/");
                }
            }
            else {
                emsDevice.setRefAreaName("未知");
            }
        }
    }
}
