package com.ced.sip.common;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
import java.util.regex.Pattern;

import javax.persistence.PersistenceException;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import com.ced.base.exception.BaseException;
import com.ced.sip.common.biz.ICacheInfoBiz;
import com.ced.sip.common.utils.StringUtil;
import com.ced.sip.system.entity.Departments;
import com.ced.sip.system.entity.Dictionary;
import com.ced.sip.system.entity.SystemConfiguration;
import com.ced.sip.system.entity.Users;

public class BaseDataInfosUtil {

	/**
	 * 获得Sequence的下一个值
	 * @author luguanglei 2016-08-25
	 * @return
	 * @throws BaseException 
	 */
	public static String getSequenceNextValue(String seqName) throws BaseException {  
	    return iCacheInfoBiz.getSequenceNextValue(seqName);  
	} 
	
	/**
	 * 取用户中文名
	 * @param userId 用户Id(主键)
	 * @return 用户中文名
	 * @throws BaseException
	 */
	public static String convertUserIdToChnName( Long userId ) throws BaseException {
		String rValue = "" ;
		
		if( StringUtil.isNotBlank(userId) ) {
			Object obj = getInitInfos(userId, TableStatus.BASE_DATA_TYPE_01) ;
			if( StringUtil.isNotBlank( obj ) ) {
				Users users = (Users) obj ;
				if( StringUtil.isNotBlank( users.getUserChinesename() ) ) {
					rValue = users.getUserChinesename() ;
				}
			}
		}
		return rValue ;
	}
	/**
	 * 取用户登录名
	 * @param userId 用户Id(主键)
	 * @return 用户登录名
	 * @throws BaseException
	 */
	public static String convertUserIdToEnnName( Long userId ) throws BaseException {
		String rValue = "" ;
		
		if( StringUtil.isNotBlank(userId) ) {
			Object obj = getInitInfos(userId, TableStatus.BASE_DATA_TYPE_01) ;
			if( StringUtil.isNotBlank( obj ) ) {
				Users users = (Users) obj ;
				if( StringUtil.isNotBlank( users.getUserName() ) ) {
					rValue = users.getUserName() ;
				}
			}
		}
		return rValue ;
	}
	/**
	 * 取用户部门Id
	 * @param loginName 用户登录名(主键)
	 * @return 用户登录名
	 * @throws BaseException
	 */
	public static Long convertUserLoginNameToDepId( String loginName) throws BaseException {
		long rValue =0 ;
		
		if( StringUtil.isNotBlank(loginName) ) {
			Object obj = getInitInfos(loginName, TableStatus.BASE_DATA_TYPE_01) ;
			if( StringUtil.isNotBlank( obj ) ) {
				Users users = (Users) obj ;
				if( StringUtil.isNotBlank( users.getDepId() ) ) {
					rValue = users.getDepId() ;
				}
			}
		}
		return rValue ;
	}
	/**
	 * 取用户comId
	 * @param userId 用户Id(主键)
	 * @return comId
	 * @throws BaseException
	 */
	public static Long convertUserIdToComId(Long userId) throws BaseException {
		long rValue =0 ;
		
		if( StringUtil.isNotBlank(userId) ) {
			Object obj = getInitInfos(userId, TableStatus.BASE_DATA_TYPE_01) ;
			if( StringUtil.isNotBlank( obj ) ) {
				Users users = (Users) obj ;
				if( StringUtil.isNotBlank( users.getDepId() ) ) {
					rValue = users.getComId() ;
				}
			}
		}
		return rValue ;
	}
	/**
	 * 取用户中文名
	 * @param loginName 用户登录名(英文)
	 * @return 用户中文名
	 * @throws BaseException
	 */
	public static String convertLoginNameToChnName( String loginName ) throws BaseException {
		String rValue = "" ;
		
		if( StringUtil.isNotBlank(loginName) ) {
			Object obj = getInitInfos(loginName, TableStatus.BASE_DATA_TYPE_01) ;
			if( StringUtil.isNotBlank( obj ) ) {
				Users users = (Users) obj ;
				if( StringUtil.isNotBlank( users.getUserChinesename() ) ) {
					rValue = users.getUserChinesename() ;
				}
			}
		}

		return rValue ;
	}
	/**
	 * 取用户信息
	 * @param loginName 用户登录名(英文)
	 * @return 用户中文名
	 * @throws BaseException
	 */
	public static Users convertLoginNameToUsers( String loginName ) throws BaseException {
		Users users=null;
		if( StringUtil.isNotBlank(loginName) ) {
			Object obj = getInitInfos(loginName, TableStatus.BASE_DATA_TYPE_01) ;
			if( StringUtil.isNotBlank( obj ) ) {
				users = (Users) obj ;
			}
		}

		return users ;
	}
	/**
	 * 取用户类别
	 * @param loginName 用户登录名(英文)
	 * @return 用户中文名
	 * @throws BaseException
	 */
	public static int convertLoginNameToUserType( String loginName ) throws BaseException {
		int rValue = 0 ;
		
		if( StringUtil.isNotBlank(loginName) ) {
			Object obj = getInitInfos(loginName, TableStatus.BASE_DATA_TYPE_01) ;
			if( StringUtil.isNotBlank( obj ) ) {
				Users users = (Users) obj ;
					rValue = users.getUserType();
			}
		}

		return rValue ;
	}
	/**
	 * 根据用户英文名取用户的部门信息
	 * @param departName 用户登录名
	 * @return 用户中文名
	 * @throws BaseException
	 */
	public static String convertDepartNameToChnName( String loginName ) throws BaseException {
		String rValue = "" ;
		
		if( StringUtil.isNotBlank(loginName) ) {
			Object obj = getInitInfos(loginName, TableStatus.BASE_DATA_TYPE_01) ;
			if( StringUtil.isNotBlank( obj ) ) {
				Users users = (Users) obj ;
				rValue=convertDeptIdToName(users.getDepId());
			}
		}

		return rValue ;
	}
	/**
	 * 取用户中文名
	 * @param loginName 用户登录名(英文)
	 * @return 用户中文名
	 * @throws BaseException
	 */
	public static String convertLoginNameToUserId( String loginName ) throws BaseException {
		String rValue="";
		
		if( StringUtil.isNotBlank(loginName) ) {
			Object obj = getInitInfos(loginName, TableStatus.BASE_DATA_TYPE_01) ;
			if( StringUtil.isNotBlank( obj ) ) {
				Users users = (Users) obj ;
				if( StringUtil.isNotBlank( users.getUserId() ) ) {
					rValue = users.getUserId().toString();
				}
			}
		}

		return rValue ;
	}
	
