package com.fxy.common;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.elvishew.xlog.XLog;
import com.fxy.BuildConfig;
import com.fxy.constant.SPCache;
import com.fxy.net.Urls;
import com.tencent.cos.xml.CosXmlServiceConfig;
import com.tencent.cos.xml.CosXmlSimpleService;
import com.tencent.cos.xml.exception.CosXmlClientException;
import com.tencent.cos.xml.exception.CosXmlServiceException;
import com.tencent.cos.xml.listener.CosXmlProgressListener;
import com.tencent.cos.xml.listener.CosXmlResultListener;
import com.tencent.cos.xml.model.CosXmlRequest;
import com.tencent.cos.xml.model.CosXmlResult;
import com.tencent.cos.xml.transfer.COSXMLUploadTask;
import com.tencent.cos.xml.transfer.TransferConfig;
import com.tencent.cos.xml.transfer.TransferManager;
import com.tencent.cos.xml.transfer.TransferState;
import com.tencent.cos.xml.transfer.TransferStateListener;
import com.tencent.qcloud.core.auth.QCloudCredentialProvider;
import com.tencent.qcloud.core.auth.SessionCredentialProvider;
import com.tencent.qcloud.core.http.HttpRequest;

import java.net.MalformedURLException;
import java.net.URL;

public class CosService {
    private  Context mContext;

    private String bucketName = "";
    private String path_prefix = "";
    // 存储桶所在地域简称，例如广州地区是 ap-guangzhou
    private String regionId = "";
    // 创建 CosXmlServiceConfig 对象，根据需要修改默认的配置参数
    private CosXmlServiceConfig serviceConfig ;
    // 初始化 COS Service，获取实例
    private CosXmlSimpleService cosXmlService ;
    private COSXMLUploadTask cosxmlUploadTask;

    public CosService(Context context,String prefix){
        mContext = context;


        SPCache spCache = SPCache.getInstance(mContext);
        String cosHost = spCache.getResourceHost();
        String  resource_prefix = spCache.getResourcePrefix();
        //上传路径确保前缀
        if (!resource_prefix.contains(resource_prefix)){
            prefix = resource_prefix+prefix;
        }

        //zj-1304592070.cos.ap-singapore.myqcloud.com
        bucketName = spCache.getResourceBucket();
        regionId   = spCache.getResourceRegion();
        path_prefix = prefix;
        creationCos();


    }


