package com.palmnest.webapp.controller;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.core.util.FileUploadUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Controller
@RequestMapping("/uploadTemplate*")
public class UploadTemplateController {

	/**
	 * 上传图片
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/upload*")
	public void upload(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> data = new HashMap<String, Object>(3);
		data.put("success", true);
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest
					.getFile("Filedata");// 这里是表单的名字，在swfupload.js中this.ensureDefault("file_post_name",
			// "filedata");

			InputStream stream  = null;
			String      fileExt = null;

			if (file != null) {
				stream = file.getInputStream();
				String fileName = file.getOriginalFilename();
				fileName = new String(fileName.getBytes(), "utf-8");
				fileExt = StringUtils.isNotEmpty(fileName) ? fileName
						.substring(fileName.lastIndexOf("."))
						: StringUtils.EMPTY;
			}

			FileUploadUtils fileUploadUtils = new FileUploadUtils();
			fileUploadUtils.init();
			String url = fileUploadUtils.uploadFile(stream, fileExt);

			data.put("url", url);
			data.put("preview", fileUploadUtils.fullVisitPath(url));
		} catch (Exception e) {
			e.printStackTrace();
		}
		printJson(response, JSONObject.toJSONString(data));
	}

	/**
	 * 上传图片
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/uploadImgFile*")
	public void uploadImgFile(HttpServletRequest request,
							  HttpServletResponse response, @RequestParam MultipartFile imgFile) {
		Map<String, Object> data = new HashMap<String, Object>(3);
		data.put("success", true);
		try {
			InputStream stream   = imgFile.getInputStream();
			String      fileName = imgFile.getOriginalFilename();
			fileName = new String(fileName.getBytes(), "utf-8");
			String fileExt = StringUtils.isNotEmpty(fileName) ? fileName
					.substring(fileName.lastIndexOf("."))
					: StringUtils.EMPTY;
			FileUploadUtils fileUploadUtils = new FileUploadUtils();
			fileUploadUtils.init();
			String url = fileUploadUtils.uploadFile(stream, fileExt);
			data.put("url", url);
			data.put("preview", fileUploadUtils.fullVisitPath(url));

		} catch (Exception e) {
			e.printStackTrace();
		}
		printJson(response, JSONObject.toJSONString(data));
	}


	@RequestMapping(value = "/uploadBase64", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=utf-8")
	public @ResponseBody
	Map<String, String> uploadImage(HttpServletRequest request, HttpServletResponse response) {

		String   rootPath = FileUploadUtils.getATTACHMENT_ROOT();
		Calendar cal      = Calendar.getInstance();

		Map<String, String> retMap = new HashMap<String, String>();

		String imagePath = "/" + cal.get(Calendar.YEAR) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DAY_OF_MONTH);
		File   file      = new File(rootPath + imagePath);
		if (!file.exists()) {
			file.mkdirs();
		}
		String imageName = UUID.randomUUID().toString() + "." + request.getParameter("suffix");
		String imgStr    = request.getParameter("fileData");
		if (string2Image(imgStr, rootPath + imagePath + "/" + imageName)) {
			retMap.put("url", imagePath + "/" + imageName);
			retMap.put("preview", FileUploadUtils.getVisitPrefix() + imagePath + "/" + imageName);
		} else {
			retMap.put("url", "");
		}
		return retMap;
	}

	/**
	 * 通过BASE64Decoder解码，并生成图片
	 *
	 * @param imgStr 解码后的string
	 */
	public boolean string2Image(String imgStr, String imgFilePath) {

		// 对字节数组字符串进行Base64解码并生成图片
		if (imgStr == null)
			return false;
		try {
			// Base64解码
			byte[] b = new Base64().decode(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {
					// 调整异常数据
					b[i] += 256;
				}
			}
			// 生成Jpeg图片
			OutputStream out = new FileOutputStream(imgFilePath);
			out.write(b);
			out.flush();
			out.close();
			return true;

		} catch (Exception e) {
			return false;
		}
	}


	public static final void printJson(HttpServletResponse response,
									   String content) {
		response.setContentType("text/html; charset=utf-8");
		OutputStream out;
		try {
			out = response.getOutputStream();
			out.write(content.getBytes());
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