	/**
	 * 取用户部门中文名
	 * @param deptId 部门Id(主键)
	 * @return 部门中文名
	 * @throws BaseException
	 */
	public static String convertDeptIdToName( Long deptId ) throws BaseException {
		String rValue = "" ;
		
		if( StringUtil.isNotBlank(deptId) ) {
			Object obj = getInitInfos(deptId, TableStatus.BASE_DATA_TYPE_02) ;
			if( StringUtil.isNotBlank( obj ) ) {
				Departments dept = (Departments) obj ;
				if( StringUtil.isNotBlank( dept.getDeptName() ) ) {
					rValue = dept.getDeptName() ;
				}
			} 
		}
		
		return rValue ;
	}
	
	/**
	 * 取字典表编码对应中文名称 
	 * @param dictCode 字典表编码, 如01
	 * @param dictType 字典表类型, 如1700
	 * @return 字典表编码中文名称
	 * @throws BaseException
	 */
	public static String convertDictCodeToName( String dictCode, String dictType ) throws BaseException {
		String rValue = "" ;
		Dictionary dict = null ;
		
		if( StringUtil.isNotBlank(dictType ) && StringUtil.isNotBlank(dictCode ) ) {
			Object obj = getInitInfos(dictType, TableStatus.BASE_DATA_TYPE_03) ;
			if( StringUtil.isNotBlank( obj ) ) {
				List<Dictionary> dictList = (List<Dictionary>) obj ;
				for( int i=0; i<dictList.size(); i++ ) {
					dict = dictList.get(i) ;
					if( dictCode.equals( dict.getDictCode() ) ) {
						rValue = dict.getDictName() ;
						break ;
					}
				}
			} 
		}
		
		return rValue ;
	}
	
