package com.kym.service.admin.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.kym.common.cache.PlatformCache;
import com.kym.entity.admin.EquipmentRelation;
import com.kym.entity.admin.dto.BatchBindEquipmentRelation;
import com.kym.mapper.admin.EquipmentRelationMapper;
import com.kym.service.admin.EquipmentRelationService;
import com.kym.service.cache.KymCache;
import com.kym.service.mybatisplus.MyBaseServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author skyline
 * @since 2023-08-07
 */
@Service
@DS("db-admin")
public class EquipmentRelationServiceImpl extends MyBaseServiceImpl<EquipmentRelationMapper, EquipmentRelation> implements EquipmentRelationService {

    @Override
    public EquipmentRelation getByShortId(String shortId) {
        return lambdaQuery().eq(EquipmentRelation::getShortId, shortId).one();
    }

    @Override
    public EquipmentRelation getByConnectorId(String connectorId) {
        return lambdaQuery().eq(EquipmentRelation::getConnectorId, connectorId).one();
    }


    @Override
    public EquipmentRelation getByEquipmentId(String equipmentId) {
        return lambdaQuery().eq(EquipmentRelation::getEquipmentId, equipmentId).one();
    }

    /**
     * 对同一站点的设备批量绑定平台
     *
     * @param equipmentRelation
     */
    @Override
    public void batchBind(BatchBindEquipmentRelation equipmentRelation) {
        UpdateWrapper<EquipmentRelation> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("connector_id", equipmentRelation.getConnectorIds());
        updateWrapper.set("platform_name", equipmentRelation.getPlatformName());
        update(updateWrapper);

        // 更新缓存
        var connectorId2PlatformName = equipmentRelation.getConnectorIds().stream().collect(Collectors.toMap(
                connectorId -> connectorId,
                connectorId -> equipmentRelation.getPlatformName()
        ));
        PlatformCache.INSTANCE.putConnectorId2PlatformName(connectorId2PlatformName);
        // todo 现有条件原则上只支持以站点维度更新绑定，一个站点只支持一个平台
        PlatformCache.INSTANCE.putStationId2PlatformName(
                Map.of(KymCache.INSTANCE.getStationIdByEquipmentIdOrConnectorId(equipmentRelation.getConnectorIds().get(0)), equipmentRelation.getPlatformName())
        );
    }

    @Override
    public List<String> getStationIdsByPlatformName(String platformName) {
        return lambdaQuery()
                .select(EquipmentRelation::getStationId)
                .eq(EquipmentRelation::getPlatformName, platformName)
                .groupBy(EquipmentRelation::getStationId)
                .list()
                .stream()
                .map(EquipmentRelation::getStationId)
                .collect(Collectors.toList());
    }

}
