package com.winsun.utils;

import com.winsun.constant.FilePath;
import lombok.extern.slf4j.Slf4j;

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

/**
 * @Author: chancy
 * @Date: 2020/3/12 14:33
 */
@Slf4j
public class PicturesUtil {

    /**
     * 上传图片
     * <p>
     * 前端传来图片必须为jpeg格式
     *
     * @param file 图片字符串
     * @param path 图片文件夹名
     * @return
     */
    public static String uploadPictures(String file, String path){
        Date date = new Date();
        SimpleDateFormat yyMM = new SimpleDateFormat("yyMM");
        String y = yyMM.format(date.getTime());
        SimpleDateFormat yyMMdd = new SimpleDateFormat("yyMMdd");
        String h = yyMMdd.format(date.getTime());
        String filePath = null;
        String[] multipartFiles = new String[]{file};
        for (int i = 0; i < multipartFiles.length; i++) {
            if (!multipartFiles[i].isEmpty()) {
                String base64Data = multipartFiles[i].split(",")[1];
                String houzhui = multipartFiles[i].split(",")[0].split("/")[1].split(";")[0];
                /**
                 * 2.解码成字节数组
                 */
                filePath = FilePath.BACKGROUNDIMG.getValue()+ "/" + y + "/" + h + "/" + path + "/" + date.getTime() + "." + houzhui;
                 String  filePath1 = FilePath.BACKGROUNDIMG.getValue()+ "/" + y + "/" + h + "/" + path;
                File dir = new File(filePath1);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                //byte[] bytes = Base64.getUrlDecoder().decode(base64Data);
                //byte[] bytes =new BASE64Decoder().decodeBuffer(base64Data);
                //byte[] bytes = Base64.getDecoder().decode(base64Data);
                byte[] bytes = Base64.getMimeDecoder().decode(base64Data.replace(" ","+"));
                        FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(filePath);
                    fos.write(bytes);
                } catch (IOException e) {
                    log.info("图片上传异常");
                    e.printStackTrace();
                } finally {
                    if (fos != null) {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            log.info("图片上传异常");
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return filePath;
    }
}
