package com.jeequan.jeepay.thirdparty.model;

import com.jeequan.jeepay.core.cache.RedisUtil;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.model.DBWxMpConfig;
import com.jeequan.jeepay.service.impl.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.redis.RedisTemplateWxRedisOps;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpRedisConfigImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
* 获取 WxMpService
*
* @author zx
* @site https://www.jeepay.vip
* @date 2021/10/15 9:37
*/
@Slf4j
@Component
public class WxmpServerContext {

    private static WxMpService wxMpService = null;

    public WxMpService getWxService(DBWxMpConfig wxMpConfig){

        if (!SysConfigService.IS_USE_CACHE) {
            return getWxMpService(wxMpConfig);
        }

        if(wxMpService == null){
            this.init(wxMpConfig);
        }

        return wxMpService;
    }

    public void clearWxService(){
        if (!SysConfigService.IS_USE_CACHE) {
            return;
        }

        wxMpService = null;
        log.info("微信公众号wxMpService对象已重置");
    }

    private synchronized void init(DBWxMpConfig wxMpConfig){

        wxMpService = getWxMpService(wxMpConfig);
        log.info("微信公众号wxMpService对象初始化完成");
    }

    private WxMpService getWxMpService(DBWxMpConfig wxMpConfig) {
        if(wxMpConfig == null || StringUtils.isAnyBlank(wxMpConfig.getWxAppId(), wxMpConfig.getWxAppSecret())){
            return null;
        }

        // 微信java使用redis缓存
        RedisTemplateWxRedisOps wxRedisOps = new RedisTemplateWxRedisOps(RedisUtil.getStringRedisTemplate());

        WxMpRedisConfigImpl config = new WxMpRedisConfigImpl(wxRedisOps, CS.CACHE_KEY_WX_JAVA);
        config.setAppId(wxMpConfig.getWxAppId()); // 设置微信公众号的appid
        config.setSecret(wxMpConfig.getWxAppSecret()); // 设置微信公众号的app corpSecret

        WxMpService wxService = new WxMpServiceImpl();
        wxService.setWxMpConfigStorage(config);

        return wxService;
    }

}
