package com.goafanti.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;


public class FileUtils {
	@Value(value = "${upload.private.path}")
	private String					uploadPrivatePath	= null;

	private static final Pattern	SLASH_PATTERN		= Pattern.compile("^/|/$");
	private static final String		SLASH				= "/";
	private static final String		UNDERLINE			= "_";

	/**
	 * response 输出JSON
	 * 
	 * @param hresponse
	 * @param resultMap
	 * @throws IOException
	 */
	public static void out(HttpServletResponse response, String jsonStr) {
		PrintWriter out = null;
		try {
			response.setHeader("Content-Type", "application/json");
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
			out.println(jsonStr);
		} catch (Exception e) {
			LoggerUtils.fmtError(FileUtils.class, e, "输出数据失败");
		} finally {
			if (null != out) {
				out.flush();
				out.close();
			}
		}
	}

	/**
	 * Excel报表导出
	 * 
	 * @param response
	 * @param fileName
	 * @param workbook
	 */
	public static void downloadExcel(HttpServletResponse response, String fileName, HSSFWorkbook workbook) {
		String fn = null;
		try {
			fn = URLEncoder.encode(fileName, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			fn = fileName;
		}
		response.setContentType("application/x-download;charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment; filename=\"" + fn + "\";");
		OutputStream out = null;
		try {
			out = response.getOutputStream();
			workbook.write(out);
		} catch (IOException e) {
			LoggerUtils.fmtError(FileUtils.class, e, "输出Excel失败");
		} finally {
			if (null != out) {
				try {
					out.flush();
					out.close();
				} catch (IOException e) {
					out = null;
				}
			}
		}
	}

	/**
	 * 根据上传文件 拼接fileName
	 * 
	 * @param mf
	 * @param isPrivate
	 * @param sign
	 * @param path
	 * @return
	 */
	public static String mosaicFileName(MultipartFile mf, boolean isPrivate, String sign, String path, String uid) {
		String suffix = mf.getOriginalFilename().substring(mf.getOriginalFilename().lastIndexOf("."));
		boolean uniq = false;
		if (sign.indexOf("demand_picture") != -1|| sign.indexOf("achievement_picture") != -1 || sign.indexOf("user_picture")!=-1
				|| sign.indexOf("jt_project_picture")!=-1 || sign.indexOf("jt_business_picture")!=-1 || sign.indexOf("honor_picture")!=-1
				|| sign.indexOf("banners")!=-1|| sign.indexOf("head_portrait")!=-1 || sign.indexOf("video")!=-1 ) {
			uniq = true;
		}
		String fileName = "";
		if (isPrivate || StringUtils.isNotBlank(sign)) {
			if (uniq) {
				fileName = path + uid + "/" + System.nanoTime() + "_" + sign + suffix;
			} else {
				fileName = path + uid + "/" +  sign + suffix;
			}
		} else {
			fileName = path + uid + "/" + System.nanoTime() + suffix;
		}
		return fileName;
	}
	
	public static String mosaicFileName( String fn, boolean isPrivate, String path, String uid) {
		String fileName = "";
		if (isPrivate) {
			fileName = path + uid + "/" + fn;
		} else {
			fileName = path + uid + "/" + "logo"  + fn ;
		}
		return fileName;
	}

	/**
	 * 获取下载文件名称
	 * 
	 * @param path
	 * @return
	 */
	public static String getDownloadFileName(String path) {
		if (StringUtils.isBlank(path) || path.lastIndexOf(".") < 0) {
			return null;
		}
		String prefix = "附件";
		String suffix = path.substring(path.lastIndexOf("."));
		return prefix + suffix;
	}

	public static String getSuffix(String path) {
		if (StringUtils.isBlank(path) || path.lastIndexOf(".") < 0) {
			return "";
		}
		return path.substring(path.lastIndexOf("."));
	}

	/**
	 * 拼接文件路径
	 * 
	 * @param root
	 * @param params
	 * @return
	 */
	public static String buildFilePath(String... params) {
		StringBuilder sb = new StringBuilder();
		if (params != null) {
			for (String s : params) {
				sb.append(SLASH);
				sb.append(SLASH_PATTERN.matcher(s).replaceAll(""));
			}
		}
		return sb.toString();
	}

	/**
	 * 拼接文件名字
	 * 
	 * @param root
	 * @param params
	 * @return
	 */
	public static String buildFileName(String... params) {
		return StringUtils.join(params, UNDERLINE);
	}

	// year
	private static String subStr(String s) {
		return "企业" + s.substring(s.lastIndexOf(UNDERLINE) + 1, s.lastIndexOf("."));
	}

	public static boolean deleteFile(String realFilePath) {
		return new File(realFilePath).delete();
	}

	/**
	 * 
	 * @param response
	 * @param fileName
	 * @param realFilePath
	 */
	public static void downloadFile(HttpServletResponse response, String fileName, String realFilePath) {
		InputStream in = null;
		OutputStream out = null;
		byte[] buffer = new byte[8 * 1024];
		try {
			File file = new File(realFilePath);
			in = new FileInputStream(file);
			out = response.getOutputStream();
			// 设置文件MIME类型
			response.setContentType("application/octet-stream");
			fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
			response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
			response.setHeader("Content-Length", String.valueOf(file.length()));
			for (;;) {
				int bytes = in.read(buffer);
				if (bytes == -1) {
					break;
				}
				out.write(buffer, 0, bytes);
			}
		} catch (IOException e) {
			LoggerUtils.fmtError(FileUtils.class, e, "IO错误：%s", e.getMessage());
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				in = null;
				LoggerUtils.fmtError(FileUtils.class, e, "IO错误：%s", e.getMessage());
			}
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				out = null;
				LoggerUtils.fmtError(FileUtils.class, e, "IO错误：%s", e.getMessage());
			}
		}
	}

}
