package net.northking.cctp.executePlan.quartz;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import net.northking.cctp.executePlan.constants.QuartzConstant;
import net.northking.cctp.executePlan.db.entity.AtuPlanInfo;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * <p>Title: JobInvokeUtil</p>
 * <p>Description: </p>
 *
 * @Author chenjianfeng
 * @Version V1.0
 * @Date 2022/12/29
 * <p>Copyright (c) 京北方信息技术股份有限公司 Corporation 2022 . All rights reserved.</p>
 */

public class JobInvokeUtil {

    /**
     * 执行方法
     *
     * @param planInfo 调度计划信息
     */
    public static void invokeMethod(AtuPlanInfo planInfo) throws Exception
    {
        String beanName = QuartzConstant.PLAN_TASK_EXECUTE_BEAN;
        String methodName = QuartzConstant.PLAN_TASK_EXECUTE_METHOD;

        if (!isValidClassName(beanName))
        {
            Object bean = SpringUtil.getBean(beanName);
            invokeMethod(bean, methodName, planInfo);
        }
        else
        {
            Object bean = Class.forName(beanName).newInstance();
            invokeMethod(bean, methodName, planInfo);
        }
    }

    /**
     * 调用任务方法
     *
     * @param bean 目标对象
     * @param methodName 方法名称
     * @param planInfo 方法参数
     */
    private static void invokeMethod(Object bean, String methodName, AtuPlanInfo planInfo)
            throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
            InvocationTargetException
    {
        if (ObjectUtil.isNotNull(planInfo)){
            Method method = bean.getClass().getDeclaredMethod(methodName, AtuPlanInfo.class);
            method.invoke(bean, planInfo);
        }
    }

    /**
     * 校验是否为为class包名
     *
     * @param invokeTarget 名称
     * @return true是 false否
     */
    public static boolean isValidClassName(String invokeTarget)
    {
        return StringUtils.countMatches(invokeTarget, ".") > 1;
    }
}
