package com.ajb.car.metadata.service;

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


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import com.ajb.car.entity.meta.AgMdCode;
import com.ajb.common.utils.cache.SystemCacheManager;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

@Service("systemConfigService")
@org.springframework.core.annotation.Order(1)
public class SystemConfigService implements CommandLineRunner{
	private static Cache systemConfigCache = SystemCacheManager.getCache("systemConfigCache");
	@Autowired
	private AgMdCodeService mdCodeService;
	
	/**
	 * 根据配置类型去获取相应配置
	 * @param configType
	 * @return
	 */
	public String getSingleConfigValue(String configType){
		String configValue = null;
		Element element = systemConfigCache.get(configType);
		if(element != null && element.getObjectValue() != null){
			configValue = (String)element.getObjectValue();
		}else{
			AgMdCode mdCode = new AgMdCode();
			mdCode.setCodeType(configType);
			mdCode.setIsActive(1);
//			System.out.println("------------------------------查询"+configType+"并放入缓存");
			List<AgMdCode> mdCodeList = mdCodeService.findByObjSortable(mdCode, null);
			if(mdCodeList != null && mdCodeList.size()>0){
				mdCode = mdCodeList.get(0);
				configValue = mdCode.getCodeCode();
				element = new Element(configType,configValue);
				systemConfigCache.put(element);
			}
		}
		return configValue;
	}

	/**
	 * 慎用！以免出现和keyValueMap中的key冲突，导致转换异常。
	 * 建议使用getKeyValueMap来替代此方法
	 * @param configType
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<String> getListConfigValue(String configType){
		List<String> configValues = null;
		Element element = systemConfigCache.get(configType);
		if(element != null && element.getObjectValue() != null){
			configValues = (List<String>)element.getObjectValue();
		}else{
			AgMdCode mdCode = new AgMdCode();
			mdCode.setCodeType(configType);
			mdCode.setIsActive(1);
			List<AgMdCode> mdCodeList = mdCodeService.findByObjSortable(mdCode, null);
			if(mdCodeList != null && mdCodeList.size()>0){
				configValues = new ArrayList<String>();
				for(AgMdCode md : mdCodeList){
					configValues.add(md.getCodeCode());	
				}
				element = new Element(configType,configValues);
				systemConfigCache.put(element);
			}
		}
		return configValues;
	}

	@Override
	public void run(String... args) throws Exception {
		// TODO Auto-generated method stub
		
	}
}
