package com.qmth.qrzk.repository.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.commons.CommonsMultipartFile;

public class FileTool {

	/**
	 * 复制整个文件夹内容
	 * 
	 * @param oldPath
	 *            String 原文件路径 如：c:/fqf
	 * @param newPath
	 *            String 复制后路径 如：f:/fqf/ff
	 * @return boolean
	 */
	public static void copyFolder(String oldPath, String newPath) {
		try {
			(new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
			File a = new File(oldPath);
			String[] file = a.list();
			File temp = null;
			for (int i = 0; i < file.length; i++) {
				if (oldPath.endsWith(File.separator)) {
					temp = new File(oldPath + file[i]);
				} else {
					temp = new File(oldPath + File.separator + file[i]);
				}
				if (temp.isFile()) {
					FileInputStream input = new FileInputStream(temp);
					FileOutputStream output = new FileOutputStream(newPath
							+ "/" + (temp.getName()).toString());
					byte[] b = new byte[1024 * 5];
					int len;
					while ((len = input.read(b)) != -1) {
						output.write(b, 0, len);
					}
					output.flush();
					output.close();
					input.close();
				}
				if (temp.isDirectory()) {// 如果是子文件夹
					copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
				}
			}
		} catch (Exception e) {
			System.out.println("复制整个文件夹内容操作出错");
			e.printStackTrace();
		}
	}

	public static void showAllFiles(List<String> list, File dir) {
		File[] fs = dir.listFiles();
		for (int i = 0; i < fs.length; i++) {
			if (fs[i].isDirectory()) {
				showAllFiles(list, fs[i]);
			} else {
				list.add(fs[i].getAbsolutePath());
			}
		}
	}

	/**
	 * 复制单个文件 2014年9月17日
	 * 
	 * @author 钟辉
	 * @description
	 * @param oldPath
	 *            需要复制文件路径
	 * @param newPath
	 *            复制到的文件路径
	 */
	public static void copyFile(String oldPath, String newPath, String fileName) {
		InputStream inStream = null;
		FileOutputStream fs = null;
		try {
			int byteread = 0;
			File oldfile = new File(oldPath);

			if (oldfile.exists()) { // 文件存在时
				inStream = new FileInputStream(oldPath); // 读入原文件
				File file = new File(newPath);
				if (!file.exists()) {
					file.mkdirs();
				}
				File ff = new File(newPath + fileName);
				if (!file.exists()) {
					file.createNewFile();
				}
				fs = new FileOutputStream(ff);
				byte[] buffer = new byte[2048];
				while ((byteread = inStream.read(buffer)) != -1) {
					fs.write(buffer, 0, byteread);
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inStream != null) {
				try {
					inStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (fs != null) {
				try {
					fs.flush();
					fs.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 上传后的数据写入磁盘 2014年9月17日
	 * 
	 * @author 钟辉
	 * @description
	 * @param file
	 *            上传文件
	 * @param path
	 *            文件路径
	 * @param name
	 *            文件名称
	 */
	public static void writeFile(CommonsMultipartFile file, String path,
			String name) {
		InputStream stream = null;
		OutputStream bos = null;
		try {
			String fileName = file.getOriginalFilename();

			stream = file.getInputStream();

			fileName = new String(fileName.getBytes(), "utf-8");
			File ff = new File(path);
			if (!ff.exists()) {
				ff.mkdirs();
			}
			bos = new FileOutputStream(path + "/" + name);
			int bytesRead = 0;
			byte[] buffer = new byte[2048];
			while ((bytesRead = stream.read(buffer, 0, 2048)) != -1) {
				bos.write(buffer, 0, bytesRead);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (bos != null) {
				try {
					bos.flush();
					bos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public static boolean deletefile(String delpath) {
		try {
			File file = new File(delpath);
			// 当且仅当此抽象路径名表示的文件存在且 是一个目录时，返回 true
			if (!file.isDirectory()) {
				file.delete();
			} else if (file.isDirectory()) {
				String[] filelist = file.list();
				for (int i = 0; i < filelist.length; i++) {
					File delfile = new File(delpath + "\\" + filelist[i]);
					if (!delfile.isDirectory()) {
						delfile.delete();
					} else if (delfile.isDirectory()) {
						deletefile(delpath + "\\" + filelist[i]);
					}
				}
				file.delete();
			}

		} catch (Exception e) {
			System.out.println("deletefile() Exception:" + e.getMessage());
		}
		return true;
	}

	// 删除指定文件夹下所有文件
	// param path 文件夹完整绝对路径
	public static boolean delAllFile(String path) {
		boolean flag = false;
		File file = new File(path);
		if (!file.exists()) {
			return flag;
		}
		if (!file.isDirectory()) {
			return flag;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);// 再删除空文件夹
				flag = true;
			}
		}
		return flag;
	}

	// 删除文件夹
	// param folderPath 文件夹完整绝对路径

	public static void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			myFilePath.delete(); // 删除空文件夹
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String getAppPath() {
		// 获得应用程序路径
		URL appUrl = FileTool.class.getClassLoader().getResource("");
		String appPath = appUrl.getPath();

		if (WINDOWS && appPath.startsWith("/"))
			appPath = appPath.substring(1);

		try {
			appPath = URLDecoder.decode(appPath, "UTF-8");
			// appPath = System.getProperty("user.dir");
		} catch (UnsupportedEncodingException e) {
		}

		return appPath;
	}

	public static void downLoad(HttpServletResponse response,String fileName){
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			File file = new File(fileName);
			
			response.setContentType("application/x-download");// 设置为下载application/x-download
			String filedisplay = file.getName();// 下载文件时显示的文件保存名称
			String filenamedisplay = URLEncoder.encode(filedisplay, "UTF-8");
			response.addHeader("Content-Disposition", "attachment;filename="+ filenamedisplay);

			bis = new BufferedInputStream(new FileInputStream(file));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[4096];
			int bytesRead;
			while (-1 != (bytesRead = (bis.read(buff, 0, buff.length)))) {
				bos.write(buff, 0, bytesRead);
			}
			bos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void downLoad(HttpServletResponse response,String downPath,String fileName){
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			response.setContentType("application/x-download");// 设置为下载application/x-download
			String filedownload = downPath;// 即将下载的文件的相对路径
			String filedisplay = fileName;// 下载文件时显示的文件保存名称
			String filenamedisplay = URLEncoder.encode(filedisplay, "UTF-8");
			response.addHeader("Content-Disposition", "attachment;filename="+ filenamedisplay);

			bis = new BufferedInputStream(new FileInputStream(filedownload+ "/" + fileName));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[4096];
			int bytesRead;
			while (-1 != (bytesRead = (bis.read(buff, 0, buff.length)))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			File ff = new File(downPath+fileName);
			if (ff.exists()) {
				ff.delete();
			}
		}
	}
	
	public static void main(String[] args) {
		String ss="00032140901A";
		List<String> ls=new ArrayList<String>();
		ls.add("00032140901A");
		ls.add("aaaaaabbbbbb");
		for(String s:ls){
			System.out.println(ls.contains(ss));
		}
	}
	
	private static final boolean WINDOWS = System.getProperty("os.name")
			.startsWith("Windows");
}
