package com.cpop.oam.framework.handler.wxOpen;

import com.cpop.oam.framework.config.wxOpen.WechatOpenProperties;
import com.cpop.oam.framework.config.wxOpen.WxOpenRedisProperties;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.Getter;
import me.chanjar.weixin.common.redis.RedisTemplateWxRedisOps;
import me.chanjar.weixin.open.api.impl.WxOpenInRedisConfigStorage;
import me.chanjar.weixin.open.api.impl.WxOpenMessageRouter;
import me.chanjar.weixin.open.api.impl.WxOpenServiceImpl;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author DB
 * @version 1.0.0
 * @since 2024-03-26 9:52
 */
@Component
@EnableConfigurationProperties({WechatOpenProperties.class, WxOpenRedisProperties.class})
public class WxOpenHandler extends WxOpenServiceImpl {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    @Getter
    private WechatOpenProperties wechatOpenProperties;

    @Getter
    private WxOpenMessageRouter wxOpenMessageRouter;

    @Resource(name = "wxOpenRedisTemplate")
    private StringRedisTemplate stringRedisTemplate;

    @PostConstruct
    public void init() {
        WxOpenInRedisConfigStorage inRedisConfigStorage = getWxOpenInRedisConfigStorage();
        setWxOpenConfigStorage(inRedisConfigStorage);
        wxOpenMessageRouter = new WxOpenMessageRouter(this);
        wxOpenMessageRouter.rule().handler((wxMpXmlMessage, map, wxMpService, wxSessionManager) -> {
            logger.info("\n接收到 {} 公众号请求消息，内容：{}", wxMpService.getWxMpConfigStorage().getAppId(), wxMpXmlMessage);
            return null;
        }).next();
    }

    @NotNull
    private WxOpenInRedisConfigStorage getWxOpenInRedisConfigStorage() {
        WxOpenInRedisConfigStorage inRedisConfigStorage;
        inRedisConfigStorage = new WxOpenInRedisConfigStorage(new RedisTemplateWxRedisOps(stringRedisTemplate), null);
        inRedisConfigStorage.setComponentAppId(wechatOpenProperties.getComponentAppId());
        inRedisConfigStorage.setComponentAppSecret(wechatOpenProperties.getComponentSecret());
        inRedisConfigStorage.setComponentToken(wechatOpenProperties.getComponentToken());
        inRedisConfigStorage.setComponentAesKey(wechatOpenProperties.getComponentAesKey());
        return inRedisConfigStorage;
    }


}
