package com.fxy.common;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.elvishew.xlog.XLog;
import com.fxy.baselibrary.bean.BaseEventBusBean;
import com.fxy.baselibrary.util.JsonUtil;
import com.fxy.baselibrary.util.RxTimeTool;
import com.fxy.bean.ActionBean;
import com.fxy.constant.EventCode;
import com.fxy.constant.SPCache;
import com.fxy.net.MyDialogCallback;
import com.fxy.realm.AsyncUploadRealm;
import com.fxy.utils.UploadUtils;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import io.realm.Realm;
import io.realm.RealmResults;

public class AsyncFileUpload {

    private final Context mContext;
     private String uploadType = "";
    //文件上传类型
    protected String fileKey = "";


    protected Realm mRealm;
    private List<AsyncUploadRealm> awaitUploadList=new ArrayList<>();

    //全部重推
    private boolean isAllRePush =false;


    private OssService ossService;


    private boolean allowUpload = true;



    public AsyncFileUpload(Context context){
        mContext = context;
        initData();
    }



    private void initData() {
        mRealm = Realm.getDefaultInstance();
    }


    public void setUploadType(String fileKey) {
        this.fileKey = fileKey;
    }

    public void setIsAllRePush(){
        isAllRePush = true;
    }

    @SuppressLint("HandlerLeak")
    private Handler uploadHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            HashMap<String,Object> hashMap = new HashMap<>();
            hashMap.put("fileKey",fileKey);
            boolean result = false;
            try {

                //XLog.e(msg);
                int current = (Integer) msg.arg1;

                switch (msg.what){
                    case 0:
                         break;
                    case 1://失败

                        if (awaitUploadList.size()>0){

                            AsyncUploadRealm asyncUploadRealm = awaitUploadList.get(current);
                            awaitUploadList.remove(current);
                            resultUpload(asyncUploadRealm.getId(),0,"");
                            hashMap.put("error",(String) msg.obj);
                            hashMap.put("result","error");
                            hashMap.put("realmId",asyncUploadRealm.getId());
                        }

                        break;
                    case 2://成功
                        result = true;
                        //表示数据存在
                        if (awaitUploadList.size()>0){
                            AsyncUploadRealm asyncUploadRealm = awaitUploadList.get(current);
                            awaitUploadList.remove(current);
                            resultUpload(asyncUploadRealm.getId(),1,(String) msg.obj);
                            hashMap.put("result","success");
                            hashMap.put("realmId",asyncUploadRealm.getId());
                        }
                        break;
                    case 3:
                        //设置进度条
                        EventBus.getDefault().post(new UploadProgressEvent(msg.arg2));

                        hashMap.put("result","process");
                        hashMap.put("process",(int)msg.arg2);
                        if (awaitUploadList.get(current)!=null){
                            hashMap.put("realmId",awaitUploadList.get(current).getId());
                        }

                        EventBus.getDefault().post(new BaseEventBusBean<>(EventCode.file_upload_progress_lister,hashMap));
                        return;
                        //progressDialog.show();
                    case 4:
                        //获取上传状态
                        return;
                    default:
                        break;
                }




            } catch (Exception e) {
                XLog.e(e.getMessage());
                e.printStackTrace();
                // 通过接口对象传上传状态
                hashMap.put("error",e.getMessage());
            }

