package com.fxy.common;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.elvishew.xlog.XLog;
import com.fxy.baselibrary.util.RxTimeTool;
import com.fxy.R;
import com.fxy.bean.UploadResultBean;
import com.fxy.constant.SPCache;

import org.json.JSONObject;

import java.util.UUID;

public class FiledUpload {
    private Activity mActivity;
    private Context mContext;
    // 图片上传目录
    private String mPrefix="default";

    //是否停止上传
    private String resourceUrl = "";
    private String resourceType = "";
    private String resourcePrefix = "";

    private ProgressDialog progressDialog;
    private OssService ossService;
    private CosService cosService;

    public FiledUpload(Activity activity, String prefix){
        mActivity = activity;
        mContext  = activity.getBaseContext();
        mPrefix = prefix;
        initData();
    }
    private void initData() {
        SPCache spCache = SPCache.getInstance(mContext);
        resourceUrl    = spCache.getResourceHost()+"/";
        resourceType   = spCache.getResourceType();
        resourcePrefix = spCache.getResourcePrefix();
    }

    private void closeDialog(){
        if (progressDialog != null && !progressDialog.isIndeterminate() && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
    @SuppressLint("HandlerLeak")
    private final Handler uploadHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                //XLog.e(msg);
                JSONObject jsonObject = new JSONObject();

                switch (msg.what){
                    case 0:
                        Toast.makeText(mActivity, "error", Toast.LENGTH_SHORT).show();
                        break;
                    case 1://失败
                        String message = (String) msg.obj;
                        if (!message.isEmpty()){
                            Toast.makeText(mActivity, message, Toast.LENGTH_SHORT).show();
                        }
                        if (uploadChangeListener!=null){
                            UploadResultBean uploadResultBean = new UploadResultBean();
                            uploadResultBean.setMsg("上传失败");
                            uploadResultBean.setError(message);
                            uploadResultBean.setStatus(0);
                            uploadChangeListener.uploadResult(uploadResultBean);
                        }
                        break;
                    case 2://成功
                        String file_path = (String) msg.obj;
                        //表示数据存在
                        Toast.makeText(mActivity, "上传成功", Toast.LENGTH_SHORT).show();
                        // 通过接口对象传上传状态
                        if (uploadChangeListener!=null){
                            UploadResultBean uploadResultBean = new UploadResultBean();
                            uploadResultBean.setMsg("上传成功");
                            uploadResultBean.setPath(file_path);
                            uploadResultBean.setStatus(1);
                            uploadChangeListener.uploadResult(uploadResultBean);
                        }
                        break;
                    case 3:
                        //设置进度条
                        progressDialog.setProgress(msg.arg2);
                        //progressDialog.show();
                        return;
                    case 4:
                        //获取上传状态

                        return;
                    default:
                        break;
                }
                closeDialog();

            } catch (Exception e) {
                XLog.e(e.getMessage());
                e.printStackTrace();
            }
        }
    };
    //取消任务
    public void taskCancel(){

        new AlertDialog.Builder(mActivity)
                .setTitle(R.string.dl_hint)
                .setMessage("确定取消上传,并且清空所有上传任务?")
                .setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                }).setPositiveButton(R.string.str_submit, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                //取消上传任务
                if (resourceType.equals("tencent")){
                    cosService.taskCancel();
                }else{
                    ossService.taskCancel();
                }
            }
        }).show();

        //task.waitUntilFinished(); // 等待任务完成。
    }


    // 持有一个接口对象
    UploadChangeListener uploadChangeListener;

    // 状态变化监听
    public interface UploadChangeListener {
        // 回调方法 可以多个
        void uploadResult(UploadResultBean uploadResultBean);
    }
    // 提供注册事件监听的方法
    public void setOnChangeListener(UploadChangeListener uploadChangeListener) {
        this.uploadChangeListener = uploadChangeListener;
    }

    private String getFileName(String localPath){
        String fileSuffix = "";
        if (localPath.lastIndexOf(".")>-1) {
            // 获取文件后缀名
            fileSuffix = localPath.substring(localPath.lastIndexOf("."));
        }
        String fileName= UUID.randomUUID().toString() + fileSuffix;
        return fileName;
    }

    public void filedUpload(String urlPath){
        filedUpload(urlPath,getFileName(urlPath));
    }
    public void filedUpload(String urlPath,String fileName){

        progressDialog = new ProgressDialog(mActivity);
        progressDialog.setTitle("文件准备上传");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        //设置对话框执行内容
        progressDialog.show();
        //监听取消事件
        progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                // TODO Auto-generated method stub
                taskCancel();
            }

        });


        if (resourceType.equals("tencent")){
            if (cosService==null){
                String path_prefix = resourcePrefix+"/android/"+mPrefix+"/"+ RxTimeTool.getYestoryDate("yyyyMMd")+"/";
                cosService  = new CosService(mActivity.getBaseContext(),path_prefix);
            }
            //new cosThread(urlPath, fileName , num).start();
            cosService.cosUpload(urlPath, fileName , 0,uploadHandler);
        }else{
            if (ossService ==null){
                ossService = new OssService(mActivity,mPrefix);
            }
            ossService.ossUpload(urlPath, fileName , 0,uploadHandler);
            //new ossThread(urlPath, fileName , num).start();
        }
    }


    /**
     * 只操作上传
     * @param localPath
     * @param handler
     * @param sort
     */
    public void filedUpload(String localPath,Handler handler,int sort){
        String fileName = getFileName(localPath);
        if (resourceType.equals("tencent")){
            if (cosService==null){
                String path_prefix = resourcePrefix+"/android/"+mPrefix+"/"+ RxTimeTool.getYestoryDate("yyyyMMd")+"/";
                cosService  = new CosService(mActivity.getBaseContext(),path_prefix);
            }
            cosService.cosUpload(localPath, fileName , sort,handler);
        }else{
            if (ossService ==null){
                ossService = new OssService(mActivity,mPrefix);
            }
            ossService.ossUpload(localPath, fileName , sort,handler);
        }
    }

}
