package com.izouma.awesomeadmin.service;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

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;
import com.izouma.awesomeadmin.util.ImagesUtil;
import com.izouma.awesomeadmin.util.PropertiesFileLoader;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Service
public class OSSFileService {

    /**
     * 日志对象
     */
    private static Logger logger = Logger.getLogger(OSSFileService.class);
    private static final String projectName = PropertiesFileLoader.getProperties("projectname");

    public String uploadOss(InputStream fin, String path) {
        if (path.startsWith("/")) {
            path = path.replaceFirst("\\\\/", "");
        }
        path = projectName + "/" + path;

        String aliid = PropertiesFileLoader.getDefaultProperties("aliossid", "");
        String alikey = PropertiesFileLoader.getDefaultProperties("aliosskey", "");
        String aliossendpoit = PropertiesFileLoader.getDefaultProperties("aliossendpoit", "");
        String bucketname = PropertiesFileLoader.getDefaultProperties("alibucketname", "");
        logger.info(String.format("OSS上传:\naliid: %s\nalikey: %s\naliossendpoit: %s\nbucketname: %s\npath: %s", aliid, alikey, aliossendpoit, bucketname, path));

        OSSClient client = new OSSClient(aliossendpoit, aliid, alikey);
        OSSObject object = null;
        try {
            client.putObject(bucketname, path, fin, new ObjectMetadata());
            object = client.getObject(bucketname, path);
        } catch (Exception r) {
            logger.error("OSS上传异常:", r);
        }
        // 如果不设置content-length, 默认为chunked编码。
        if (object != null) {
            return getFullPath(path);
        }
        return null;
    }

    public String upload(InputStream fin, String imageName) {

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        String uploadPath = request.getSession().getServletContext().getRealPath(projectName);

        String imgUrlPath = "";


        try {


            File file = new File(uploadPath + "/" + imageName.split("/")[0]);
            if (!file.exists() && !file.isDirectory())
                file.mkdirs();

            InputStream in = fin;
            OutputStream out = new FileOutputStream(uploadPath + "/" + imageName, true);
            byte b[] = new byte[1024];
            int len = 0;
            while ((len = in.read(b)) != -1) {
                out.write(b, 0, len);
            }
            in.close();
            out.close();
            System.out.println("存入照片：" + uploadPath + "/" + imageName);
            imgUrlPath = projectName + "/" + imageName;
        } catch (Exception r) {
            logger.error("OSS上传异常:", r);
        }
        // 如果不设置content-length, 默认为chunked编码。
        if (imgUrlPath != null) {
            return getFullPath(imgUrlPath);
        }
        return null;
    }


    private static String getFullPath(String Path) {
        if (Path == null || "".equals(Path)) {
            return Path;
        }
//        String aliossendpoit = PropertiesFileLoader.getDefaultProperties("aliImageSever", "");
        String aliossendpoit = PropertiesFileLoader.getDefaultProperties("base_domain", "");
        return aliossendpoit + "/" + Path;
    }


    public String uploadImg(String base64) throws UnsupportedEncodingException {
        try {
            logger.info("uploadIcon:上传图片");

            if (base64 == null) {
                return null;
            }
            Random random = new Random();
            StringBuilder randomCode = new StringBuilder();
            for (int i = 0; i < 8; i++) {
                randomCode.append(Integer.toString(random.nextInt(36), 36));
            }
            try {
                String path = String.format("images/%s-%s.jpg", new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss").format(new Date()), randomCode);
                return upload(ImagesUtil.GenerateImage(base64), path);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("上传图片异常");
        }
        return null;
    }

}
