package com.izouma.awesomeadmin.util;

import java.io.InputStream;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

@Service
public class ImageFileUtil {

    /**
     * 日志对象
     */
    private static Logger logger = Logger.getLogger(ImageFileUtil.class);


    public static String UpLoadImage(InputStream fin, String path) {

        logger.info("UpLoadImage :上传照片 开始  ： fin：" + fin + "; phth: " + path);
        String aliid = PropertiesFileLoader.getDefaultProperties("aliossid", "");
        String alikey = PropertiesFileLoader.getDefaultProperties("aliosskey", "");
        String aliossendpoit = PropertiesFileLoader.getDefaultProperties("aliossendpoit", "");
        String bucketname = PropertiesFileLoader.getDefaultProperties("alibucketname", "izouma");
        OSSClient client = new OSSClient(aliossendpoit, aliid, alikey);
        OSSObject object = null;
        logger.info("UpLoadImage :上传照片  ： aliid：" + aliid + "; alikey: " + alikey + "; aliossendpoit : " + aliossendpoit + "; bucketname:"
                + bucketname);
        if (path.startsWith("/")) {
            return "invalid path";
        }
        @SuppressWarnings("unused")
        PutObjectResult result = client.putObject(bucketname, path, fin, new ObjectMetadata());

        try {
            object = client.getObject(bucketname, path);
        } catch (Exception r) {
            logger.error("UpLoadImage: 上传照片异常 ", r);
        }
        // 如果不设置content-length, 默认为chunked编码。
        if (object != null) {
            return "file exist";
        }

        return "success";
    }


    public static String GetRealImagePath(String Path) {

        if (Path == null || "".equals(Path) || Path.startsWith("images")) {
            return Path;
        }
        String aliossendpoit = PropertiesFileLoader.getDefaultProperties("aliImageSever", "");
        return aliossendpoit + "/" + Path;
    }

}
