package com.bonait.bnframework.common.oss;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSFederationToken;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bonait.bnframework.business.ConfigData;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.helper.I.IRun;
import com.bonait.bnframework.common.helper.I.IRunT;
import com.bonait.bnframework.common.image.utils.LocalCacheUtils;
import com.bonait.bnframework.common.model.ResAPI;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * OSS 上传帮助
 */
public class OssHelper {

    //region 私有
    private static OssHelper mInstance; //实例变量设置私有，防止直接通过类名访问

    public static synchronized OssHelper getInstance() { //静态同步方法作为唯一的实例对象获取方式
        if (mInstance == null) {
            mInstance = new OssHelper();
        }
        return mInstance;
    }

    private OssHelper() { //默认构造函数私有，防止类外直接new创建对象
        Init();
    }
    //endregion

    //region 变量
    public String AppId = "1305371387";
    public String Region = "ap-chengdu";
    public String Bucket = "hbl-test-1305371387";
    public String SecretId = "AKIDa4KQIvKUP6bw4ye6JI3a8lCPN7cswnV3";
    public String SecretKey = "ObaLtCH9nCNPFrFQO7ex2sTqyxlLgnfJ";


    //endregion

    public void Init() {

    }

    /**
     * 上传完成通知
     */
    public IRunT OnCharge;
    private static final String CACHE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/hblxiaochaodb/WebImage";

    /**
     * 上传文件
     *
     * @param context
     * @param fileurl
     */
    public void UpdataFile(Context context, String fileurl) {
        try {
            ResAPI<String> res = new ResAPI<String>();
            if (isHttpUrl(fileurl)) {
                res.succeeded = false;
                res.data = fileurl;
                if (OnCharge != null)
                    OnCharge.Run(res);
                return;
            } else {
                File file = new File(CACHE_PATH, fileurl);
                String name = "Franchisee/" + ConfigName.getInstance().organizeMode.store_Name + "/goods/android/";
                String filename = "https://hbl-test-1305371387.cos.ap-chengdu.myqcloud.com/" + name + file.getName();
                // 第一个参数：在【RAM访问控制】创建用户时分配的accessKeyId
                // 第二个参数：在【RAM访问控制】创建用户时分配的accessKeySecret
                OSSCredentialProvider ossCredentialProvider = new OSSPlainTextAKSKCredentialProvider(SecretId, SecretKey);
                // 第一个参数：上下文
                // 第二个参数：在OSS控制台创建好Bucket后，会有一个EndPoint(地域节点)，比如我这里的节点是：http://oss-cn-shanghai.aliyuncs.com
                // 第三个参数：OSSCredentialProvider
                OSS oss = new OSSClient(context, "https://hbl-test-1305371387.cos.ap-chengdu.myqcloud.com", ossCredentialProvider);
                // 第二个参数：可以是一个文件路径：比如你在image-header创建了一个文件夹为images,那第二个参数传images/img.jpg
                // 第三个参数：是文件的本地路径，比如我这里在本地路径中是姨丈图片，路径是sdcard/img/img.jpg
                PutObjectRequest put = new PutObjectRequest(Bucket, name + file.getName(), file.getPath());
                // 异步上传时可以设置进度回调。
                put.setProgressCallback((request, currentSize, totalSize) -> {
                    Log.d("currentSize = " + currentSize, "totalSize = " + totalSize);
                });
                // 此处调用异步上传方法
                OSSAsyncTask ossAsyncTask = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                    @Override
                    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                        Log.d("PutObject", "UploadSuccess");
                        Log.d("ETag", result.getETag());
                        Log.d("RequestId", result.getRequestId());
                        res.succeeded = true;
                        res.data = filename;
                        if (OnCharge != null)
                            OnCharge.Run(res);
                    }

                    @Override
                    public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                        // 请求异常。
                        if (clientException != null) {
                            // 本地异常，如网络异常等。
                            Log.e("如网络异常等", clientException.getMessage());
                            res.succeeded = false;
                            res.data = fileurl;
                            if (OnCharge != null)
                                OnCharge.Run(res);
                        }
                        if (serviceException != null) {
                            // 服务异常。
                            Log.e("ErrorCode", serviceException.getErrorCode());
                            Log.e("RequestId", serviceException.getRequestId());
                            Log.e("HostId", serviceException.getHostId());
                            Log.e("RawMessage", serviceException.getRawMessage());
                            res.succeeded = false;
                            res.data = fileurl;
                            if (OnCharge != null)
                                OnCharge.Run(res);
                        }
                    }
                });
            }

        } catch (Exception ex) {

        }
    }

    /**
     * 判断字符串是否为URL
     *
     * @param urls 需要判断的String类型url
     * @return true:是URL；false:不是URL
     */
    public static boolean isHttpUrl(String urls) {
        boolean isurl = false;
        //设置正则表达式
        String regex = "(((https|http)?://)?([a-z0-9]+[.])|(www.))"
                + "\\w+[.|\\/]([a-z0-9]{0,})?[[.]([a-z0-9]{0,})]+((/[\\S&&[^,;\u4E00-\u9FA5]]+)+)?([.][a-z0-9]{0,}+|/?)";
        //对比
        Pattern pat = Pattern.compile(regex.trim());
        Matcher mat = pat.matcher(urls.trim());
        //判断是否匹配
        isurl = mat.matches();
        if (isurl) {
            isurl = true;
        }
        return isurl;
    }
}
