package com.fxy.common;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.elvishew.xlog.XLog;
import com.fxy.R;
import com.fxy.adapter.GridImageAdapter;
import com.fxy.baselibrary.bean.BaseEventBusBean;
import com.fxy.baselibrary.util.DateUtil;
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.view.FullyGridLayoutManager;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.Permission;
import com.luck.picture.lib.permissions.RxPermissions;
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.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import io.reactivex.functions.Consumer;
import io.realm.Realm;
import io.realm.RealmQuery;
import io.realm.RealmResults;

public class AsyncPictureUpload {
    private final Activity mActivity;
    private final Context mContext;


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

    //通知地址
    private String notifyUrl = "";

    //唯一标识
    private String uniqueTag = "";

    //通知地址
    private HashMap<String, Object> notifyParam  = new HashMap<>();


    private HashMap<String, Object> limitOperate  = new HashMap<>();

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


    //
    private List<LocalMedia> selectList = new ArrayList<>();
    //上传图片路径
    private ArrayList<String> ossPhotoList =new ArrayList<>();

    private String mPrefix="tally";

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

    private String resourceType = "";

    private String resourcePrefix = "/fxy";

    private OssService ossService;

    private CosService cosService;

    private boolean allowUpload = true;

    //
    private boolean isAllRe =false;

    private boolean debug = false;
    public void setDebug(boolean debug) {
        this.debug = debug;
    }
    public AsyncPictureUpload(Activity activity){
        mActivity = activity;
        mContext  = activity.getBaseContext();
        initData();
    }



    private void initData() {
        SPCache spCache = SPCache.getInstance(mContext);
        resourceUrl    = spCache.getResourceHost()+"/";
        resourceType   = spCache.getResourceType();
        resourcePrefix = spCache.getResourcePrefix();
        mRealm = Realm.getDefaultInstance();
        if (mActivity != null && mActivity.getClass()!=null){
            uploadType = mActivity.getClass().getSimpleName();
        }

        limitOperate = new HashMap<>();
        uniqueTag =  this.fileKey+UUID.randomUUID().toString();
    }



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



    public void  setNotifyParam( HashMap<String, Object> map){
        this.notifyParam = map;
    }

