package cn.component.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import cn.config.SysConfig;
import cn.constant.CharsetKit;
import cn.util.core.IsKit;
import cn.util.core.TypeKit;
import cn.util.file.FileKit;
import cn.util.string.JsonKit;

@Component
public class FileService 
{
	@Autowired
	private SysConfig sysConfigService;

	/**构造文件名：上传的文件名名_基于时间的随机数.扩展名*/
	public String genFileName(MultipartFile mf)
	{
		String fileName;
		String orgName = mf.getOriginalFilename();// 获取文件名
		orgName = this.getFileName(orgName);
		if(orgName.indexOf(".")!=-1){
			fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
		}else{
			fileName = orgName+ "_" + System.currentTimeMillis();
		}
		return fileName;
	}
    /**
     * 判断文件名是否带盘符，重新处理
     * @param fileName
     */
    public String getFileName(String fileName)
    {
        //判断是否带有盘符信息
        // Check for Unix-style path
        int unixSep = fileName.lastIndexOf('/');
        // Check for Windows-style path
        int winSep = fileName.lastIndexOf('\\');
        // Cut off at latest possible point
        int pos = (winSep > unixSep ? winSep : unixSep);
        if (pos != -1)  {
            // Any sort of path separator found...
            fileName = fileName.substring(pos + 1);
        }
        //替换上传文件名字的特殊字符
        fileName = fileName.replace("=","").replace(",","").replace("&","").replace("#", "");
        return fileName;
    }
    /**
     *  把指定URL后的字符串全部截断当成参数
     *  这是为了防止URL中包含中文或者特殊字符（/等）时，匹配不了的问题
     * @param request
     * @return
     */
    public String extractPathFromPattern(final HttpServletRequest request)
    {
        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
    }

	/**
	 * @param photoByte
	 * @return
	 */
	public String getFileExtendName(byte[] photoByte) 
	{
		String strFileExtendName = "JPG";
		if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) && (photoByte[3] == 56) && ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97)) {
			strFileExtendName = "GIF";
		} else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70)) {
			strFileExtendName = "JPG";
		} else if ((photoByte[0] == 66) && (photoByte[1] == 77)) {
			strFileExtendName = "BMP";
		} else if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71)) {
			strFileExtendName = "PNG";
		}
		return strFileExtendName;
	}

    
	/* 解析wangeditor5编辑内容，获取图片文件
	 格式：
	 [{
	   type=paragraph, children=[
	    {text=}, {type=image, src=http://www.localhost:8080/news/2022081109202627410392773.jpg, href=, alt=, style={}, children=[{text=}]}, {text=}, 
	    {type=image, src=http://www.localhost:8080/news/2022081112121300810344357.jpg, href=, alt=, style={}, children=[{text=}]}, {text=}, 
	    {type=image, src=http://www.localhost:8080/news/2022081112121340056143822.jpg, href=, alt=, style={}, children=[{text=}]}, {text=}
	  ]
	  }]		  
	 */
	public List<String> getImgUrl(String htmlStr) 
	{
		List<String> pics = new ArrayList<>();
		if(IsKit.isNullOrEmpty(htmlStr)) {
			return pics;
		}
		List<Map<String, Object>> listMap = JsonKit.jsonToList_gson(htmlStr);
		if(IsKit.isNullOrEmpty(listMap)) {
			return pics;
		}
		for(int i = 0; i < listMap.size(); ++i) {
			Map<String, Object> tempMap = listMap.get(i);
			String type = TypeKit.objToStr(tempMap.get("type"));
			if("paragraph".equals(type)) {
				//(List<Map<String, Object>>)
				List<Map<String, Object>> tempListMap =	TypeKit.cast(tempMap.get("children"));
				if(IsKit.isNotNullOrEmpty(tempListMap)) 
				{
					for(int k = 0; k < tempListMap.size(); ++k)
					{
						Map<String, Object> inMap = tempListMap.get(k);
						String inType = TypeKit.objToStr(inMap.get("type"));
						if("image".equals(inType)) {
							String src = TypeKit.objToStr(inMap.get("src"));
							if(IsKit.isNotNullOrEmpty(src)) {
								pics.add(src);	
							}
						}
					}
				}
			}
		}  
		return pics;
	}
	/**依据传入目录标识dirPath与拟删除的文件路径进行删除，
	 * 返回成功删除的文件数量
	 */
	public int deleteFiles(String dirPath,List<String> paths)
	{
		int num = 0;
		String dirName = "news";
		if(IsKit.isNotNull(dirPath)) {
			dirName = dirPath;
		}
		int pathLength = dirName.length();
		String filePath = getFileFullPath(dirName);
		for (String str : paths) {
			/**
			 * 如果文件含有:http://www.localhost:8080/news/2022081112121340056143822.jpg
			 * 则只需返回：2022081112121340056143822.jpg 部分。此情况主要是应对：
			 * wangeditor编辑内容所含的图片
			 * indexOf返回-1，表示没有查找到.
			*/
			String fileName = str.indexOf(dirName) == -1? str : 
				str.substring(str.lastIndexOf(dirName)+pathLength,str.length());	
			if(FileKit.delFile(filePath + fileName)) {
				++num;
			}
		}
		return num;
	}
	public int deleteFile(String dirPath,String fileName)
	{
		int num = 0;
		String dirName = "temp";
		if(IsKit.isNotNull(dirPath)) {
			dirName = dirPath;
		}
		String filePath = getFileFullPath(dirName);
		if(FileKit.delFile(filePath + fileName)) {
			++num;
		}
		return num;
	}
	/**依据传入目录标识dirPath与拟删除的文件路径进行删除，
	 * 返回成功删除的文件数量
	 */
	public int deleteFiles(String dirPath,String filePrefix,List<String> fileName)
	{
		int num = 0;
		String dirName = "news";
		if(IsKit.isNotNull(dirPath)) {
			dirName = dirPath;
		}
		int pathLength = dirName.length();
		String filePath = getFileFullPath(dirName);
		for (String str : fileName) {
		
			String tempFileName = str.indexOf(dirName) == -1? str : 
				str.substring(str.lastIndexOf(dirName)+pathLength,str.length());
			
			//处理文件名前缀  页面给出
			if(IsKit.isNotNullOrEmpty(filePrefix)){
				tempFileName = filePrefix + "-"+tempFileName;
			}
			if(FileKit.delFile(filePath + tempFileName)) {
				++num;
			}
		}
		return num;
	}
	/**依据传入目录标识subfolder，返回文件目录的绝对路径
	 * @param subfolder
	 * @return
	 */
	public String getFileFullPath(String subfolder)
	{	/**要写入子目录所在根目录*/
		String folderPath = this.sysConfigService.getReposityURI();
		if (IsKit.isNullOrEmpty(subfolder)) {
			folderPath = this.sysConfigService.getTempPath() + CharsetKit.FILE_SEPARATOR;
		}
		else {
			folderPath = folderPath + subfolder + CharsetKit.FILE_SEPARATOR;
		}
		return folderPath;
	}

	/**
	 * 供下载文件的暂存路径
	 * @param filename 文件名称
	 */
	public String getAbsoluteFile(String filename) 
	{
		String downloadPath = sysConfigService.getTempPath() + filename;
		File desc = new File(downloadPath);
		if (!desc.getParentFile().exists()) {
			desc.getParentFile().mkdirs();
		}
		return downloadPath;
	}
}
