package com.winsun.utils;

import org.springframework.stereotype.Component;

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


/**
 * Base64流转图片工具类
 * @author calvin
 */
@Component
public class Base64ToImgUtils {
	public String base64ToImg(String imgData, String hhr_img){
		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;
	}
	//path 为图片在服务器的绝对路径
	public String imgToBase64(String url) {
		try {
			File file = new File(url);
			FileInputStream fis;
			fis = new FileInputStream(file);

			long size = file.length();
			byte[] temp = new byte[(int) size];
			fis.read(temp, 0, (int) size);
			fis.close();
			byte[] data = temp;
			return new String(org.apache.commons.codec.binary.Base64.encodeBase64(data));
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
}
