package com.winsun.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


/**
 * Base64流转图片工具类
 * @author calvin
 */
public class Base64ToImgUtils {
	public static String base64ToImg(String imgData, String hhr_img) throws IOException {
		String filePath = "";
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		uuid = uuid.substring(1, 12);
		SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
		SimpleDateFormat sd2 = new SimpleDateFormat("yyyyMM");
		String orderNumber = "YRYM" + sd.format(new Date()) + uuid;

		Date date = new Date();
		String createdate = sd2.format(date);
		File file = new File(hhr_img + "/" + createdate+ "/" + sd.format(date) + "/"+ orderNumber);
		if (!file.exists() && !file.isDirectory()) {
			file.mkdirs();
		}

		if (!imgData.isEmpty()) {
			String name = orderNumber;
			String base64Data =  imgData.split(",")[1];
			String houzhui = imgData.split(",")[0].split("/")[1].split(";")[0];
			/**
			 * 2.解码成字节数组
			 */

			filePath = hhr_img + "/" + createdate+ "/" + sd.format(date) + "/"+ orderNumber +"/" + "O" + name +"."+ houzhui;

			java.util.Base64.Decoder decoder = java.util.Base64.getDecoder();
			byte[] bytes = decoder.decode(base64Data);
			FileOutputStream fos = null;
			try {
				fos = new FileOutputStream(filePath);
				fos.write(bytes);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (fos != null){
					try {
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return filePath;
	}
}
