package com.zzsn.knowbase.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author yanxin
 */
@Slf4j
public class LoadToolUtil {
	/**
	 * 中文字符和中文引号
	 */
	private static Pattern decodePattern = Pattern.compile("[\u4e00-\u9fa5“”]+");
	public static List<String> readFiletoList(String fileName){
		List<String> list = new ArrayList<>();
		BufferedReader br = null;
		try{
			 br = new BufferedReader(new FileReader(fileName));
			 String contentLine ;
			 while ((contentLine = br.readLine()) != null) {
	             if(StringUtils.isNotEmpty(contentLine)){
	            	 contentLine = contentLine.trim();
	            	 list.add(contentLine);
	             }
	         }
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(br != null){
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return list;
	}
	
	public static boolean judegExcelEdition(String fileName) {
		String regex = "^.+\\.(?i)(xls)$";
		return !fileName.matches(regex);
	}
	
	/**
	 * 找到文件的扩展名
	 */
	public static String getFileSuffix(String fileName) {
		// TODO Auto-generated method stub
		if(fileName == null || StringUtils.isEmpty(fileName) ){
			return null;
		}
		String suffix = "";
		String indexOf = ".";
		if(fileName.lastIndexOf(indexOf) > -1){
			suffix = fileName.substring(fileName.lastIndexOf("."));
		}
		return suffix;
	}
	/**
	 * 获取参数编码后的url
	 */
	public static String urlEncoder(String url) {
		try {
			Matcher m = decodePattern.matcher(url);
			StringBuffer b = new StringBuffer();
			while (m.find()) {
				m.appendReplacement(b, URLEncoder.encode(m.group(0), "utf-8"));
			}
			m.appendTail(b);
			url = b.toString();
			url = url.replace("&amp;", "&");
		} catch (Exception e) {
			log.error("url编码转换失败e:{}",e.getMessage());
		}
		return url;
	}
	/**
	 * 获取相对路径，不带第一个/
	 */
	public static String urlEncoderRelative(String url) {
		url = urlEncoder(url);
		if(url.startsWith("/")){
			url = url.substring(1);
		}
		return url;
	}

}
