package com.pingpang.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pingpang.fastdfs.FileDfsUtil;
import com.pingpang.util.ImageBase64Converter;
import com.pingpang.util.ImageUtil;
 
@RestController
@RequestMapping("/fileUpload")
public class PictureController{
	
	//日志操作
	private Logger logger = LoggerFactory.getLogger(PictureController.class);
	
	@Resource
    private FileDfsUtil fileDfsUtil;
	
	@Value("${fdfs.sever-addres}")
	private String fileServer;
	
	@ResponseBody
    @RequestMapping("/imageUpload")
    //名字upload是固定的，有兴趣，可以打开浏览器查看元素验证
    public String imageUpload(HttpServletRequest request,@RequestParam("file") MultipartFile file) throws Exception {
		//获取跟目录
		File path = new File(ResourceUtils.getURL("file:").getPath());
		if(!path.exists()) path = new File("");
		logger.info("path:"+path.getAbsolutePath());

		//如果上传目录为/static/images/upload/，则可以如下获取：
		File upload = new File(path.getAbsolutePath(),"static/upload/");
		if(!upload.exists()) upload.mkdirs();
		logger.info("upload url:"+upload.getAbsolutePath());
		
		logger.info(request.getServletContext().getRealPath("/static/upload"));
		 
		// 获取文件名0
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //实际处理肯定是要加上一段唯一的字符串（如现在时间），这里简单加 cun
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        String newFileName = uuid + suffixName;
        //使用架包 common-io实现图片上传
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(upload.getAbsolutePath()+File.separator + newFileName));
         
        //再保存一份压缩文件 
        String reImg=uuid+ suffixName;
        
//        if(PictureController.isImage(upload.getAbsolutePath()+File.separator + newFileName)) {
//        	reImg=uuid+"_2"+ suffixName;
//        	ImageUtil.resize(new File(upload.getAbsolutePath()+File.separator + newFileName), new File(upload.getAbsolutePath()+File.separator + reImg),150, 0.7f);
//        }
        
