package cn.axzo.msg.center.wx.notices.compont;

import cn.axzo.msg.center.common.consts.ConstPool;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import com.alibaba.ttl.TransmittableThreadLocal;
import lombok.SneakyThrows;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * 企业微信自建应用
 *
 * @author cn
 * @version 1.0
 * @description
 * @date 2023/5/25 14:19
 */
@Service
public class WxCpProcessor extends WxCpServiceImpl {

    //初始化为微信的公共包数据
    static {
        //改变threadLocal为ttl的
        setTTlThreadPool();
    }

    @SneakyThrows
    @SuppressWarnings({"rawtypes", "unchecked"})
    private static void setTTlThreadPool() {
        TransmittableThreadLocal<String> ttlThreadLocal = new TransmittableThreadLocal() {
            @Override
            protected String initialValue() {
                return "default";
            }
        };
        Field threadLocal = ReflectionUtils.findField(WxMaConfigHolder.class, "THREAD_LOCAL");
        if (threadLocal != null) {
            ReflectionUtils.makeAccessible(threadLocal);
            Field modifiers = ReflectionUtils.findField(threadLocal.getClass(), ConstPool.MODIFIERS);
            if (modifiers != null) {
                ReflectionUtils.makeAccessible(modifiers);
                ReflectionUtils.setField(modifiers, threadLocal, threadLocal.getModifiers() ^ Modifier.FINAL);
            }
            ReflectionUtils.setField(threadLocal, WxMaConfigHolder.class, ttlThreadLocal);
        }
    }
}