	/**
	 * 取字典表信息数据, 以Map形式(key=dictCode, value=dictName)显示
	 * @param dictType 字典表类型
	 * @return 字典表信息
	 * @throws BaseException
	 */
	public static Map getDictInfoToMap( String dictType ) throws BaseException {
		Map rValue = new TreeMap() ;
		
		if( StringUtil.isNotBlank(dictType ) ) {
			Object obj = getInitInfos(dictType, TableStatus.BASE_DATA_TYPE_03) ;
			if( StringUtil.isNotBlank( obj ) ) {
				List<Dictionary> dictList = (List<Dictionary>) obj ;
				for( Dictionary tdict : dictList ) {
					rValue.put(tdict.getDictCode(), tdict.getDictName() ) ;
				}
			} 
		}
		
		return rValue ;
	}
	/**
	 * 取字典表信息数据, 以List形式显示
	 * @param dictType 字典表类型
	 * @return 字典表信息
	 * @throws BaseException
	 */
	public static List<Dictionary> getDictInfoToList( String dictType ) throws BaseException {
		
		List<Dictionary> dictList=null;
		if( StringUtil.isNotBlank(dictType ) ) {
			Object obj = getInitInfos(dictType, TableStatus.BASE_DATA_TYPE_03) ;
			if( StringUtil.isNotBlank( obj ) ) {
				dictList = (List<Dictionary>) obj ;
				
			} 
		}
		
		return dictList ;
	}
	
	/**
	 * 如果对user表进行操作，则需要同时对缓存数据进行操作
	 * @return 字典表信息
	 * @throws BaseException
	 */
	public static void updateUserCache(String opertype,Users users) throws BaseException {
		
			if(opertype.equals("save")){

				iCacheInfoBiz.addCache(users.getUserId(), TableStatus.BASE_DATA_TYPE_01,users);

				iCacheInfoBiz.addCache(users.getUserName(), TableStatus.BASE_DATA_TYPE_01,users);
			}else if(opertype.equals("update")){
				iCacheInfoBiz.updateCache(users.getUserId(), TableStatus.BASE_DATA_TYPE_01,users);

				iCacheInfoBiz.updateCache(users.getUserName(), TableStatus.BASE_DATA_TYPE_01,users);
			}else if(opertype.equals("delete")){
				
				iCacheInfoBiz.removeCache(users.getUserId(), TableStatus.BASE_DATA_TYPE_01);

				iCacheInfoBiz.removeCache(users.getUserName(), TableStatus.BASE_DATA_TYPE_01);
			}
		
	}
	/**
	 * 如果对Depments表进行操作，则需要同时对缓存数据进行操作
	 * @return 字典表信息
	 * @throws BaseException
	 */
	public static void updateDepmengtCache(String opertype,Departments departments) throws BaseException {
		
			if(opertype.equals("save")){
				iCacheInfoBiz.addCache(departments.getDepId(), TableStatus.BASE_DATA_TYPE_02,departments);
			}else if(opertype.equals("update")){
				iCacheInfoBiz.updateCache(departments.getDepId(), TableStatus.BASE_DATA_TYPE_02,departments);
			}else if(opertype.equals("delete")){
				iCacheInfoBiz.removeCache(departments.getDepId(), TableStatus.BASE_DATA_TYPE_02);
			}
	}
	/**
	 * 如果对SystemConfiguration表进行操作，则需要同时对缓存数据进行操作
	 * @return 系统配置表信息
	 * @throws BaseException
	 */
	public static void updateSystemConfigurationCache(String opertype,SystemConfiguration systemConfiguration) throws BaseException {
		
			if(opertype.equals("save")){
				iCacheInfoBiz.addCache(systemConfiguration.getComId(), TableStatus.BASE_DATA_TYPE_04,systemConfiguration);
			}else if(opertype.equals("update")){
				iCacheInfoBiz.updateCache(systemConfiguration.getComId(), TableStatus.BASE_DATA_TYPE_04,systemConfiguration);
			}
	}
	/**
	 * 取字典表编码对应资料模板页面 
	 * @param dictCode 字典表编码, 如01
	 * @param dictType 字典表类型, 如1706
	 * @return 字典表编码中文名称
	 * @throws BaseException
	 */
	public static String convertDictCodeToUrlpage( String dictCode, String dictType ) throws BaseException {
		String rValue = "" ;
		Dictionary dict = null ;
		
		if( StringUtil.isNotBlank(dictType ) && StringUtil.isNotBlank(dictCode ) ) {
			Object obj = getInitInfos(dictType, TableStatus.BASE_DATA_TYPE_03) ;
			if( StringUtil.isNotBlank( obj ) ) {
				List<Dictionary> dictList = (List<Dictionary>) obj ;
				for( int i=0; i<dictList.size(); i++ ) {
					dict = dictList.get(i) ;
					if( dictCode.equals( dict.getDictCode() ) ) {
						rValue = dict.getDictName() ;
						break ;
					}
				}
			} 
		}
		
		return rValue ;
	}