            hashMap.put("result",false);
            EventBus.getDefault().post(new BaseEventBusBean<>(EventCode.file_upload_lister,hashMap));
        }
    };




    // 调用回调方法
    //uploadChangeListener.uploadResult(false);

    public void filedUpload(int num){


        // 例如 LocalMedia 里面返回三种path
        // 1.media.getPath(); 为原图path
        // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
        // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
        // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
        LocalMedia localMedia = awaitUploadList.get(num).getLocalMedia();
        String urlPath =localMedia.getPath();
        if (urlPath.isEmpty()){
            Message msg = new Message();
            msg.obj = "文件路径不存在";
            msg.what = 1;
            uploadHandler.sendMessage(msg);
            return;
        }

        if (localMedia.isCompressed() && localMedia.getCompressPath()!=null){
            if (new File(localMedia.getCompressPath()).exists()){
                urlPath = localMedia.getCompressPath();
            }
        }



        String fileName = "";
        String path_prefix = "";

        String ossUrl = awaitUploadList.get(num).getOssUrl();
        fileKey = awaitUploadList.get(num).getNotifyKey();

        //目录为空
        if (ossUrl.isEmpty()){
            setPushStatus(awaitUploadList.get(num).getId(),1,1);
            if (awaitUploadList.size()>0){
                resultUpload(awaitUploadList.get(num).getId(),0,"");
            }


            return;
        }



        String[] urlArr = ossUrl.split("/");
        fileName = urlArr[urlArr.length-1];

        //用户循环路径
        for (int i = 0; i <urlArr.length -1  ; i++) {
            if (!urlArr[i].isEmpty()){
                path_prefix =   path_prefix.concat(urlArr[i]).concat("/");
            }
        }



        if (ossService ==null){
            ossService = new OssService(mContext,path_prefix);
        }

        ossService.ossUpload(urlPath, fileName , num,uploadHandler,path_prefix);
        //ossService.ossUpload(urlPath, fileName , num,uploadHandler);
        setIsFinish(awaitUploadList.get(num).getId(),1);
    }



    public int getAwaitNum(){
        RealmResults<AsyncUploadRealm> realmResults  = mRealm.where(AsyncUploadRealm.class)
                .equalTo("isDelete",0)
                .equalTo("pushStatus",0)
                .equalTo("uploadType",uploadType)
                .sort("pushStatus").findAll();
        realmResults.load();
        return  realmResults.size();
    }

    public int getAwaitNum(String[] uploadTypeList){
        RealmResults<AsyncUploadRealm> realmResults  = mRealm.where(AsyncUploadRealm.class)
                .equalTo("isDelete",0)
                .equalTo("pushStatus",0)
                .in("uploadType",uploadTypeList)
                .sort("pushStatus").findAll();
        realmResults.load();
        return  realmResults.size();
    }

    public int getAllAwaitNum(){

        RealmResults<AsyncUploadRealm> realmResults  = mRealm.where(AsyncUploadRealm.class)
                .equalTo("isDelete",0)
                .equalTo("pushStatus",0)
                .sort("pushStatus").findAll();
        realmResults.load();
        return  realmResults.size();
    }
    public int getAllAwaitNum(Integer[] pushStatus){

        RealmResults<AsyncUploadRealm> realmResults  = mRealm.where(AsyncUploadRealm.class)
                .equalTo("isDelete",0)
                .in("pushStatus",pushStatus)
                .sort("pushStatus").findAll();
        realmResults.load();
        return  realmResults.size();
    }


    //存储数据问题
    private void asyncUpload(){
        if (awaitUploadList==null || awaitUploadList.size()==0){
            Integer[] isFinish = {0,2};
            RealmResults<AsyncUploadRealm> realmResults  = getBatchUploadRealm(isFinish);
            if (realmResults.size()==0){
                Integer[] isFinish2 = {0,1,2};
                realmResults  = getBatchUploadRealm(isFinish2);
            }
            awaitUploadList.addAll(realmResults);
        }



        if (awaitUploadList.size()>0){
            filedUpload(0);
        }else{
            removeHandler();
        }
    }


    //取消任务
    public void taskCancel(){

    }

    public void setStartUpload(){
        allowUpload = true;
        if (UploadUtils.getUploadExists(mContext)){
            UploadUtils.delInterfaceRequestTime(mContext);
            asyncUpload();
        }else{
            XLog.d("AsyncFileUpload当前有任务正在上传");
        }

    }

    public void setStopUpload(){
        allowUpload = false;
        if(ossService !=null){
            ossService.taskCancel();
        }
        EventBus.getDefault().post(new UploadProgressEvent(0));
    }

    /**
     * 设置是否完成
     * @param realmId String
     * @param  isFinish Integer
     */
    private void setIsFinish(String realmId,Integer isFinish){
        //更新值
        mRealm.beginTransaction();
        AsyncUploadRealm myObject = mRealm.where(AsyncUploadRealm.class).equalTo("id",realmId).findFirst();
        assert myObject != null;
        myObject.setIsFinish(isFinish);
        mRealm.commitTransaction();
    }

    private RealmResults<AsyncUploadRealm> getBatchUploadRealm(Integer[] isFinish){
        //更新值
        RealmResults<AsyncUploadRealm> realmResults  = mRealm.where(AsyncUploadRealm.class)
                .equalTo("isDelete",0)
                .equalTo("pushStatus",0)
                .in("isFinish",isFinish)
//                    .equalTo("notifyKey",fileKey)
//                    .equalTo("uploadType",uploadType)
                .sort("pushStatus").findAll();
        realmResults.load();
        return realmResults;
    }


    /**
     * 上传结果
     * @param tmpRealmId String
     * @param status Integer
     * @param photoPath String
     */
    private void resultUpload(String tmpRealmId,Integer status,String photoPath){
        if (tmpRealmId!=null && !tmpRealmId.isEmpty()){
            //遍历删除
            if (awaitUploadList.size()>0){
                for (int i=0;i<awaitUploadList.size();i++){
                    if (awaitUploadList.get(i).getId().equals(tmpRealmId)){
                        awaitUploadList.remove(i);
                        break;
                    }
                }
            }


            //更新值
            mRealm.beginTransaction();
            AsyncUploadRealm myObject = mRealm.where(AsyncUploadRealm.class).equalTo("id",tmpRealmId).findFirst();
            assert myObject != null;
            int pushStatus = 2;
            int rePush = myObject.getRePush();
            if (status==0){
                pushStatus = rePush>4 ? 1 : 0;
            }

            if (myObject.getPushStatus()!=3){
                myObject.setPushStatus(pushStatus);
            }
            //已完成则不需要再更新
            if (myObject.getIsFinish() != 3){
                myObject.setIsFinish( status == 1 ? 3 : 2);
            }
            if (status == 1){
                myObject.setOssUrl(photoPath);
            }else{
                myObject.setRePush(myObject.getRePush()+1);
            }


            mRealm.commitTransaction();

        }

        allowUpload = UploadUtils.getUploadIsContinue(mContext);
        //可以允许上传
        if (allowUpload){
            //上传完，继续执行
            asyncUpload();
        }else{
            awaitUploadList.clear();
        }

    }
    private void setPushStatus(String realmId,Integer pushStatus,int isDelete){
        //更新值
        mRealm.beginTransaction();
        AsyncUploadRealm myObject = mRealm.where(AsyncUploadRealm.class).equalTo("id",realmId).findFirst();
        assert myObject != null;
        myObject.setPushStatus(pushStatus);
        myObject.setIsDelete(isDelete);

        mRealm.commitTransaction();
    }

    /**
     * 获取待上传数量
     * @return
     */
    public int getAwaitUploadListNum(){
        return  awaitUploadList.size();
    }

    //销毁
    public void removeHandler(){
        if (uploadHandler!=null){
            uploadHandler.removeCallbacksAndMessages(null);
        }
    }
}
