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.ProcessReportEngineImpl;
import com.leanwo.activiti.util.SpringUtil;

@Service
public class ProcessTaskEngineServiceImpl implements ProcessTaskEngineService {

	@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("processReportEngineImpl" + accountManagementDto.getAccountId())) {
        	defaultListableBeanFactory.removeBeanDefinition("processReportEngineImpl" + accountManagementDto.getAccountId());
        }
        // 创建流程bean定义
        BeanDefinitionBuilder beanDefinitionBuilder =
            BeanDefinitionBuilder.genericBeanDefinition(ProcessReportEngineImpl.class);
//        beanDefinitionBuilder.setInitMethodName("init");
        beanDefinitionBuilder.addConstructorArgValue(accountManagementDto.getAccountId());
        beanDefinitionBuilder.addConstructorArgValue(accountManagementDto.getProcessreportengineimplValue());
        defaultListableBeanFactory.registerBeanDefinition("processReportEngineImpl" + accountManagementDto.getAccountId(),
            beanDefinitionBuilder.getRawBeanDefinition());
        ProcessReportEngineImpl processReportEngineImpl = (ProcessReportEngineImpl)applicationContext.getBean("processReportEngineImpl" + accountManagementDto.getAccountId());
        processReportEngineImpl.init();
        
	}

}