        //实现图片回显，基本上是固定代码，只需改路劲即可
        Map<String,Object> resultMap=new HashMap<String,Object>();
        Map<String,Object> fileMap=new HashMap<String,Object>();
        resultMap.put("code", "0");
        resultMap.put("msg", "上传成功");
        resultMap.put("data", fileMap);
        //fileMap.put("src", request.getContextPath()+"upload/"+ reImg);
        fileMap.put("src", "/"+reImg);
        fileMap.put("title", newFileName);
        ObjectMapper mapper = new ObjectMapper();
        String result=mapper.writeValueAsString(resultMap);
        return result;
    }
	
	public static boolean isImage(String srcFileName) {
		FileInputStream imgFile = null;
		byte[] b = new byte[10];
		int l = -1;
		try {
			imgFile = new FileInputStream(srcFileName);
			l = imgFile.read(b);
			imgFile.close();
		} catch (Exception e) {
			return false;
		}
		if (l == 10) {
			byte b0 = b[0];
			byte b1 = b[1];
			byte b2 = b[2];
			byte b3 = b[3];
			byte b6 = b[6];
			byte b7 = b[7];
			byte b8 = b[8];
			byte b9 = b[9];
			if (b0 == (byte) 'G' && b1 == (byte) 'I' && b2 == (byte) 'F') {
				return true;
			} else if (b1 == (byte) 'P' && b2 == (byte) 'N' && b3 == (byte) 'G') {
				return true;
			} else if (b6 == (byte) 'J' && b7 == (byte) 'F' && b8 == (byte) 'I' && b9 == (byte) 'F') {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
	
	@ResponseBody
    @RequestMapping("/imageUploadBase64")
    public Map<String,Object> imageUploadBase64(@RequestParam("img") String img) {
		Map<String,Object> resultMap=new HashMap<String,Object>();
		try {
			//获取跟目录
			File path = new File(ResourceUtils.getURL("file:").getPath());
			if(!path.exists()) path = new File("");
			logger.info("path:"+path.getAbsolutePath());

			//如果上传目录为/static/images/upload/，则可以如下获取：
			File upload = new File(path.getAbsolutePath(),"static/upload/");
			if(!upload.exists()) upload.mkdirs();
			logger.info("upload url:"+upload.getAbsolutePath());
			//data:image/png;base64,
			String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
			String newFileName = uuid + "."+img.substring(img.indexOf("/")+1,img.indexOf(";"));
			logger.info("文件名称:"+newFileName);
			
			ImageBase64Converter.convertBase64ToFileImg(img.substring(img.indexOf(",")+1), upload.getAbsolutePath(), newFileName);
			
			Map<String,Object> fileMap=new HashMap<String,Object>();
			resultMap.put("code", "0");
	        resultMap.put("msg", "上传成功");
	        resultMap.put("data", fileMap);
	        //fileMap.put("src", request.getContextPath()+"upload/"+ reImg);
	        fileMap.put("src", "/"+newFileName);
	        fileMap.put("title", newFileName);
			return resultMap;
		} catch (FileNotFoundException e) {
			logger.error("base64图片上传失败", e);
		}
		resultMap.put("code", "-1");
		return resultMap;
    }
	
	
	@ResponseBody
    @RequestMapping("/imageBase64")
    public Map<String,Object> loadImage(@RequestParam("imageName") String imageName) {
		Map<String,Object> resultMap=new HashMap<String,Object>();
		try {
			File path = new File(ResourceUtils.getURL("file:").getPath());
			File upload = new File(path.getAbsolutePath(),"static/upload/");
			String base64=ImageBase64Converter.convertFileToBase64Img(upload.getAbsolutePath()+File.separator + imageName);
	        resultMap.put("code", "0");
	        resultMap.put("msg", base64);
	        return resultMap;
		} catch (FileNotFoundException e) {
			logger.error("图片获取失败"+imageName, e);
		}
		resultMap.put("code", "-1");
		return resultMap;
    }
	
	@ResponseBody
    @RequestMapping("/audioUpload")
    //名字upload是固定的，有兴趣，可以打开浏览器查看元素验证
    public String audioUpload(HttpServletRequest request,@RequestParam("file") MultipartFile file) throws Exception {
		//获取跟目录
		File path = new File(ResourceUtils.getURL("'file:").getPath());
		if(!path.exists()) path = new File("");
		logger.info("path:"+path.getAbsolutePath());

		//如果上传目录为/static/images/upload/，则可以如下获取：
		File upload = new File(path.getAbsolutePath(),"/static/upload/");
		if(!upload.exists()) upload.mkdirs();
		logger.info("upload url:"+upload.getAbsolutePath());
		
		logger.info(request.getServletContext().getRealPath("/static/upload"));
		
		String suffixName=".wav";
        //实际处理肯定是要加上一段唯一的字符串（如现在时间），这里简单加 cun
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        String newFileName = uuid + suffixName;
        //使用架包 common-io实现图片上传
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(upload.getAbsolutePath()+File.separator + newFileName));
         
        //再保存一份压缩文件 
        String reImg=uuid+ suffixName;
        
        //实现图片回显，基本上是固定代码，只需改路劲即可
        Map<String,Object> resultMap=new HashMap<String,Object>();
        Map<String,Object> fileMap=new HashMap<String,Object>();
        resultMap.put("code", "0");
        resultMap.put("msg", "上传成功");
        resultMap.put("data", fileMap);
        fileMap.put("src", request.getContextPath()+File.separator +"upload/"+ reImg);
        fileMap.put("title", newFileName);
        ObjectMapper mapper = new ObjectMapper();
        String result=mapper.writeValueAsString(resultMap);
        return result;
	}
	
	
	@ResponseBody
    @RequestMapping("/imageUploadDfs")
    //名字upload是固定的，有兴趣，可以打开浏览器查看元素验证 
    public String imageUploadDfs(HttpServletRequest request,@RequestParam("file") MultipartFile file) throws Exception {
		// 获取文件名0
        String fileName = file.getOriginalFilename();
        
		String path = fileDfsUtil.upload(file) ;
		
		//实现图片回显，基本上是固定代码，只需改路劲即可
        Map<String,Object> resultMap=new HashMap<String,Object>();
        Map<String,Object> fileMap=new HashMap<String,Object>();
        resultMap.put("code", "0");
        resultMap.put("msg", "上传成功");
        resultMap.put("data", fileMap);
        fileMap.put("src", "http://"+fileServer+"/"+path);
        fileMap.put("title", fileName);
        fileMap.put("width", "180px");
        fileMap.put("height", "100px");
        ObjectMapper mapper = new ObjectMapper();
        String result=mapper.writeValueAsString(resultMap);
        return result;
	}
}