package com.kym.service.admin.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.kym.entity.admin.EquipmentRelation;
import com.kym.mapper.admin.EquipmentRelationMapper;
import com.kym.service.admin.EquipmentRelationService;
import com.kym.service.cache.KymCache;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Service;

import java.util.stream.Collectors;

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


    @PostConstruct
    private void init() {
        // 初始化KymCache shortId:equipmentId
        // 手动切换数据源
        DynamicDataSourceContextHolder.push("db-admin");
        KymCache.INSTANCE.putShort2EquipmentId(list().stream().collect(Collectors.toMap(EquipmentRelation::getConnectorId, EquipmentRelation::getShortId)));
        // 初始化KymCache connectorId:stationId
        KymCache.INSTANCE.putConnector2Station(list().stream().collect(Collectors.toMap(EquipmentRelation::getConnectorId, EquipmentRelation::getStationId)));
        DynamicDataSourceContextHolder.poll();
    }

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

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