package com.uas.platform.b2b.core;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Random;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class BaseUtil implements ApplicationContextAware {
	private static ApplicationContext context;
	
//	目录结构： -SYSPATH(saas)
//			  	-PATH(WEB-INF)
//			  -FILEPATH(自定义附件目录)
	//系统class加载路径 WEB-INF目录
	public static String PATH;
	//系统目录，saas
	public static String SYSPATH;
	//系统的附件的路径，默认与项目同级
	public static String FILEPATH;

	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		context = applicationContext;
		setPath();
		setSysPath();
		setFilePath();
	}
	
	@SuppressWarnings({ "rawtypes", "static-access" })
	public static void setPath() {
		Class classes = context.getClass();
		String strRealPath = classes.getClassLoader().getResource("").getFile();
		try {
			strRealPath = URLDecoder.decode(strRealPath, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		File file = new File(strRealPath);
		BaseUtil.PATH = file.getParent() + file.separator;
		if(BaseUtil.PATH.contains("/")){
			BaseUtil.PATH = "/" + BaseUtil.PATH;
		}
	};
	
	@SuppressWarnings("static-access")
	public static void setSysPath() {
		if(BaseUtil.PATH != null) {
			File file = new File(BaseUtil.PATH);
			BaseUtil.SYSPATH = file.getParent() + file.separator;
		}
	}
	
	@SuppressWarnings("static-access")
	public static void setFilePath() {
		if(BaseUtil.SYSPATH != null) {
			File file = new File(BaseUtil.SYSPATH);
			BaseUtil.FILEPATH = file.getParent() + file.separator;
		}
	}

	/**
	 * 获得随机长度的字符串
	 * */
	public static String randomString(int length) {
		Random randGen = null;
		char[] numbersAndLetters = null;
		if (length < 1) {
			return null;
		}
		if (randGen == null) {
			randGen = new Random();
			numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz" + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
			// numbersAndLetters =
			// ("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
		}
		char[] randBuffer = new char[length];
		for (int i = 0; i < randBuffer.length; i++) {
			randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
		}
		return new String(randBuffer);
	}
}
