package com.cftech.core.util;

import com.cftech.core.config.MpGlobalConfig;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by liuling on 16/4/26.
 */
public class QiniuUploadUtils {
    private static Logger logger = LoggerFactory.getLogger(QiniuUploadUtils.class);

    public static final String ak = MpGlobalConfig.QN_ACCESS_KEY;
    public static final String sk = MpGlobalConfig.QN_SECRET_KEY;
    public static final String bucket = MpGlobalConfig.QN_BACKET_NAME;
    public static String uptoken = null;

    public static Response upload(String uploadFilePath, String filename) {
        //权限
        Auth auth = Auth.create(ak,  sk);
        String qnToken = auth.uploadToken(MpGlobalConfig.QN_BACKET_NAME);
        //创建上传对象
        UploadManager uploadManager = new UploadManager();
        Response res = null;
        try {
            res = uploadManager.put(uploadFilePath, filename, qnToken);
            logger.info("QiniuUploadUtils upload",res.bodyString());

        } catch (QiniuException e) {
            logger.error("QiniuUploadUtils upload",e.response.toString());
        }
        return res;
    }
    
    public static Response uploadDiskFileItem(DiskFileItem fileItem, String filename) {
        //权限
        Auth auth = Auth.create(ak,sk);
        String qnToken = auth.uploadToken(MpGlobalConfig.QN_BACKET_NAME);
        //创建上传对象
        UploadManager uploadManager = new UploadManager();
        Response res = null;
       
        
     
        try {
        	byte[] fileBytes = IOUtils.toByteArray(fileItem.getInputStream());
            res = uploadManager.put(fileBytes, filename, qnToken);
            logger.info("QiniuUploadUtils upload",res.bodyString());

        } catch (QiniuException e) {
            logger.error("QiniuUploadUtils upload",e.response.toString());
        } catch (IOException e) {
        	logger.error("QiniuUploadUtils upload IO exception",e.getMessage());
		}
        return res;
    }
    
    public static Response uploadInputStream(byte[] buf,String filename){
    	 //权限
        Auth auth = Auth.create(ak,sk);
        String qnToken = auth.uploadToken(MpGlobalConfig.QN_BACKET_NAME);
        //创建上传对象
        UploadManager uploadManager = new UploadManager();
        Response res = null;
        try {
            res = uploadManager.put(buf, filename, qnToken);
            logger.info("QiniuUploadUtils upload",res.bodyString());

        } catch (QiniuException e) {
            logger.error("QiniuUploadUtils upload",e.response.toString());
        } catch (IOException e) {
        	logger.error("QiniuUploadUtils upload IO exception",e.getMessage());
		}
        return res;
    }

    /**
     * 获取token
     * @return
     */
    public static String getUptoken(){
        return Auth.create(ak, sk).uploadToken(bucket);
    }

    /**
     * 生成uptoken
     */
    public static void genUptoken(){
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        executor.scheduleAtFixedRate(new Runnable() {
            public void run() {
                uptoken = getUptoken();
            }
        }, 0, 3500, TimeUnit.SECONDS);
    }

    /**
     * 上传文件
     * @param path
     * @param file
     */
    public static UploadManager uploadManager = new UploadManager();
    public static void uploadFile(String path, String file){
        uptoken = getUptoken();
        try {
            Response res = uploadManager.put(file, path, uptoken);
            logger.info("QiniuUploadUtils upload:" + res.bodyString());
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }

    public static String getUploadFileName(String fileName, long time) {
        String extName = getFileExt(fileName);
        String newFileName=time + extName;

        return newFileName;
    }

    public static String getFileExt(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }


    public static String getRandomFileName(String fileName) {
        String extName = getFileExt(fileName);
        long time = new Date().getTime();
        String newFileName=time + extName;

        return newFileName;
    }
}
