package com.cftech.core.util;

import com.alibaba.fastjson.JSONObject;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.request.*;
import com.qcloud.cos.utils.*;
import com.qcloud.cos.utils.StringUtils;
import org.apache.commons.fileupload.FileItem;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author 作者 lisw:
 * @version 创建时间：2016年9月18日 上午10:36:45
 * 腾讯云cos资源操作工具类
 */
public class QcloudUploadUtils {

    static int APP_ID = Integer.parseInt(SystemConfig.p.getProperty("Qcloud_APP_ID"));
    static String SECRET_ID = SystemConfig.p.getProperty("Qcloud_SECRET_ID");
    static String SECRET_KEY = SystemConfig.p.getProperty("Qcloud_SECRET_KEY");
    static String BUCKETNAME =  SystemConfig.p.getProperty("Qcloud_BUCKET_NAME");
    static String region=SystemConfig.p.getProperty("Qcloud_Region");

//	static int APP_ID = 1253344332;
//	static String SECRET_ID = "AKID1tZ2IKGmCOM8h3q7qMeiZDerqcAVtWDg";
//	static String SECRET_KEY = "MYXIq9GApHWYNyMXVEj04vYyBAvSmtmS";
//	static String BUCKETNAME =  "faye5";
//	static String region="sh";

    //	//AO账号  运行main方法使用
    //	static int APP_ID = 10065849;
    //	static String SECRET_ID ="AKIDaWZPqjyrdUiOe5nALvfRbBscByM0rNml";
    //	static String SECRET_KEY = "rtQq27ul6B1DntCGFZOlSnZyq0qG289X";
    //	static String BUCKETNAME = "weixin";

    //lsw测试账号  运行main方法使用
    //  static int APP_ID = 10066139;
    //  static String SECRET_ID ="AKIDZ0QUF7uexVgDyOxpi5mwJwR20tRBOjVx";
    //  static String SECRET_KEY = "fMNmGljnNSw3RIaalrFhqHkzkyXr4A3Q";
    //  static String BUCKETNAME = "weixin";


