package com.goafanti.common.utils;

import com.goafanti.common.enums.AttachmentType;
import com.goafanti.common.error.BusinessException;
import com.mchange.v1.io.InputStreamUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.regex.Pattern;

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
	 *
	 * @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("protocol") != -1 || sign.indexOf("achievement") != -1 || sign.indexOf("honor") != -1
				|| sign.indexOf("proof") != -1 || sign.indexOf("activity_cost_account") != -1
				|| sign.indexOf("tech_product") != -1 || sign.indexOf("property_ritht") != -1
				|| sign.indexOf("tech_project") != -1 || sign.indexOf("patent_prory_statement") != -1
				|| sign.indexOf("patent_writing") != -1 || sign.indexOf("authorization_notice") != -1
				|| sign.indexOf("patent_certificate") != -1 || sign.indexOf("standard") != -1
				|| sign.indexOf("demand_picture") != -1 || sign.indexOf("demand_text_file") != -1
				|| sign.indexOf("achievement_technical_picture") != -1|| sign.indexOf("order_file") != -1
				|| sign.indexOf("achievement_maturity_picture") != -1 || sign.indexOf("demand_order_file") != -1
				|| sign.indexOf("lecture_picture") != -1|| sign.indexOf("cover_picture") != -1
				|| sign.indexOf("news") != -1||sign.indexOf("customer_sys_file") != -1 || sign.indexOf("order_refund_file") != -1
				||sign.indexOf("business_project_max_picture") != -1||sign.indexOf("business_project_min_picture") != -1
				||sign.indexOf("varieties_picture") != -1  || sign.indexOf("organization_application") != -1
				||sign.indexOf("order_task_file") != -1||sign.indexOf("patent_certificate") != -1
				||sign.indexOf("order_invoice_file") != -1 ||sign.indexOf("order_outsource") != -1|| sign.indexOf("dun_log_attachment") != -1||
				sign.indexOf("legal_log_attachment") != -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;
	}

	/**
	 * 根据上传文件 拼接fileName
	 *
	 * @param mf
	 * @param isPrivate
	 * @param sign
	 * @param path
	 * @return
	 */
	public static String splicingFileName(MultipartFile mf, boolean isPrivate, String sign, String path, String uid) {
		String suffix = mf.getOriginalFilename().substring(mf.getOriginalFilename().lastIndexOf("."));
		boolean uniq = false;
		if (sign!= null ){
			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;
	}

	/**
	 * 根据上传文件 拼接fileName
	 *
	 * @param mf
	 * @param sign
	 * @param path
	 * @return
	 */
	public static String orderFileName(MultipartFile mf, String id, String path,String sign) {
		String suffix = mf.getOriginalFilename().substring(mf.getOriginalFilename().lastIndexOf("."));
		String fileName =  path + id + "/" + System.nanoTime()+"_"+sign + suffix;
		return fileName;
	}

	public static String orderFileName(MultipartFile mf, String path,String sign) {
		String suffix = mf.getOriginalFilename().substring(mf.getOriginalFilename().lastIndexOf("."));
		String fileName =  path + sign + "/" + System.nanoTime()+"_"+sign + suffix;
		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("."));
		if (path.indexOf(AttachmentType.PATENT_PRORY_STATEMENT.getCode()) != -1) {
			prefix = "专利代理委托书";
		} else if (path.indexOf(AttachmentType.PATENT_WRITING.getCode()) != -1) {
			prefix = "专利稿件";
		} else if (path.indexOf(AttachmentType.AUTHORIZATION_NOTICE.getCode()) != -1) {
			prefix = "授权通知书";
		} else if (path.indexOf(AttachmentType.PATENT_CERTIFICATE.getCode()) != -1) {
			prefix = "专利证书";
		} else if (path.indexOf(AttachmentType.PROOF.getCode()) != -1) {
			prefix = "立项证明材料";
		} else if (path.indexOf(AttachmentType.ACTIVITY_COST_ACCOUNT.getCode()) != -1) {
			prefix = "研发活动费用台帐";
		} else if (path.indexOf(AttachmentType.TECH_PRODUCT.getCode()) != -1) {
			prefix = "高新技术产品台帐";
		} else if (path.indexOf(AttachmentType.PROPERTY_RIGHT.getCode()) != -1) {
			prefix = "知识产权证书";
		} else if (path.indexOf(AttachmentType.ROSTER.getCode()) != -1) {
			prefix = subStr(path) + "花名册";
		} else if (path.indexOf(AttachmentType.SOCIAL_SECURITY.getCode()) != -1) {
			prefix = subStr(path) + "社保情况";
		} else if (path.indexOf(AttachmentType.HONOR.getCode()) != -1) {
			prefix = "荣誉材料证明";
		} else if (path.indexOf(AttachmentType.ACHIEVEMENT.getCode()) != -1) {
			prefix = "科技成果附件";
		} else if (path.indexOf(AttachmentType.INSTITUTION.getCode()) != -1) {
			prefix = "制度目录";
		} else if (path.indexOf(AttachmentType.PROTOCOL.getCode()) != -1) {
			prefix = "技术协议";
		} else if (path.indexOf(AttachmentType.FINANCE.getCode()) != -1) {
			prefix = subStr(path) + "财务报表";
		} else if (path.indexOf(AttachmentType.RATEPAY.getCode()) != -1) {
			prefix = subStr(path) + "纳税申报表";
		} else if (path.indexOf(AttachmentType.TECH_PROJECT.getCode()) != -1) {
			prefix = "科技项目资料";
		} else if (path.indexOf(AttachmentType.STANDARD.getCode()) != -1) {
			prefix = "标准制定";
		} else if (path.indexOf(AttachmentType.MANUSCRIPT.getCode()) != -1) {
			prefix = "稿件";
		} else if (path.indexOf(AttachmentType.DEMAND_TEXT_FILE.getCode()) != -1) {
			prefix = "科技需求文本文件资料";
		} else if (path.indexOf(AttachmentType.ACHIEVEMENT_MATURITY_TEXT_FILE.getCode()) != -1) {
			prefix = "科技成果成熟度资料文本文件";
		} else if (path.indexOf(AttachmentType.ACHIEVEMENT_TECH_PLAN.getCode()) != -1) {
			prefix = "科技成果技术方案文件";
		} else if (path.indexOf(AttachmentType.ACHIEVEMENT_BUSINESS_PLAN.getCode()) != -1) {
			prefix = "科技成果商业计划书";
		}

		return prefix + suffix;
	}

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

	/**
	 * 拼接文件路径
	 *
	 * @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 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 {
			if(!com.goafanti.common.utils.excel.FileUtils.checkAllowDownload(realFilePath)){
                throw new BusinessException("文件名称非法，不允许下载。 ");
            }
			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 (BusinessException e) {
			LoggerUtils.fmtError(FileUtils.class, e, "名称错误：%s", e.getMessage());
        } 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());
			}
		}
	}


	public static byte[] getBytes(File file) throws IOException {
		BufferedInputStream var1 = new BufferedInputStream(new FileInputStream(file));

		byte[] var2;
		try {
			var2 = InputStreamUtils.getBytes(var1);
		} finally {
			InputStreamUtils.attemptClose(var1);
		}

		return var2;
	}

}
