package com.product;

import com.google.common.collect.Lists;
import com.product.common.utils.spring.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.List;

/**
 * @Author cheng
 * @Description 绯荤粺鍚姩鍒濆鍖栧姞杞�
 * @Date 2021/11/8 15:14
 * @Version 1.0
 */
public class InitialLoad {

    private static Logger logger = LoggerFactory.getLogger(InitialLoad.class);
    /**
     * 鍒濆鍖栧姞杞絙ean.method 鍙帴鍙楁棤鍙傛柟娉�
     * 涓斿繀椤诲埌缂撳瓨琛ㄤ腑閰嶇疆鐩稿簲缂撳瓨鏁版嵁
     */
    private static List<String> initMethods = Lists.newArrayList(
            "sysJobService.init",
            "userOperService.initUserSignature"
    );

    public static void runInitialization() {
        for (int i = 0; i < initMethods.size(); i++) {
            String beanMethod = initMethods.get(i);
            if (beanMethod.indexOf('.') > -1) {
                String[] p = beanMethod.split("\\.");
                execute(p[0], p[1]);
                //鍒犻櫎宸叉墽琛岃繃鐨勬柟娉曢槻姝㈤噸澶嶅垵濮嬪寲
                initMethods.remove(i);
                i--;
            }
        }
    }

    private static void execute(String beanName, String methodName) {
        try {
            Object bean = SpringUtils.getBean(beanName);
            Method method = null;
            if (bean != null) {
                method = ReflectionUtils.findMethod(bean.getClass(), methodName);
            }
            if (bean == null || method == null) {
                throw new ReflectiveOperationException(" execute bean or method not exist ! ");
            }
            ReflectionUtils.invokeMethod(method, bean);
        } catch (Exception e) {
            logger.error("execute init method " + beanName + "." + methodName + " error !", e);
        }
    }

}