    /**
     * 上传文件到腾讯云
     * @param uploadFileRequest
     * @return
     */
    public static String upload(UploadFileRequest uploadFileRequest){
        // 设置bucket所在的区域，比如广州(gz), 天津(tj)
//		COSCredentials cred = new BasicCOSCredentials(String.valueOf(SECRET_ID),String.valueOf(SECRET_KEY));
//		ClientConfig clientConfig = new ClientConfig( new Region(region));
//		// 初始化秘钥信息
//		//	Credentials cred = new Credentials(APP_ID, SECRET_ID, SECRET_KEY);
//		// 初始化cosClient
//		COSClient cosClient = new COSClient(cred, clientConfig);
//		try {
//			InputStream input = uploadFileRequest.getInputStream(); ;
//			ObjectMetadata objectMetadata = new ObjectMetadata();
//			// 从输入流上传必须制定content length, 否则http客户端可能会缓存所有数据，存在内存OOM的情况
//			objectMetadata.setContentLength(file.getSize());
//			// 默认下载时根据cos路径key的后缀返回响应的contenttype, 上传时设置contenttype会覆盖默认值
//			objectMetadata.setContentType("image/jpeg");
//
//			PutObjectRequest putObjectRequest =
//					new PutObjectRequest(uploadFileRequest.getBucketName(), uploadFileRequest.getCosPath(), input, objectMetadata);
//			// 设置存储类型, 默认是标准(Standard), 低频(standard_ia), 近线(nearline)
//			putObjectRequest.setStorageClass(StorageClass.Standard_IA);
//			PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
//			// putobjectResult会返回文件的etag
//			return putObjectResult.getETag();
//		} catch (CosServiceException e) {
//			e.printStackTrace();
//		} catch (CosClientException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		} finally {
//			// 关闭客户端
//			if(cosClient!=null)
//				cosClient.shutdown();
//		}
        return "";

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



    public static String uploadStreamNoUrl(UploadFileRequest request, FileItem file){
//		ClientConfig clientConfig = new ClientConfig();
//		// 设置bucket所在的区域，比如广州(gz), 天津(tj)
//		clientConfig.setRegion(region);
//		// 初始化秘钥信息
//		Credentials cred = new Credentials(APP_ID, SECRET_ID, SECRET_KEY);
//		// 初始化cosClient
//		COSClient cosClient = new COSClient(clientConfig, cred);
//
//		String uploadFileRet = cosClient.uploadCFSingleFile(request,file);

        // 设置bucket所在的区域，比如广州(gz), 天津(tj)
        COSCredentials cred = new BasicCOSCredentials(String.valueOf(SECRET_ID),String.valueOf(SECRET_KEY));
        ClientConfig clientConfig = new ClientConfig( new Region(region));
        // 初始化秘钥信息
        //	Credentials cred = new Credentials(APP_ID, SECRET_ID, SECRET_KEY);
        // 初始化cosClient
        COSClient cosClient = new COSClient(cred, clientConfig);
        try {
            InputStream input = file.getInputStream(); ;
            ObjectMetadata objectMetadata = new ObjectMetadata();
            // 从输入流上传必须制定content length, 否则http客户端可能会缓存所有数据，存在内存OOM的情况
            objectMetadata.setContentLength(file.getSize());
            // 默认下载时根据cos路径key的后缀返回响应的contenttype, 上传时设置contenttype会覆盖默认值
//			getFileExt(request.getCosPath());
            objectMetadata.setContentType(file.getContentType());

            PutObjectRequest putObjectRequest =
                    new PutObjectRequest(request.getBucketName(), request.getCosPath(), input, objectMetadata);
            // 设置存储类型, 默认是标准(Standard), 低频(standard_ia), 近线(nearline)
            putObjectRequest.setStorageClass(StorageClass.Standard_IA);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            // putobjectResult会返回文件的etag
            String id = putObjectResult.getRequestId();
            if(org.apache.commons.lang3.StringUtils.isNotBlank(id))
            {
                JSONObject obj = new JSONObject();
                obj.put("code",0);
                JSONObject data = new JSONObject();
                data.put("access_url", request.getCosPath());
                obj.put("data",data);
                return obj.toJSONString();
            }
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭客户端
            if(cosClient!=null)
                cosClient.shutdown();
        }
        return null;
    }

    /**通过file对象，上传到腾讯云
     * @param request
     * @param file
     * @return
     *
     */
    public static String uploadStream(UploadFileRequest request, FileItem file){
//		ClientConfig clientConfig = new ClientConfig();
//		// 设置bucket所在的区域，比如广州(gz), 天津(tj)
//		clientConfig.setRegion(region);
//		// 初始化秘钥信息
//		Credentials cred = new Credentials(APP_ID, SECRET_ID, SECRET_KEY);
//		// 初始化cosClient
//		COSClient cosClient = new COSClient(clientConfig, cred);
//
//		String uploadFileRet = cosClient.uploadCFSingleFile(request,file);

        // 设置bucket所在的区域，比如广州(gz), 天津(tj)
        COSCredentials cred = new BasicCOSCredentials(String.valueOf(SECRET_ID),String.valueOf(SECRET_KEY));
        ClientConfig clientConfig = new ClientConfig( new Region(region));
        // 初始化秘钥信息
        //	Credentials cred = new Credentials(APP_ID, SECRET_ID, SECRET_KEY);
        // 初始化cosClient
        COSClient cosClient = new COSClient(cred, clientConfig);
        try {
            InputStream input = file.getInputStream(); ;
            ObjectMetadata objectMetadata = new ObjectMetadata();
            // 从输入流上传必须制定content length, 否则http客户端可能会缓存所有数据，存在内存OOM的情况
            objectMetadata.setContentLength(file.getSize());
            // 默认下载时根据cos路径key的后缀返回响应的contenttype, 上传时设置contenttype会覆盖默认值
//			getFileExt(request.getCosPath());
            objectMetadata.setContentType(file.getContentType());

            PutObjectRequest putObjectRequest =
                    new PutObjectRequest(request.getBucketName(), request.getCosPath(), input, objectMetadata);
            // 设置存储类型, 默认是标准(Standard), 低频(standard_ia), 近线(nearline)
            putObjectRequest.setStorageClass(StorageClass.Standard_IA);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            // putobjectResult会返回文件的etag
            String id = putObjectResult.getRequestId();
            if(org.apache.commons.lang3.StringUtils.isNotBlank(id))
            {
                JSONObject obj = new JSONObject();
                obj.put("code",0);
                JSONObject data = new JSONObject();
                data.put("access_url", SystemConfig.p.getProperty("Qcloud_URL")+request.getCosPath());
                obj.put("data",data);
                return obj.toJSONString();
            }
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭客户端
            if(cosClient!=null)
                cosClient.shutdown();
        }
        return null;
    }


    //	/**通过InputStream输入流，上传到腾讯云
//	 * @param request
//	 * @return
//	 */
    public static String uploadStream(UploadFileRequest request, InputStream stream, String content){
//	/		ClientConfig clientConfig = new ClientConfig();
//		// 设置bucket所在的区域，比如广州(gz), 天津(tj)
//		clientConfig.setRegion(region);
//		// 初始化秘钥信息
//		Credentials cred = new Credentials(APP_ID, SECRET_ID, SECRET_KEY);
//		// 初始化cosClient
//		COSClient cosClient = new COSClient(clientConfig, cred);
//
//		String uploadFileRet = cosClient.uploadCFSingleFile(request,file);

        // 设置bucket所在的区域，比如广州(gz), 天津(tj)
        COSCredentials cred = new BasicCOSCredentials(String.valueOf(SECRET_ID),String.valueOf(SECRET_KEY));
        ClientConfig clientConfig = new ClientConfig( new Region(region));
        // 初始化秘钥信息
        //	Credentials cred = new Credentials(APP_ID, SECRET_ID, SECRET_KEY);
        // 初始化cosClient
        COSClient cosClient = new COSClient(cred, clientConfig);
        try {
            InputStream input =stream; ;
            ObjectMetadata objectMetadata = new ObjectMetadata();
            // 从输入流上传必须制定content length, 否则http客户端可能会缓存所有数据，存在内存OOM的情况
            objectMetadata.setContentLength(stream.available());
            // 默认下载时根据cos路径key的后缀返回响应的contenttype, 上传时设置contenttype会覆盖默认值
            objectMetadata.setContentType("image/jpeg");


            PutObjectRequest putObjectRequest =
                    new PutObjectRequest(request.getBucketName(), request.getCosPath(), input, objectMetadata);
            // 设置存储类型, 默认是标准(Standard), 低频(standard_ia), 近线(nearline)
            putObjectRequest.setStorageClass(StorageClass.Standard_IA);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            String id = putObjectResult.getRequestId();
            if(org.apache.commons.lang3.StringUtils.isNotBlank(id))
            {
                JSONObject obj = new JSONObject();
                obj.put("code",0);
                JSONObject data = new JSONObject();
                data.put("access_url", SystemConfig.p.getProperty("Qcloud_URL")+request.getCosPath());
                obj.put("data",data);
                return obj.toJSONString();
            }
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭客户端
            if(cosClient!=null)
                cosClient.shutdown();
        }
        return null;
    }


    public static String uploadStreamWithFileMeta(UploadFileRequest request, InputStream stream, String content, MultipartFile multipartFile){
//	/		ClientConfig clientConfig = new ClientConfig();
//		// 设置bucket所在的区域，比如广州(gz), 天津(tj)
//		clientConfig.setRegion(region);
//		// 初始化秘钥信息
//		Credentials cred = new Credentials(APP_ID, SECRET_ID, SECRET_KEY);
//		// 初始化cosClient
//		COSClient cosClient = new COSClient(clientConfig, cred);
//
//		String uploadFileRet = cosClient.uploadCFSingleFile(request,file);

        // 设置bucket所在的区域，比如广州(gz), 天津(tj)
        COSCredentials cred = new BasicCOSCredentials(String.valueOf(SECRET_ID),String.valueOf(SECRET_KEY));
        ClientConfig clientConfig = new ClientConfig( new Region(region));
        // 初始化秘钥信息
        //	Credentials cred = new Credentials(APP_ID, SECRET_ID, SECRET_KEY);
        // 初始化cosClient
        COSClient cosClient = new COSClient(cred, clientConfig);
        try {
            InputStream input =stream; ;
            ObjectMetadata objectMetadata = new ObjectMetadata();
            // 从输入流上传必须制定content length, 否则http客户端可能会缓存所有数据，存在内存OOM的情况
            objectMetadata.setContentLength(stream.available());
            // 默认下载时根据cos路径key的后缀返回响应的contenttype, 上传时设置contenttype会覆盖默认值
//			objectMetadata.setContentType("image/jpeg");

            objectMetadata.setContentType(multipartFile.getContentType());

            PutObjectRequest putObjectRequest =
                    new PutObjectRequest(request.getBucketName(), request.getCosPath(), input, objectMetadata);
            // 设置存储类型, 默认是标准(Standard), 低频(standard_ia), 近线(nearline)
            putObjectRequest.setStorageClass(StorageClass.Standard_IA);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            String id = putObjectResult.getRequestId();
            if(org.apache.commons.lang3.StringUtils.isNotBlank(id))
            {
                JSONObject obj = new JSONObject();
                obj.put("code",0);
                JSONObject data = new JSONObject();
                if(multipartFile.getContentType().indexOf("image")>=0){
                    data.put("access_url", SystemConfig.p.getProperty("Qcloud_URL")+request.getCosPath());
                }else{
                    data.put("access_url", SystemConfig.p.getProperty("Qcloud_File_URL")+request.getCosPath());
                }
                obj.put("data",data);
                return obj.toJSONString();
            }
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭客户端
            if(cosClient!=null)
                cosClient.shutdown();
        }
        return null;
    }

//	/**
//	 * 通过file文件，上传到腾讯云
//	 */
//	public static String uploadFile(UploadFileRequest request){
//		COSClient cosClient = request.getCosClient();
//		// 初始化cosClient
//		String uploadFileRet = cosClient.uploadFile(request);
//		return uploadFileRet;
//	}

    /**删除文件
     * @param bucketName
     * @param cosPath
     * @return
     */
    public static String delfile(String bucketName,String cosPath){
        DeleteObjectRequest delfileRequest = new DeleteObjectRequest(bucketName, cosPath);
        COSCredentials cred = new BasicCOSCredentials(String.valueOf(SECRET_ID),String.valueOf(SECRET_KEY));
        ClientConfig clientConfig = new ClientConfig( new Region(region));
        // 初始化秘钥信息
        //	Credentials cred = new Credentials(APP_ID, SECRET_ID, SECRET_KEY);
        // 初始化cosClient
        COSClient cosClient = new COSClient(cred, clientConfig);
        cosClient.deleteObject(delfileRequest);
        return "";
    }

    /**创建文件夹
     * @param bucketName  空间名
     * @param cosPath cos路径, 必须从bucket下的根/开始，目录路径必须以/结尾, 例如 /mytest/dir/
     * @param bizAttr 目录的备注，主要用于对目录用途的描述
     * @return
     */
//	public static String createfolder(String bucketName,String cosPath,String bizAttr){
//		CreateFolderRequest createFolderRequest = new CreateFolderRequest(bucketName, cosPath);
//		createFolderRequest.setBizAttr(bizAttr);
//		ClientConfig clientConfig = new ClientConfig();
//		// 设置bucket所在的区域，比如广州(gz), 天津(tj)
//		clientConfig.setRegion(region);
//		// 初始化秘钥信息
//		Credentials cred = new Credentials(APP_ID, SECRET_ID, SECRET_KEY);
//		// 初始化cosClient
//		COSClient cosClient = new COSClient(clientConfig, cred);
//		String uploadFileRet = cosClient.createFolder(createFolderRequest);
//		System.out.println(uploadFileRet);
//		return uploadFileRet;
//	}

    /**获取目录属性
     * @param bucketName  空间名
     * @param cosPath 目录地址
     * @return
     */
//	public static String statfolder(String bucketName,String cosPath){
//		StatFolderRequest statFolderRequest = new StatFolderRequest(bucketName, cosPath);
//		ClientConfig clientConfig = new ClientConfig();
//		// 设置bucket所在的区域，比如广州(gz), 天津(tj)
//		clientConfig.setRegion(region);
//		// 初始化秘钥信息
//		Credentials cred = new Credentials(APP_ID, SECRET_ID, SECRET_KEY);
//		// 初始化cosClient
//		COSClient cosClient = new COSClient(clientConfig, cred);
//		String result=cosClient.statFolder(statFolderRequest);
//		System.out.println(result);
//		return result;
//	}

    /**获取目录列表
     * @param bucketName
     * @param cosPath
     * @return
     */
//	public static String listfolder(String bucketName,String cosPath){
//		ListFolderRequest listFolderRequest = new ListFolderRequest(bucketName, cosPath);
//		ClientConfig clientConfig = new ClientConfig();
//		// 设置bucket所在的区域，比如广州(gz), 天津(tj)
//		clientConfig.setRegion(region);
//		// 初始化秘钥信息
//		Credentials cred = new Credentials(APP_ID, SECRET_ID, SECRET_KEY);
//		// 初始化cosClient
//		COSClient cosClient = new COSClient(clientConfig, cred);
//		String result=cosClient.listFolder(listFolderRequest);
//		System.out.println(result);
//		return result;
//	}

    /**删除目录
     * @param bucketName
     * @param cosPath
     * @return
     */
//	public static String delfolder(String bucketName,String cosPath){
//		DelFolderRequest delfolderRequest = new DelFolderRequest(bucketName, cosPath);
//		ClientConfig clientConfig = new ClientConfig();
//		// 设置bucket所在的区域，比如广州(gz), 天津(tj)
//		clientConfig.setRegion(region);
//		// 初始化秘钥信息
//		Credentials cred = new Credentials(APP_ID, SECRET_ID, SECRET_KEY);
//		// 初始化cosClient
//		COSClient cosClient = new COSClient(clientConfig, cred);
//		String result = cosClient.delFolder(delfolderRequest);
//		System.out.println(result);
//		return result;
//	}



//	public static void main(String[] args) {
//		//statfoder("weixin","/");
//		//listfolder("weixin", "/aosmith/wechatDown/");
//		//createfolder("weixin","/aosmith/imagetext/","");
//		//delfolder("weixin","/aosmith/ueditor/");
//		//delfile("faye5", "/cf/wechatDown/bug1488852945698.jpg");
//		//System.out.println(JwThirdAPI.args("JOVDA-_Pas82uSItSJ2WSL3V02nXsHovmPqFWYfsmMViwAuv36pANGSsmK47WQ7JeqA42ILqyagaQsCxqcSzVhTeWWg6Kd3tUYfqPqewLayWL0QVnlU5zQsKPGlzPLlLGYLgAAACUH"));
//		try {
//			String url="http://car2.autoimg.cn/cardfs/product/g9/M09/21/AE/1024x0_1_q87_autohomecar__wKjBzljBLyaADVYGAAalL_sYr-A594.jpg";
//			HttpURLConnection conn = (HttpURLConnection) new URL(url)
//					.openConnection();
//			conn.setReadTimeout(5000);
//			conn.setConnectTimeout(5000);
//			conn.setRequestMethod("GET");
//
//			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
//				InputStream inputStream = conn.getInputStream();
//				UploadFileRequest uploadFileRequest = new UploadFileRequest(BUCKETNAME, "/1/2.jpg", "");
//				ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
//				byte[] buff = new byte[100];
//				int rc = 0;
//				while ((rc = inputStream.read(buff, 0, 100)) > 0) {
//					swapStream.write(buff, 0, rc);
//				}
//				byte[] in2b = swapStream.toByteArray();
//				uploadFileRequest.setContentBufer(in2b);
//				String s=upload(uploadFileRequest);
//				System.out.print(s);
//			}
//
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//
//	}

}
