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

import com.yeejoin.amos.boot.module.common.api.dto.IBaseChangeData;
import com.yeejoin.amos.boot.module.jg.biz.edit.esUpdate.strategy.EsUpdateStrategy;
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<EsUpdateStrategy<?>> strategies;
    // 类型→策略的缓存Map
    private Map<Class<?>, EsUpdateStrategy<?>> strategyMap;

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

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

    public void updateEsDataBatch(String record, List<? extends IBaseChangeData> dataList) {
        dataList.forEach(data -> updateEsData(record, data));
    }

    @SuppressWarnings("unchecked")
    private <T extends IBaseChangeData> void executeStrategy(String record, T data, EsUpdateStrategy<?> strategy) {
        ((EsUpdateStrategy<T>) strategy).updateEsData(record, data);
    }
}
