package com.yeejoin.amos.boot.module.jg.biz.edit.esUpdate.service;

import com.yeejoin.amos.boot.module.common.api.dto.ESEquipmentCategoryDto;
import com.yeejoin.amos.boot.module.common.api.dto.IBaseChangeData;
import com.yeejoin.amos.boot.module.jg.biz.edit.esUpdate.strategy.EsBuildStrategy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
@Slf4j
public class EsUpdateService {

    private final List<EsBuildStrategy<?>> strategies;
    // 类型→策略的缓存Map
    private Map<Class<?>, EsBuildStrategy<?>> strategyMap;

    @PostConstruct
    public void init() {
        // 初始化策略映射
        strategyMap = strategies.stream()
                .collect(Collectors.toMap(
                        EsBuildStrategy::getSupportType,
                        strategy -> strategy
                ));
    }

    /**
     * 统一入口方法
     */
    public void buildEsData(ESEquipmentCategoryDto esEquipmentCategoryDto, IBaseChangeData data) {
        if (data == null) return;
        EsBuildStrategy<?> strategy = strategyMap.get(data.getClass());
        if (strategy != null) {
            executeStrategy(esEquipmentCategoryDto, data, strategy);
        } else {
            log.warn("No strategy found for type: {}", data.getClass());
        }
    }


    @SuppressWarnings("unchecked")
    private <T extends IBaseChangeData> void executeStrategy(ESEquipmentCategoryDto esEquipmentCategoryDto, T data, EsBuildStrategy<?> strategy) {
        ((EsBuildStrategy<T>) strategy).buildEsData(esEquipmentCategoryDto, data);
    }
}
