/**
 * Copyright &copy; 2013-2017 <a href="http://www.rhcncpa.com/">瑞华会计师事务所</a> All rights reserved.
 */
package com.jeeplus.modules.sys.utils;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.jeeplus.common.utils.JedisUtils;
import com.jeeplus.modules.sys.dao.MainDictDetailDao;
import com.jeeplus.modules.sys.entity.MainDict;
import com.jeeplus.modules.sys.entity.MainDictDetail;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.service.MainDictService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.utils.CacheUtils;
import com.jeeplus.common.utils.SpringContextHolder;
import com.jeeplus.modules.sys.dao.DictDao;
import com.jeeplus.modules.sys.entity.Dict;
import redis.clients.jedis.Jedis;

/**
 * 字典工具类
 * @author jeeplus
 * @version 2013-5-29
 */
public class DictUtils {
	
	private static DictDao dictDao = SpringContextHolder.getBean(DictDao.class);
	private static MainDictService mainDictService = SpringContextHolder.getBean(MainDictService.class);
	private static MainDictDetailDao mainDictDetailDao = SpringContextHolder.getBean(MainDictDetailDao.class);

	public static final String CACHE_DICT_MAP = "dictMap";
	public static final String MAIN_DICT_MAP = "mainDictMap";
	public static String getDictLabel(String value, String type, String defaultValue){
		if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(value)){
			for (Dict dict : getDictList(type)){
				if (type.equals(dict.getType()) && value.equals(dict.getValue())){
					return dict.getLabel();
				}
			}
		}
		return defaultValue;
	}

	/**
	 * 公司级业务字典
	 * @param value
	 * @param type
	 * @param defaultValue
	 * @return
	 */
	public static String getMainDictLabel(String value, String type, String defaultValue){
		if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(value)){
			for (MainDictDetail mainDictDetail : getMainDictList(type)){
				if (type.equals(mainDictDetail.getType()) && value.equals(mainDictDetail.getValue())){
					return mainDictDetail.getLabel();
				}
			}
		}
		return defaultValue;
	}
	public static String getMainDictLabels(String values,String splitStr, String type, String defaultValue){
	    if(splitStr==null)splitStr="";
		if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(values)){
            List<MainDictDetail> dictDetailList = getMainDictList(type);
            List<String> valueList = Lists.newArrayList();
            String[] split = values.split(splitStr);
            for (MainDictDetail mainDictDetail : dictDetailList){
                for (String value : split) {
                    if (value.equals(mainDictDetail.getValue())){
                        valueList.add(mainDictDetail.getLabel());
                        break;
                    }
                }
            }
            return StringUtils.join(valueList,splitStr);
		}
		return defaultValue;
	}
	public static String getDictLabels(String values, String type, String defaultValue){
		if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(values)){
			List<String> valueList = Lists.newArrayList();
			for (String value : StringUtils.split(values, ",")){
				valueList.add(getDictLabel(value, type, defaultValue));
			}
			return StringUtils.join(valueList, ",");
		}
		return defaultValue;
	}

	public static String getDictValue(String label, String type, String defaultLabel){
		if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(label)){
			for (Dict dict : getDictList(type)){
				if (type.equals(dict.getType()) && label.equals(dict.getLabel())){
					return dict.getValue();
				}
			}
		}
		return defaultLabel;
	}

	public static String getMainDictValue(String label, String type, String defaultLabel){
		if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(label)){
			for (MainDictDetail mainDictDetail : getMainDictList(type)){
				if (type.equals(mainDictDetail.getType()) && label.equals(mainDictDetail.getLabel())){
					return mainDictDetail.getValue();
				}
			}
		}
		return defaultLabel;
	}
	
	public static List<Dict> getDictList(String type){
		@SuppressWarnings("unchecked")
		Map<String, List<Dict>> dictMap = (Map<String, List<Dict>>)CacheUtils.get(CACHE_DICT_MAP);
		if (dictMap==null){
			dictMap = Maps.newHashMap();
			for (Dict dict : dictDao.findAllList(new Dict())){
				List<Dict> dictList = dictMap.get(dict.getType());
				if (dictList != null){
					dictList.add(dict);
				}else{
					dictMap.put(dict.getType(), Lists.newArrayList(dict));
				}
			}
			CacheUtils.put(CACHE_DICT_MAP, dictMap);
		}
		List<Dict> dictList = dictMap.get(type);
		if (dictList == null){
			dictList = Lists.newArrayList();
		}
		return dictList;
	}

	/**
	 * 公司级业务字典
	 * @param type
	 * @return
	 */
	public static List<MainDictDetail> getMainDictList(String type){
		Jedis jedis = null;
        List<MainDictDetail> dictList=new ArrayList<>();
		String comId=UserUtils.getSelectCompany().getId();
		String branchId=UserUtils.getSelectBranchOffice();
		MainDict mainDict = mainDictService.getIdByName(type);
		String key="";
		if("1".equals(mainDict.getDictType())){
			key="dictDetail_"+type+"_"+comId;
		}else{
			key="dictDetail_"+type+"_"+branchId;
		}
		try {
			jedis = JedisUtils.getResource();
			String listString=jedis.get(key);
			if (listString != null && !"".equals(listString)) {
                dictList= JSON.parseArray(listString, MainDictDetail.class);
				return dictList;
			}else{
				MainDictDetail mainDictDetail = new MainDictDetail();
				if("1".equals(mainDict.getDictType())){
				    mainDictDetail.setBranchOffice(comId);
				}else{
				    mainDictDetail.setBranchOffice(branchId);
				}
					mainDictDetail.setType(type);
					dictList = mainDictDetailDao.findJedisAllList(mainDictDetail);
					String str=JSON.toJSONString(dictList);
					jedis.set(key,str);
					jedis.expire(key,60*10);
					return dictList;
			}
		} catch (Exception e) {
			System.out.println("获取业务字典失败！");
		} finally {
			JedisUtils.returnResource(jedis);
		}
		return dictList;
	}

	/*public static List<MainDictDetail> getMainDictListView(String type){
		boolean admin = UserUtils.getUser().isAdmin();
		String comId=UserUtils.getSelectCompany().getId();
		String branchId=UserUtils.getSelectBranchOffice();
		List<MainDictDetail> dictList=new ArrayList<>();
		//获取字典类型对象
		MainDict mainDictCache=(MainDict)CacheUtils.get(type);
		if(mainDictCache==null){
			mainDictCache = mainDictService.getIdByName(type);
			CacheUtils.put(type, mainDictCache);
		}

		List<MainDictDetail> detailList = (List<MainDictDetail>)CacheUtils.get(mainDictCache.getId());
		if(detailList==null){
			MainDictDetail mainDictDetail=new MainDictDetail();
			mainDictDetail.setType(type);
			detailList=mainDictDetailDao.findAllListView(mainDictDetail);
			CacheUtils.put(mainDictCache.getId(), detailList);
		}else{
			for(MainDictDetail mainDictDetail:detailList){
				if(!admin) {
					if ("1".equals(mainDictCache.getDictType())) {
						if(mainDictDetail.getBranchOffice().equals(comId)&&"2".equals(mainDictDetail.getLevel())){
							dictList.add(mainDictDetail);
						}
					} else {
						if(mainDictDetail.getBranchOffice().equals(branchId)&&"2".equals(mainDictDetail.getLevel())){
							dictList.add(mainDictDetail);
						}
					}
				}else{
					if("1".equals(mainDictDetail.getLevel())){
						dictList.add(mainDictDetail);
					}
				}
			}
		}
		return dictList;
	}*/
	/*public static List<MainDictDetail> getMainDictList(String type){
		MainDict mainDict = mainDictService.getIdByName(type);
		MainDictDetail mainDictDetail = new MainDictDetail();
		boolean admin = UserUtils.getUser().isAdmin();
		List<MainDictDetail> dictList=new ArrayList<>();
		if(!admin){
			if("1".equals(mainDict.getDictType())){
				mainDictDetail.setBranchOffice(UserUtils.getSelectCompany().getId());
			}else{
				mainDictDetail.setBranchOffice(UserUtils.getSelectBranchOffice());
			}
			mainDictDetail.setType(type);
			mainDictDetail.setLevel("2");
			dictList = mainDictDetailDao.findAllList(mainDictDetail);
			return dictList;
		}else{
			mainDictDetail.setType(type);
			mainDictDetail.setLevel("1");
			dictList= mainDictDetailDao.findAllList(mainDictDetail);
			return dictList;
		}
	}*/

	/*public static List<MainDictDetail> getMainDictListView(String type){
		MainDict mainDict = mainDictService.getIdByName(type);
		MainDictDetail mainDictDetail = new MainDictDetail();
		boolean admin = UserUtils.getUser().isAdmin();
		List<MainDictDetail> dictList=new ArrayList<>();
		if(!admin){
			if("1".equals(mainDict.getDictType())){
				mainDictDetail.setBranchOffice(UserUtils.getSelectCompany().getId());
			}else{
				mainDictDetail.setBranchOffice(UserUtils.getSelectBranchOffice());
			}
			mainDictDetail.setType(type);
			mainDictDetail.setLevel("2");
			dictList = mainDictDetailDao.findAllListView(mainDictDetail);
			return dictList;
		}else{
			mainDictDetail.setType(type);
			mainDictDetail.setLevel("1");
			dictList= mainDictDetailDao.findAllListView(mainDictDetail);
			return dictList;
		}
	}*/

	/*
	 * 反射根据对象和属性名获取属性值
	 */
	public static Object getValue(Object obj, String filed) {
		try {
			Class clazz = obj.getClass();
			PropertyDescriptor pd = new PropertyDescriptor(filed, clazz);
			Method getMethod = pd.getReadMethod();//获得get方法

			if (pd != null) {

				Object o = getMethod.invoke(obj);//执行get方法返回一个Object
				return o;

			}
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IntrospectionException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		
		return null;
	}
}