    //操作限制
    public void setLimitOperate(HashMap<String, Object> map){
        this.limitOperate = map;
    }



    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();
    }

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

    /**
     * 获取所有待推送数据
     * @return
     */
    public int getAllAwaitNum(){

        if (isAllRe){
            Integer[] pushStatus = {0,1};
            RealmResults<AsyncUploadRealm> realmResults  = mRealm.where(AsyncUploadRealm.class)
                    .equalTo("isDelete",0)
                    .in("pushStatus",pushStatus)
                    .sort("pushStatus").findAll();
            realmResults.load();
            return  realmResults.size();
        }else{
            RealmResults<AsyncUploadRealm> realmResults  = mRealm.where(AsyncUploadRealm.class)
                    .equalTo("isDelete",0)
                    .equalTo("pushStatus",0)
                    .sort("pushStatus").findAll();
            realmResults.load();
            return  realmResults.size();
        }

    }

    /**
     * 返回错误数量
     * @return int
     */
    public int getFailNum(){
        Integer[] pushStatus = {1};
        RealmResults<AsyncUploadRealm> realmResults  = mRealm.where(AsyncUploadRealm.class)
                .equalTo("isDelete",0)
                .in("pushStatus",pushStatus)
                .sort("pushStatus").findAll();
        realmResults.load();
        return  realmResults.size();
    }


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

             try {

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

                switch (msg.what){
                    case 0:
                        Toast.makeText(mActivity, "error", Toast.LENGTH_SHORT).show();
                        break;
                    case 1://失败

                        if (awaitUploadList.size()>0){

                            AsyncUploadRealm asyncUploadRealm = awaitUploadList.get(current);
                            awaitUploadList.remove(current);
                            resultUpload(asyncUploadRealm.getId(),0,"");
                            String message = (String) msg.obj;
                            if (!message.isEmpty() && mActivity!=null){
                                Toast.makeText(mActivity, message, Toast.LENGTH_SHORT).show();
                            }
                            hashMap.put("error",(String) msg.obj);
                            hashMap.put("result","error");
                            hashMap.put("realmId",asyncUploadRealm.getId());
                        }

                        break;
                    case 2://成功
                         //表示数据存在
                        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:
                        //设置进度条
                        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;
                    case 4:
                        //获取上传状态
                        return;
                    default:
                        break;
                }




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

             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()){
            setPushStatus(awaitUploadList.get(num).getId(),1,1);
            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();
            }
        }

        if (!new File(urlPath).exists()){
            XLog.d("文件不存在本地路径"+urlPath+",拍照时间："+awaitUploadList.get(num).getCreateTime());
            setPushStatus(awaitUploadList.get(num).getId(),1,1);
            Message msg = new Message();
            msg.obj = "文件路径不存在";
            msg.what = 1;
            uploadHandler.sendMessage(msg);
            return;
        }


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

        String ossUrl = awaitUploadList.get(num).getOssUrl();
        fileKey = awaitUploadList.get(num).getNotifyKey();
        if (!ossUrl.isEmpty()){
            // 找到最后一个斜杠的位置
            int lastSlashIndex = ossUrl.lastIndexOf('/');
            // 如果找到了斜杠，则从斜杠之后的位置开始切割
            fileName = ossUrl.substring(lastSlashIndex + 1);

            //斜杆开始不允许
            int firstSlashIndex = ossUrl.indexOf('/');
            if (firstSlashIndex==0){
                path_prefix = ossUrl.substring(1,lastSlashIndex+ 1);
            }else{
                path_prefix = ossUrl.substring(0,lastSlashIndex+ 1);
            }



        }else{
            path_prefix = resourcePrefix+"/android/"+mPrefix+"/"+RxTimeTool.getYestoryDate("yyyyMMd")+"/";
            String fileSuffix = urlPath.lastIndexOf(".")>-1 ? urlPath.substring(urlPath.lastIndexOf(".")) : "";
            fileName = UUID.randomUUID().toString() + fileSuffix;
        }


        if (resourceType.equals("tencent")){
            if (cosService==null){
                cosService  = new CosService(mActivity.getBaseContext(),path_prefix);
            }
            //new cosThread(urlPath, fileName , num).start();
            cosService.cosUpload(urlPath, fileName , num,uploadHandler,path_prefix);

        }else{
            if (ossService ==null){
                ossService = new OssService(mActivity,path_prefix);
            }
            ossService.ossUpload(urlPath, fileName , num,uploadHandler,path_prefix);
            //ossService.ossUpload(urlPath, fileName , num,uploadHandler);

        }
        // task.cancel(); // 可以取消任务
        // task.waitUntilFinished(); // 可以等待直到任务完成
    }







    //存储数据问题
    private void asyncUpload(){

        if (!getIsNetwork()){
            //无网络时在请求检查是否有网络
            return;
        }

        if (awaitUploadList==null || awaitUploadList.size()==0){
            Integer[] isFinish = {0,2};
            RealmResults<AsyncUploadRealm> realmResults  = getBatchUploadRealm();
            awaitUploadList.addAll(realmResults);
        }

        //@todo 临时处理数据用
        tmpData();

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

    //临时处理数据用
    private void tmpData(){
        if (awaitUploadList.size()==0 && debug){
            String[] ossUrlList = {
                    "/uat/fxy/android/tally/20240924/57058c6a-6f59-4e6d-a93c-7a8044f9a721.JPEG"

                    ,"/prod/fxy/android/detection/20240923/d3e5552e-344c-4c74-be91-468cbb22f22c.JPEG"
                    ,"/prod/fxy/android/detection/20240923/893d8514-de5a-44bd-822a-c82959d11913.JPEG"
                    ,"/prod/fxy/android/detection/20240923/d0346866-d994-476c-8229-06aadb118eea.JPEG"
                    ,"/prod/fxy/android/detection/20240923/8d4f6893-e325-433a-9f78-0844d7b6b331.JPEG"
                    ,"/prod/fxy/android/detection/20240923/ac92069b-895e-45ad-b507-0494336be03a.JPEG"
                    ,"/prod/fxy/android/detection/20240923/3f2cd16c-59fb-40d5-bcf3-c969f7cbbb5c.JPEG"
                    ,"/prod/fxy/android/detection/20240923/47ef4d43-6fe6-4040-a5ec-8b9732ba5100.JPEG"
                    ,"/prod/fxy/android/detection/20240923/39284eae-b033-4e7d-a17c-e85c43931b6c.JPEG"
                    ,"/prod/fxy/android/detection/20240923/bd8c0f51-c211-458e-80d2-591b3fd7f25b.JPEG"
                    ,"/prod/fxy/android/detection/20240923/33f57a98-b86d-4b11-aca5-142042acfa77.JPEG"
                    ,"/prod/fxy/android/detection/20240923/4b611cbf-6273-43e1-81b0-120cf86dca53.JPEG"
                    ,"/prod/fxy/android/detection/20240923/63910671-cda0-4baf-a430-8bd3776c199a.JPEG"
                    ,"/prod/fxy/android/detection/20240924/b7e4125c-1c9b-4146-a11d-f2685c18e51f.JPEG"
                    ,"/prod/fxy/android/detection/20240924/5aeab08a-e938-4645-919b-41bcf3791502.JPEG"
                    ,"/prod/fxy/android/detection/20240924/f2d52733-2e21-4a54-9134-8cdf2ea2557b.JPEG"
                    ,"/prod/fxy/android/detection/20240924/0db0c21d-7b24-4781-95de-102ef7845ec8.JPEG"
                    ,"/prod/fxy/android/detection/20240924/3f81cbae-1b1e-4c6c-8f11-8a1c7c786f2f.JPEG"
                    ,"/prod/fxy/android/detection/20240924/289d314e-ad49-4c42-8be9-8156e6c673bd.JPEG"
                    ,"/prod/fxy/android/detection/20240924/73b82d21-1722-4692-94f5-b001c0b36fe9.JPEG"
                    ,"/prod/fxy/android/detection/20240924/9bd4bebb-04a4-4999-aefc-11092bafe653.JPEG"
                    ,"/prod/fxy/android/detection/20240924/9124f3ce-ab63-43f2-9e7c-d1b8fe037e65.JPEG"
                    ,"/prod/fxy/android/detection/20240924/b4931917-6851-4c18-82d3-f9010b81d84b.JPEG"
                    ,"/prod/fxy/android/detection/20240924/dbcc7133-793c-441e-9ef8-d4126372fc3d.JPEG"
                    ,"/prod/fxy/android/detection/20240924/cac07313-17e7-4ec4-b73b-cb8e42d171fa.JPEG"
                    ,"/prod/fxy/android/detection/20240923/e81da115-731b-418d-ba6d-ceac8f4eba7e.JPEG"
                    ,"/prod/fxy/android/detection/20240923/fdc1ee7d-1a56-4ee7-ac93-adba19df2845.JPEG"
                    ,"/prod/fxy/android/detection/20240923/92ccee22-a2ff-4e09-a836-238a8dc1f1cc.JPEG"
                    ,"/prod/fxy/android/detection/20240923/f9e6dcb4-62bd-425b-baf2-8db75c72223d.JPEG"
                    ,"/prod/fxy/android/detection/20240923/fe5fe3a3-595d-4127-96d1-6671e356a4fd.JPEG"
                    ,"/prod/fxy/android/detection/20240923/8bdc775d-bbd8-433d-a757-bf1523c9d3ff.JPEG"
                    ,"/prod/fxy/android/detection/20240923/29fc2776-9bdd-4c61-bf6e-21d1a6928bdc.JPEG"
                    ,"/prod/fxy/android/detection/20240923/e910bfbf-4110-4b96-a711-1323d76763fe.JPEG"
                    ,"/prod/fxy/android/detection/20240924/bfa8001a-c5e7-4db4-bd16-1d977fb9dae5.JPEG"
                    ,"/prod/fxy/android/detection/20240924/1fab9a47-51ee-4e73-9058-0a65e147d557.JPEG"
                    ,"/prod/fxy/android/detection/20240924/9d1a3561-4918-40fa-a44a-21a552936182.JPEG"
                    ,"/prod/fxy/android/detection/20240924/ce70f7f9-bcc1-452a-b4cf-cd583b4f62bf.JPEG"
                    ,"/prod/fxy/android/detection/20240924/68e40cfe-9e64-4258-8fb5-c3c160942247.JPEG"
                    ,"/prod/fxy/android/detection/20240924/4148331e-0b6e-4343-8fcf-a1f8e4ec8d8a.JPEG"
                    ,"/prod/fxy/android/detection/20240924/d5ceb788-7f9e-41c5-921f-a4ea4b7d17f8.JPEG"
                    ,"/prod/fxy/android/detection/20240924/2b05c0fe-8a1e-4fa3-8481-58877b6eda5e.JPEG"
                    ,"/prod/fxy/android/detection/20240924/dda38490-feaf-42d3-b6f9-c260a4915cc0.JPEG"
                    ,"/prod/fxy/android/detection/20240924/74587b04-3a0f-4d60-a009-7b6d77d7d302.JPEG"
                    ,"/prod/fxy/android/detection/20240924/d2feeeee-5078-49cc-934f-cedc794c8888.JPEG"
                    ,"/prod/fxy/android/detection/20240924/d6b76b2c-d778-4fa2-9485-c5f34142c7ce.JPEG"
                    ,"/prod/fxy/android/detection/20240924/b156f5a8-74a4-4329-9791-463acebabf34.JPEG"
                    ,"/prod/fxy/android/detection/20240924/56ac3bd7-3e06-4b1f-84c0-ff83571cc4d5.JPEG"
                    ,"/prod/fxy/android/detection/20240924/7f296e23-309a-4453-96b8-66403b04b73a.JPEG"
                    ,"/prod/fxy/android/detection/20240924/20cd6d0d-73dd-4ecf-b8e8-34110a0fa619.JPEG"
                    ,"/prod/fxy/android/detection/20240924/96a7b5ef-cbcf-4550-89b3-fea48579e34e.JPEG"
                    ,"/prod/fxy/android/detection/20240924/06aef90f-2714-49c2-8371-02ea218b7962.JPEG"
                    ,"/prod/fxy/android/detection/20240924/a50fc133-9a01-4cb6-97e4-476c93d86723.JPEG"
                    ,"/prod/fxy/android/detection/20240924/1f4218ee-3fe2-47dd-a9f9-ac65fa00c44c.JPEG"
                    ,"/prod/fxy/android/detection/20240924/0022e008-ba82-4e0e-9c80-4888a22c7c7e.JPEG"
                    ,"/prod/fxy/android/detection/20240923/c31f4fe2-e797-4926-8cd5-15db2e5eac59.JPEG"
                    ,"/prod/fxy/android/detection/20240923/4498de19-c6b2-44f3-b37d-ea0989230ba1.JPEG"
                    ,"/prod/fxy/android/detection/20240923/df7e573a-121c-46cc-bdfb-311c1a4b6a5e.JPEG"
                    ,"/prod/fxy/android/detection/20240923/9e4dbdc0-8a75-4518-9cf7-9b0194a42cde.JPEG"
                    ,"/prod/fxy/android/detection/20240923/9021c9b5-e17c-49c1-85d9-7773be136c7b.JPEG"
                    ,"/prod/fxy/android/detection/20240923/e7fe892c-c26f-4849-9957-f9bdf34a5f29.JPEG"
                    ,"/prod/fxy/android/detection/20240923/37e739c0-a2bc-4d86-a379-a3d00b773d41.JPEG"
                    ,"/prod/fxy/android/detection/20240923/2a301b28-9ced-460b-9e2c-da6520c39518.JPEG"
                    ,"/prod/fxy/android/detection/20240923/47da0be7-d528-4fc2-ad3d-cad9f4f456af.JPEG"
                    ,"/prod/fxy/android/detection/20240923/e46b2289-2d3a-4709-860c-6a48e48611f4.JPEG"
                    ,"/prod/fxy/android/detection/20240923/70b2c33d-7991-4cf5-99d6-69ee21f0200f.JPEG"
                    ,"/prod/fxy/android/detection/20240923/c0065364-7fdc-4eb5-be13-8c630ecf3b59.JPEG"
            };
            long timestamp = getNextTimestamp(-6);
            for (int i = 0; i < ossUrlList.length; i++) {
                String ossUrl = ossUrlList[i];
                String[] tmpOssUrl = ossUrl.split("/");
                String likeOssUrl = tmpOssUrl[tmpOssUrl.length-1];

                mRealm.beginTransaction();
                RealmResults<AsyncUploadRealm> realmResults ;

                RealmQuery<AsyncUploadRealm> queryRealm =  mRealm.where(AsyncUploadRealm.class)
                        .like("ossUrl", "%"+likeOssUrl+"%")
                        .or()
                        .equalTo("ossUrl", ossUrl.replace("detection", "tally"))
                        .or()
                        .equalTo("ossUrl", ossUrl)
                        .greaterThan("createTime",  timestamp)
                        ;
                realmResults = queryRealm.sort("createTime").findAll();


                for (AsyncUploadRealm item : realmResults) {
                    item.setOssUrl(ossUrl);
                }
                realmResults.load();
                mRealm.commitTransaction();
                awaitUploadList.addAll(realmResults);
            }
            XLog.d("总查询"+(awaitUploadList.size())+"条历史数据");
            XLog.d(awaitUploadList);

            debug = false;
        }
    }
    public static long getNextTimestamp(int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.add(Calendar.DAY_OF_MONTH, day);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTimeInMillis();
    }

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

    }

    public void setStartUpload(){
        if (awaitUploadList==null ||awaitUploadList.size()==0){
            asyncUpload();
        }
        allowUpload = true;
    }
    public void setIsAllRe(){
        isAllRe = true;
    }

    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 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();
    }


    private RealmResults<AsyncUploadRealm> getBatchUploadRealm(){
        //更新值
        mRealm.beginTransaction();
        Integer[] isFinish = {0,1,2};
        RealmResults<AsyncUploadRealm> realmResults ;
        RealmQuery<AsyncUploadRealm> queryRealm =  mRealm.where(AsyncUploadRealm.class)
                .in("isFinish",isFinish)
                .equalTo("isDelete",0);
        if (isAllRe){
            Integer[] pushStatus = {0,1};
            queryRealm.in("pushStatus",pushStatus)
//                    .equalTo("notifyKey",fileKey)
//                    .equalTo("uploadType",uploadType)
                    ;
            isAllRe = false;
        }else{
            queryRealm.equalTo("pushStatus",0)
//                    .equalTo("notifyKey",fileKey)
//                    .equalTo("uploadType",uploadType)
                    ;
        }
        realmResults = queryRealm.sort("createTime").findAll();


        // 遍历结果并修改
        for (AsyncUploadRealm item : realmResults) {
            item.setIsFinish(1);
        }
        realmResults.load();
        mRealm.commitTransaction();
        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 rePush = myObject.getRePush();
            int pushStatus = 2;
            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();

        }

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

    }

    //异步通知结果
    private void  asyncNotify(AsyncUploadRealm myObject){
        try {
            JSONObject jsonObject = new JSONObject(myObject.getNotifyParam());
            jsonObject.put(myObject.getNotifyKey(),myObject.getOssUrl());
            jsonObject.put("realm_id",myObject.getId());
            jsonObject.put("unique_tag",myObject.getUniqueTag());
            final String tmpRealmId1 = myObject.getId();
            OkGo.<String>post(myObject.getNotifyUrl()).upJson(jsonObject)
                    .execute(new MyDialogCallback(mContext, true, false) {
                        @Override
                        public void onSuccess(Response<String> response) {
                            super.onSuccess(response);
                            try {
                                ActionBean bean = JsonUtil.getObject(response.body(), ActionBean.class);
                                if(bean.code == 1){
                                    setIsFinish(tmpRealmId1,3);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                XLog.e("回传图片地址错误",e.getMessage());
                                setIsFinish(tmpRealmId1,2);
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
            XLog.e("异步通知"+e.getMessage());

        }
    }

    /**
     * 获取当前网络
     * @return Boolean
     */
    private Boolean getIsNetwork(){
        boolean isNetwork = false;

        try {
            if (mActivity==null){
                return  isNetwork;
            }

            ConnectivityManager connectivityManager = (ConnectivityManager) mActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivityManager == null) {
                //XLog.d( "无法获取ConnectivityManager实例");
                return  isNetwork;
            }
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            if (networkInfo != null) {
                //XLog.d( "当前网络状态：" + networkInfo.getState());
                isNetwork = true;
            } else {
                //XLog.d( "当前无网络连接");
                isNetwork = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return  isNetwork;
    }

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