package com.leanwo.activiti.db;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.leanwo.activiti.app.conf.CloudConfig;
import com.leanwo.activiti.dto.base.AccountManagementDto;
import com.leanwo.activiti.service.base.impl.ProdogServer;

@Service
public class AccountManagementServiceImpl implements AccountManagementService {

	private static Logger logger = LoggerFactory.getLogger(AccountManagementServiceImpl.class);

	@Inject
	private ProdogServer prodogServer;

	@Autowired
	private HttpTaskEngineService httpTaskEngineService;

	@Autowired
	private ProcessTaskEngineService processTaskEngineService;

	@Autowired
	private DataSourceService dataSourceService;

	private List<AccountManagementDto> accountManagementDtos = null;

	@Autowired
	private CloudConfig cloudConfig;

	@Autowired
	private ObjectMapper objectMapper;
	
	@Override
	public List<AccountManagementDto> loadAccountManagement(boolean force) {
		try {
			if (accountManagementDtos == null || force) {
				String accountManagement = cloudConfig.getAccountManagement();
				if(!StringUtils.isEmpty(accountManagement)) {
					accountManagementDtos = objectMapper.readValue(accountManagement, new TypeReference<List<AccountManagementDto>>() {});
					if(accountManagementDtos == null) {
						accountManagementDtos = new ArrayList<AccountManagementDto>();
					}
				}
				
				if (accountManagementDtos != null && accountManagementDtos.size() > 0) {
					for (AccountManagementDto accountManagementDto : accountManagementDtos) {
						if (accountManagementDto != null) {
							// 创建dataSource的bean
							dataSourceService.createDynamicDataSource(accountManagementDto);

							// 创建流程报表自动执行bean
							httpTaskEngineService.createDynamicEngine(accountManagementDto);

							processTaskEngineService.createDynamicEngine(accountManagementDto);
						}
					}
				}
			}
		} catch (Exception ex) {
			logger.error("从Prodog-Server服务器获取账套信息失败。", ex);
		}

		return accountManagementDtos;
	}

	@EventListener(EnvironmentChangeEvent.class)
	public void onApplicationEvent(EnvironmentChangeEvent event) {
		Set<String> keys = event.getKeys();
		if(keys != null && keys.contains("accountManagement")) {
			loadAccountManagement(true);
		}
	}
}