	/**
	 * 取系统配置表信息
	 * @param comId 采购单位Id
	 * @return 采购单位系统配置信息
	 * @throws BaseException
	 */
	public static SystemConfiguration convertSystemConfiguration( Long comId) throws BaseException {
		SystemConfiguration systemConfiguration = null;		
		if( StringUtil.isNotBlank(comId ) && StringUtil.isNotBlank(comId ) ) {
			systemConfiguration=(SystemConfiguration)getInitInfos(comId, TableStatus.BASE_DATA_TYPE_04) ;
		}
		if(systemConfiguration==null) systemConfiguration=new SystemConfiguration() ;
		return systemConfiguration ;
	}
	/**
	 * 取基础信息 ,如 keyValue=userId, initName=usersCache, 返回值为整个Users对象实例
	 * @param keyValue 主键ID
	 * @param initName 基础信息
	 * @return
	 * @throws BaseException
	 */
	public static Object  getInitInfos( Object keyValue, Object initName) throws BaseException {
        return iCacheInfoBiz.convertCacheInfoToMap(keyValue, initName).get( keyValue )  ;
	}
	
	/**
	 * 取基础信息中的所有信息, 如initName=usersCache, 返回值为所有的用户信息
	 * @param vInit true  从数据库重新装载 false 从内存装载
	 * @param initName 基础信息
	 * @return
	 * @throws BaseException
	 */
	public static List getAllInitInfos( boolean vInit, String initName) throws BaseException {
		List gList = new ArrayList();
		if (vInit || getBaseIndexInfoSize(initName) == 0) {
        	
            // 取得所有数据
            gList = initBaseIndexInfos( initName ) ;
            
        } else {
        	gList= iCacheInfoBiz.convertCacheInfoToList(initName) ;
        }

		return gList ;
	}
	
	/**
	 * 初始化基础数据同步到缓存, 重新加载缓存
	 * @param initType 同步类型 
	 * @return
	 * @throws BaseException 
	 */
	public static List initBaseIndexInfos( String initType ) throws BaseException{
		return iCacheInfoBiz.initCacheInfos( initType ) ;
	}
	
	/**
	 * 取基础信息的数量
	 * @param cacheName 基础信息类型 
	 * @return
	 */
	public static int getBaseIndexInfoSize( String cacheName ) {
		return iCacheInfoBiz.getCacheInfoSize( cacheName ) ;
	}
	
	private static void initBaseData( ) throws BaseException {
		initBaseIndexInfos( TableStatus.BASE_DATA_TYPE_01 );
		initBaseIndexInfos( TableStatus.BASE_DATA_TYPE_02 );
		initBaseIndexInfos( TableStatus.BASE_DATA_TYPE_03 );
		initBaseIndexInfos( TableStatus.BASE_DATA_TYPE_04 );
	}
	
	private static ICacheInfoBiz iCacheInfoBiz ;
	
	public static ICacheInfoBiz getICacheInfoBiz() {
		return iCacheInfoBiz;
	}

	public static boolean setICacheInfoBiz(ICacheInfoBiz cacheInfoBiz) throws BaseException {
		iCacheInfoBiz = cacheInfoBiz;
		initBaseData ( );
		return true; 
	}
	
	/**
	 * 获取采购方式中文名
	 * @param buyWay 采购方式编码
	 * @author luguanglei 2016-09-10
	 * @return
	 * @throws PersistenceException
	 */
	public static String convertBuyWayToBuyType(String buyWay){
		String buyWayCn = "";
		if("00".equals(buyWay)){buyWayCn = "招标";}
		if("01".equals(buyWay)){buyWayCn = "询价";}
		if("02".equals(buyWay)){buyWayCn = "竞价";}
		if("08".equals(buyWay)){buyWayCn = "自主采购";}
		return buyWayCn;
	}
	/**
	 * 获取供应商选择方式中文名
	 * @param supplierType 供应商选择方式编码
	 * @author luguanglei 2016-09-10
	 * @return
	 * @throws PersistenceException
	 */
	public static String convertSupplierTypeCnTosupplierType(String supplierType){
		String supplierTypeCn = "";
		if("00".equals(supplierType)){supplierTypeCn = "公开";}
		if("01".equals(supplierType)){supplierTypeCn = "邀请";}
		return supplierTypeCn;
	}
	/**
	 * 获取采购异常类别中文名
	 * @param buyType 采购方式编码
	 * @author luguanglei 2016-09-10
	 * @return
	 * @throws PersistenceException
	 */
	public static String convertAbnomalTypeToAbnomalType(String AbnomalType){
		String buytypeCn = "";
		if("2".equals(AbnomalType)){buytypeCn = TableStatus.BID_STATUS_2_TEXT;}
		if("3".equals(AbnomalType)){buytypeCn = TableStatus.BID_STATUS_3_TEXT;}
		if("4".equals(AbnomalType)){buytypeCn = TableStatus.BID_STATUS_4_TEXT;}
		if("5".equals(AbnomalType)){buytypeCn = TableStatus.BID_STATUS_5_TEXT;}
		return buytypeCn;
	}
	
