package com.ssj.framework.core.util;

import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.idworker.IdWorker;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;




/**
 * 
 * 类名称：ImageTools<br>
 * 类描述：图片工具类<br>
 * @version v1.0
 *
 */
public class ImageTools {
    protected static Logger logger = LoggerFactory.getLogger(ImageTools.class);
    /**
     * jpg后缀
     */
    public static final String SUFF_JPG = ".jpg";

    /**
     * png后缀
     */
    public static final String SUFF_PNG = ".png";

    /**
     * gif后缀
     */
    public static final String SUFF_GIF = ".gif";

    /**
     * 保存来自base64的图片,返回参数不为空保存成功
     * @param base64String
     * @return
     */
    public static String savePic4Base64(String base64String) {
        String saveFileName = IdWorker.generateId() + getPicExtension(base64String);

        //判断是否为base64字符串，不是要处理
        if (!Base64.isBase64(base64String)) {
            String[] base64Strs = base64String.split(",");
            if (base64Strs.length > 1) {
                base64String = base64Strs[1];
            }
        }
        byte[] bytes = Base64.decodeBase64(base64String);

        for (int i = 0; i < bytes.length; ++i) {
            if (bytes[i] < 0) {//调整异常数据  
                bytes[i] += 256;
            }
        }

        String imgFilePath = getSavePath() + "/" +  saveFileName;//图片保存路径

        try {
            IOUtils.write(bytes, new FileOutputStream(imgFilePath));
            String ps=OSSUtils.uploadFile(imgFilePath,
                    imgFilePath.replaceAll(PropertiesUtil.getValue("file_save_path"),""));
            logger.info("阿里oss返回的路径="+ps);

        } catch (IOException e) {
            e.printStackTrace();
            imgFilePath = null;
        }
        return imgFilePath;
    }




    public static String[] uploadFile(Map<String, MultipartFile> fileList) {
        String[] filePaths = new String[fileList.size()];

        String imgFilePath = getSavePath() + "/" ;
        int i = 0;
        for (Map.Entry<String, MultipartFile> entity : fileList.entrySet()) {
            MultipartFile fileItem = entity.getValue();

            //图片保存文件名
            String saveFileName =IdWorker.generateId() + "." + FilenameUtils.getExtension(fileItem.getName());
            FileOutputStream outputStream = null;
            try {
                outputStream = new FileOutputStream(imgFilePath + saveFileName);
                IOUtils.write(fileItem.getBytes(), outputStream);

                filePaths[i] = imgFilePath + saveFileName;
            } catch (IOException e) {
                e.printStackTrace();
            }finally  {
                IOUtils.closeQuietly(outputStream);
            }
            i++;
        }
        return filePaths;
    }
    
    public static String[] uploadFile(List<MultipartFile> fileList) {
        String imgFilePath = getSavePath() + "/" ;
        return uploadFile(imgFilePath, fileList);
    }


    public static String[] uploadFile(String imgFilePath, List<MultipartFile> fileList) {
        String[] filePaths = new String[fileList.size()];
        int i = 0;
        for (MultipartFile fileItem : fileList) {

            //图片保存文件名
            String originalFile = fileItem.getOriginalFilename();
            String ext = originalFile.substring(originalFile.lastIndexOf("."));
            if(ext !=null && ext.contains("image%")){
                ext =SUFF_JPG;
            }
            String saveFileName = IdWorker.generateId() + ext;
            FileOutputStream outputStream = null;
            try {
                outputStream = new FileOutputStream(imgFilePath + saveFileName);
                IOUtils.write(fileItem.getBytes(), outputStream);


                String ps= OSSUtils.uploadInputStream(fileItem.getInputStream(),
                        (imgFilePath + saveFileName).replaceAll(PropertiesUtil.getValue("file_save_path"),""));
                logger.info("阿里oss返回的路径="+ps);



                filePaths[i] = imgFilePath + saveFileName;
            } catch (IOException e) {
                e.printStackTrace();
            }finally  {
                IOUtils.closeQuietly(outputStream);
            }
            i++;
        }

        return filePaths;
    }

    public static void uploadFile(String absFileName, MultipartFile file) {
        //图片保存文件名
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(absFileName);
            IOUtils.write(file.getBytes(), outputStream);
//            String ps= OSSUtils.uploadInputStream(file.getInputStream(),
//                    absFileName.replaceAll(PropertiesUtil.getValue("file_save_path"),""));
//            logger.info("阿里oss返回的路径="+ps);
        } catch (IOException e) {
            e.printStackTrace();
        }finally  {
            IOUtils.closeQuietly(outputStream);
        }
    }

    public static void uploadFilePd(MultipartFile files,String imgFilePath) {
        FileOutputStream outputStream = null;
            try {
                outputStream = new FileOutputStream(imgFilePath);
                IOUtils.write(files.getBytes(), outputStream);

                String ps= OSSUtils.uploadInputStream(files.getInputStream(),
                        imgFilePath.replaceFirst(PropertiesUtil.getValue("file_save_path"),""));
                logger.info("上海培典上传深圳阿里oss返回的路径="+ps);
            } catch (IOException e) {
                e.printStackTrace();
            }finally  {
                IOUtils.closeQuietly(outputStream);
            }
    }

    /**
     * 获取保存目录 按年/月/日 区分
     */
    public static String getSavePath() {
        String savePath = PropertiesUtil.getValue("file_save_path");
        // 当前日期(按月保存)
        String date = DateHelper.formatDateByFormat(new Date(), "yyyy/MM/dd");
        savePath = savePath +  date;
        // 创建文件夹
        File f = new File(savePath);
        if (!f.exists()) {
            f.mkdirs();
        }
        return savePath;
    }

    /**
     * 从base64字符串中获取图片后缀
     * @return
     */
    private static String getPicExtension(String base64String) {
        //默认使用jpg
        if (base64String.contains("image/jpg")) {
            return SUFF_JPG;
        } else if (base64String.contains("image/png")) {
            return SUFF_PNG;
        } else if (base64String.contains("image/gif")) {
            return SUFF_GIF;
        } else {
            return SUFF_JPG;
        }
    }


}