    public CosXmlSimpleService creationCos(){
        URL url = null; // 后台授权服务的 url 地址
        try {
            url = new URL(Urls.getServiceAddress(mContext)+ Urls.FMS_UPLOAD_SIGN);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        QCloudCredentialProvider credentialProvider = new SessionCredentialProvider(new HttpRequest.Builder<String>()
                .url(url)
                .method("GET")
                .addHeader("warehouse-id",SPCache.getInstance(mContext).getWareHouseId())
                .addHeader("version","999999")
                .addHeader("token",SPCache.getInstance(mContext).getToken())
                .encodedQuery("path_prefix",path_prefix+"*")
                .build());

        serviceConfig = new CosXmlServiceConfig.Builder()
                .setRegion(regionId)
                .isHttps(true) // 使用 HTTPS 请求, 默认为 HTTP 请求
                .builder();
        cosXmlService = new CosXmlSimpleService(mContext,serviceConfig, credentialProvider);
        return cosXmlService;
    }

    public void cosUpload(String filePath, String uploadName , int num, Handler handler){
        new CosThread(filePath, uploadName , num,handler).start();
    }
    //取消上传
    public void taskCancel(){
        if (cosxmlUploadTask!=null){
            boolean pauseSuccess = cosxmlUploadTask.pauseSafely();
            if (pauseSuccess){
                cosxmlUploadTask.cancel();
            }
        }
    }

    //腾讯云cos上传
    class CosThread extends Thread {
        private String urlPath = "";
        private String fileName = "";
        private int current = 0;
        private Handler uploadHandler ;
        // 若存在初始化分块上传的 UploadId，则赋值对应的 uploadId 值用于续传；否则，赋值 null
        private String uploadId = null;
        /**
         *
         * @param filePath 本地文件路径
         * @param uploadName 上传后文件名
         * @param num 序号
         */
        public CosThread(String filePath, String uploadName , int num, Handler handler) {
            urlPath = filePath;
            fileName = uploadName;
            current = num;
            uploadHandler = handler;
        }
        public void run() {
            // 初始化 TransferConfig，这里使用默认配置，如果需要定制，请参考 SDK 接口文档
            TransferConfig transferConfig = new TransferConfig.Builder().build();
            // 初始化 TransferManager
            TransferManager transferManager = new TransferManager(getCosXmlService(), transferConfig);
            String bucket = getBucketName(); //存储桶，格式：BucketName-APPID
            String cosPath = getCosPath()+fileName; //对象在存储桶中的位置标识符，即称对象键
            //String srcPath = new File(mContext.getCacheDir(), urlPath).toString(); //本地文件的绝对路径

            // 上传文件
            cosxmlUploadTask = transferManager.upload(bucket, cosPath,urlPath, uploadId);
            //设置上传进度回调
            cosxmlUploadTask.setCosXmlProgressListener(new CosXmlProgressListener() {
                @Override
                public void onProgress(long complete, long target) {
                    // todo Do something to update progress...
                    int progress = (int) ((double) complete / (double) target * 100);
                    Message msg = new Message();
                    msg.arg1 = current;
                    msg.arg2 = progress;
                    msg.what = 3;
                    uploadHandler.sendMessage(msg);

                }
            });
            //设置返回结果回调
            cosxmlUploadTask.setCosXmlResultListener(new CosXmlResultListener() {
                @Override
                public void onSuccess(CosXmlRequest request, CosXmlResult result) {
                    if (BuildConfig.DEBUG){
                        XLog.e(result);
                    }

                    //COSXMLUploadTask.COSXMLUploadTaskResult cOSXMLUploadTaskResult = (COSXMLUploadTask.COSXMLUploadTaskResult) result;
                    String[] accessUrlArr = result.accessUrl.split(".myqcloud.com");
                    Message msg = new Message();
                    msg.arg1 = current;
                    msg.obj = accessUrlArr[1];
                    msg.what = 2;
                    uploadHandler.sendMessage(msg);
                }
                @Override
                public void onFail(CosXmlRequest request, CosXmlClientException clientException, CosXmlServiceException serviceException) {
                    Message msg = new Message();
                    msg.what = 1;
                    if (clientException != null) {
                        // 本地异常，如网络异常等。
                        msg.obj = "网络异常，请稍后...";
                        uploadHandler.sendMessage(msg);
                        //clientException.printStackTrace();
                    } else {
                        msg.obj = "服务异常，请稍后...";
                        uploadHandler.sendMessage(msg);
                        //serviceException.printStackTrace();
                        XLog.e("ErrorCode", serviceException.getErrorCode());
                        XLog.e("RequestId", serviceException.getRequestId());
                        XLog.e("tLocalizedMessage", serviceException.getLocalizedMessage());
                        XLog.e("Message", serviceException.getMessage());
                    }
                }
            });
            //设置任务状态回调, 可以查看任务过程
            cosxmlUploadTask.setTransferStateListener(new TransferStateListener() {
                @Override
                public void onStateChanged(TransferState state) {
                    // todo notify transfer state
                    if (BuildConfig.DEBUG){
                        XLog.e(state);
                    }
                    Message msg = new Message();
                    msg.arg1 = current;
                    msg.obj = state;
                    msg.what = 5;
                    uploadHandler.sendMessage(msg);
                }
            });
        }
    }

    /**
     *  返回  cosXmlService
     * @return
     */
    public CosXmlSimpleService getCosXmlService(){
        return  cosXmlService;
    }

    public String getBucketName(){
        return bucketName;
    }

    public String getCosPath(){
        return path_prefix;
    }
}
