package cn.palmte.work.service;

import cn.palmte.work.config.UploadProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;
import top.jfunc.common.datetime.DatetimeUtils;
import top.jfunc.common.utils.CommonUtil;
import top.jfunc.common.utils.FileUtil;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;

/**
 * @author xiongshiyan at 2020/10/13 , contact me with email yanshixiong@126.com or phone 15208384257
 */
@Service
public class UploadService {
    private static final Logger logger = LoggerFactory.getLogger(UploadService.class);
    public static final String DATA_IMAGE_PNG_BASE64 = "data:image/png;base64,";
    public static final String DATA_IMAGE_JPEG_BASE64 = "data:image/jpeg;base64,";
    public static final String DATA_IMAGE_JPG_BASE64 = "data:image/jpg;base64,";

    @Autowired
    private UploadProperties uploadProperties;

    public String upload(String base64Str){
        String suffix = "png";
        if (base64Str.contains(DATA_IMAGE_PNG_BASE64)) {
            base64Str = base64Str.replaceAll(DATA_IMAGE_PNG_BASE64, "");
            suffix = "png";
        } else if (base64Str.contains(DATA_IMAGE_JPEG_BASE64)) {
            base64Str = base64Str.replaceAll(DATA_IMAGE_JPEG_BASE64, "");
            suffix = "jpeg";
        }else if (base64Str.contains(DATA_IMAGE_JPG_BASE64)) {
            base64Str = base64Str.replaceAll(DATA_IMAGE_JPG_BASE64, "");
            suffix = "jpg";
        }
        String uploadPath = uploadProperties.getPath();
        String uploadPrefix = uploadProperties.getPrefix();
        String yyyyMMdd = DatetimeUtils.toStr(new Date(), "yyyyMMdd");
        String saveDir = uploadPath + "/" + yyyyMMdd;
        FileUtil.makeSureExistDir(saveDir);

        String fileName = CommonUtil.randomString(32) + "." + suffix;
        String absolutePath = saveDir + "/" + fileName;
        File file = new File(absolutePath);

        decodeAndWrite(base64Str , file);

        return uploadPrefix + "/" + yyyyMMdd + "/" + fileName;
    }


    private void decodeAndWrite(String base64Str, File destFile) {
        try {
            // Base64解码
            byte[] bytes = new BASE64Decoder().decodeBuffer(base64Str);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {
                    // 调整异常数据
                    bytes[i] += 256;
                }
            }
            Files.write(Paths.get(destFile.getAbsolutePath()), bytes);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}
