package com.leanwo.activiti.db;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Service;

import com.leanwo.activiti.dto.base.AccountManagementDto;
import com.leanwo.activiti.service.base.impl.HttpTaskEngineImpl;
import com.leanwo.activiti.util.SpringUtil;

@Service
public class HttpTaskEngineServiceImpl implements HttpTaskEngineService {

	@Override
	public void createDynamicEngine(AccountManagementDto accountManagementDto) {
		ApplicationContext applicationContext = SpringUtil.getApplicationContext();
		// 将applicationContext转换为ConfigurableApplicationContext
        ConfigurableApplicationContext configurableApplicationContext =
            (ConfigurableApplicationContext)SpringUtil.getApplicationContext();
        // 获取bean工厂并转换为DefaultListableBeanFactory
        DefaultListableBeanFactory defaultListableBeanFactory =
            (DefaultListableBeanFactory)configurableApplicationContext.getBeanFactory();
        if(applicationContext.containsBean("httpTaskEngineImpl" + accountManagementDto.getAccountId())) {
        	defaultListableBeanFactory.removeBeanDefinition("httpTaskEngineImpl" + accountManagementDto.getAccountId());
        }
        
        //创建任务执行流程bean
        BeanDefinitionBuilder beanDefinitionBuilder1 =
                BeanDefinitionBuilder.genericBeanDefinition(HttpTaskEngineImpl.class);
//        beanDefinitionBuilder1.setInitMethodName("init");
        beanDefinitionBuilder1.addConstructorArgValue(accountManagementDto.getAccountId());
        beanDefinitionBuilder1.addConstructorArgValue(accountManagementDto.getHttpTaskEngineImplValue());
        defaultListableBeanFactory.registerBeanDefinition("httpTaskEngineImpl" + accountManagementDto.getAccountId(),
        		beanDefinitionBuilder1.getRawBeanDefinition());
        HttpTaskEngineImpl httpTaskEngineImpl = (HttpTaskEngineImpl)applicationContext.getBean("httpTaskEngineImpl" + accountManagementDto.getAccountId());
        httpTaskEngineImpl.init();
	}

}
