package org.dromara.mp.aspect;

import me.chanjar.weixin.mp.api.WxMpService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.dromara.common.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 微信公众号切面 用于切换公众号配置
 *
 * @author Peng Les
 */
@Aspect
@Component
public class SwitchoverCheckAspect {

    @Autowired
    private WxMpService wxMpService;

    @Pointcut("@annotation(org.dromara.mp.annotation.SwitchoverCheck)")
    public void switchoverCheckPointcut() {
    }

    @Before("switchoverCheckPointcut()")
    public void beforeSwitchover(JoinPoint joinPoint) {
        // 获取方法参数
        Object[] args = joinPoint.getArgs();
        if (args.length > 0 && args[0] instanceof String) {
            String appid = (String) args[0];
            System.out.println("前置切面：准备切换公众号配置，appid: " + appid);

            // 检查 appid 是否为空
            if (StringUtils.isEmpty(appid)) {
                throw new IllegalArgumentException("appid 不能为空！");
            }

            if (!wxMpService.switchover(appid)) {
                throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
            }
        }
    }
}