	/**
	 * 获取评标类别中文名
	 * @param 评标类别编码
	 * @author luguanglei 2016-09-10
	 * @return
	 * @throws PersistenceException
	 */
	public static String convertBidKindToItemType(String ItemType){
		String ItemTypeCn = "";
		if("0".equals(ItemType)){ItemTypeCn = "技术";}
		if("1".equals(ItemType)){ItemTypeCn = "商务";}
		if("2".equals(ItemType)){ItemTypeCn = "综合";}
		return ItemTypeCn;
	}
	
	/**
	 * 获取评标价格规则中文名
	 * @param 评标价格类别编码
	 * @author luguanglei 2016-09-10
	 * @return
	 * @throws PersistenceException
	 */
	public static String convertBidPriceTypeToChinese(String ItemType){
		String ItemTypeCn = "";
		if("01".equals(ItemType)){ItemTypeCn = "最低价满分";}
		if("02".equals(ItemType)){ItemTypeCn = "平均价满分";}
		if("03".equals(ItemType)){ItemTypeCn = "最高价满分";}
		return ItemTypeCn;
	}
	
	/**
	 * 获取计划类型中文名
	 * @param 计划类型编码
	 * @author luguanglei 2016-09-10
	 * @return
	 * @throws PersistenceException
	 */
	public static String convertPurchKindType(String ItemType){
		String ItemTypeCn = "";
		if(StringUtil.isNotBlank(ItemType)){
			if("00".equals(ItemType)){ItemTypeCn = "普通计划";}
			if("01".equals(ItemType)){ItemTypeCn = "加急计划";}
		}
		return ItemTypeCn;
	}
	
	/**
	 * 获取供应商要求符合中文名
	 * @param 评标类别编码
	 * @author luguanglei 2016-09-10
	 * @return
	 * @throws PersistenceException
	 */
	public static String supplierToItemType(String ItemType){
		String ItemTypeCn = "";
		if("0".equals(ItemType)){ItemTypeCn = "超出预期需求";}
		if("1".equals(ItemType)){ItemTypeCn = "完全符合";}
		if("2".equals(ItemType)){ItemTypeCn = "基本符合 ";}
		if("3".equals(ItemType)){ItemTypeCn = "有不足项  ";}
		return ItemTypeCn;
	}
    
    /**
    * 汉字转拼音的方法
    * @param name 汉字
    * @return 拼音
    * @author Ushine,2016-11-05
    */
    public static String HanyuToPinyin(String name){
    	String pinyinName = "";
        char[] nameChar = name.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < nameChar.length; i++) {
            if (nameChar[i] > 128) {
                try {
                    pinyinName += PinyinHelper.toHanyuPinyinStringArray
                                           (nameChar[i], defaultFormat)[0];
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } 
        }
        return pinyinName;
    }
    

    //判断字符串是否仅为数字:用正则表达式
    public static boolean isNumeric(String str){

        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();   

     }    
    /**
	 * 获取供应商考核等级
	 * @param 评标类别编码
	 * @author luguanglei 2016-09-10
	 * @return
	 * @throws PersistenceException
	 */
	public static String getDifferentRankByPoints(Double points){
		String Rank = "";
		if(points>=90){Rank = "A级";}
		if(points>=80&&points<90){Rank = "B级";}
		if(points>=70&&points<80){Rank = "C级";}
		if(points<70){Rank = "D级";}
		return Rank;
	}
	
	/**
	 * 生成UUID
	 */
	public static String generateUUID(){ 
		UUID uuid = UUID.randomUUID(); 
		return uuid.toString().replace("-", ""); 
	} 

}
