package com.fs.wx.order.service;

import com.fs.pay.domain.PaymentMiniProgramConfig;
import com.fs.pay.mapper.PaymentMiniProgramConfigMapper;
import com.fs.wx.order.service.impl.InMemoryWeChatAuthServiceImpl;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//@Component
public class WeChatAuthFactory  {
    private static ApplicationContext applicationContext;
    private final static Map<String,WeChatAuthService> weChatAuthServices = new ConcurrentHashMap<>();


    public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
        WeChatAuthFactory.applicationContext = applicationContext;
    }


    public void afterSingletonsInstantiated() {
        PaymentMiniProgramConfigMapper mapper = applicationContext.getBean(PaymentMiniProgramConfigMapper.class);
        List<PaymentMiniProgramConfig> configs = mapper.selectAll();
        for (PaymentMiniProgramConfig config : configs) {
            WeChatAuthService weChatAuthService = new InMemoryWeChatAuthServiceImpl(config.getAppid(),config.getAppSecret());
            weChatAuthServices.put(config.getAppid(),weChatAuthService);
        }
    }

    /**
     * 通过appid获取WeChatAuthService
     * @param appid 小程序ID
     * @return WeChatAuthService
     */
    public static WeChatAuthService getWeChatAuthService(String appid){
        return weChatAuthServices.get(appid);
    }

}
