package com.fxy.putIn;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;

import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.elvishew.xlog.XLog;
import com.fxy.R;
import com.fxy.base.NetworkChangeReceiver;
import com.fxy.baselibrary.base.BaseActivity;
import com.fxy.baselibrary.bean.BaseEventBusBean;
import com.fxy.baselibrary.interfaces.OnRxScanerListener;
import com.fxy.baselibrary.util.DateUtil;
import com.fxy.baselibrary.util.HideUtil;
import com.fxy.baselibrary.util.JsonUtil;
import com.fxy.bean.ActionBean;
import com.fxy.bean.ScanBean;
import com.fxy.common.FiledUpload;
import com.fxy.constant.BaseConfig;
import com.fxy.constant.EventCode;
import com.fxy.net.MyDialogCallback;
import com.fxy.net.Urls;
import com.fxy.putIn.bean.realm.TakePhotosRealm;
import com.fxy.tool.OrderToolMainActivity;
import com.google.gson.Gson;

import com.google.zxing.Result;

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.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import org.json.JSONObject;


import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.realm.RealmResults;
import sto.android.app.StoJNI;
import sto.android.app.StoPdaKeyEvent;
import sto.android.app.StoTongJNI;

public class PutinPhotosMainActivity extends  BaseActivity implements StoJNI.ScanCallBack{

    /**
     * 列表适配器
     */
    Context mContext = this;

    @BindView(R.id.ll_take_picture)
    LinearLayout llTakePicture;

    @BindView(R.id.tv_photos)
    TextView tvPhotos;

    @BindView(R.id.tv_uploaded)
    TextView tvUploaded;

    @BindView(R.id.tv_upload_exception)
    TextView tvUploadedException;

    @BindView(R.id.pb_progressbar)
    ProgressBar pbProgressbar;
    @BindView(R.id.percentage_text_view)
    TextView tvPercentageTextView;




    private ArrayList photoList =new ArrayList<>();

    private FiledUpload filedUpload;

    private ArrayList<String> uploadMapSort =new ArrayList<>();

    //
    //扫码扫码动作
    private ScanBean scanBean;



    protected String action;


    private Unbinder unbinder;

    private JSONObject postParam = new JSONObject();

    //private RealmResults awaitUploadList;
    private List<TakePhotosRealm> awaitUploadList=new ArrayList<>();

    //总数
    private int totalPhoto = 0;
    //上传数量
    private int totalUpload = 0;
    //异常数量
    private int totalAbnormal = 0;

    //当前网络
    private static Boolean currentNetwork = false;


    //检查网络
    private BroadcastReceiver networkReceiver;
    @Override
    public int getContentViewResId() {
        return R.layout.activity_fxy_putin_photos;
    }

    @Override
    public boolean showToolBar() {
        return true;
    }

    @Override
    public boolean openEventBus() {
        return true;
    }

    @Override
    protected void getBundleExtras(Bundle bundle) {
        //XLog.e("接收数据解析：",bundle);
        action = bundle.getString("action","add");
    }



    //finish的返回监听
    //这里的requestCode参数，就是上面设置的 1 ，当跳转的页面返回的时候，通过这个加以判断
    //resultCode ,这个参数是在跳转的页面里面规定的，它也是一个int类型的标志
    //第三个参数包含了返回的值
    //如果不需要所跳转的页面返回值，也就不需要这个方法了
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {// 图片选择结果回调
                List<LocalMedia>  images = PictureSelector.obtainMultipleResult(data);
                addTakePhotos(images.get(0));
               authCamera();


            }

        }
    }



    private void authCamera(){
        //拍照
        com.luck.picture.lib.PictureSelector.create(this)
                .openCamera(PictureMimeType.ofImage())
                //只需要拍照
                //.selectionMode(PictureConfig.SINGLE)
//                .isCamera(true)
                //.compressMaxKB()//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效
                .compress(true) // 压缩
                .cropCompressQuality(100)// 裁剪压缩质量 默认100
                .minimumCompressSize(100) //最新压缩图片 默认100
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    /**
     * EventBus接收信息的方法，开启后才会调用(非粘性事件)
     *
     * @param event
     */
    @Override
    protected void EventBean(BaseEventBusBean event) {
//        XLog.e("----------接收返回--------------");
//        XLog.e("接收返回："+event.getEventCode());
        if (event != null && event.getEventCode() == EventCode.displacement_refresh){

        }
    }

    @Override
    public boolean isPlayMusic() {
        return true;
    }


    @Override
    protected void initView() {
        unbinder = ButterKnife.bind(this);
        setTitleName("快递入库");
        //注册监听网络
        registerNetReceiver();
        initEdit();
        iniData();
        setTotalData();
        filedUpload = new FiledUpload(PutinPhotosMainActivity.this,"work");
        uploadedAbnormal();
    }




    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        //XLog.e("event:"+event.getKeyCode());
        if ((event.getKeyCode()==KeyEvent.KEYCODE_DPAD_CENTER || event.getKeyCode()==KeyEvent.KEYCODE_ENTER )  && event.getAction() == KeyEvent.ACTION_DOWN){
            //按确定键
            if(this.validate()){
//               authCamera();
            }
        }
        return super.dispatchKeyEvent(event);
    }

    //监听按键
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        XLog.e("监听按键："+keyCode);XLog.e(event);
        if (scanBean.getIsBroadcast()==0 && StoTongJNI.getIns(mContext).getEventFuction(keyCode)  == StoPdaKeyEvent.KEYCODE_SCAN
                && event.getRepeatCount() == 0) {

            if (StoTongJNI.getIns(mContext).GetScannerIsScanning()) {
//
            } else {
                StoTongJNI.getIns(mContext).SetScannerStart();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @SuppressLint("HandlerLeak")
    Handler scanHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            if (msg.obj != null) {

                String scanResult = msg.obj.toString().trim();
                if (!scanResult.isEmpty()){
                    setScanResult(scanResult);
                }
            }

        }

    };
    @Override
    public void onScanResults(String str) {
        Message msg = new Message();
        msg.obj = str;
        scanHandler.sendMessage(msg);

    }

    @Override
    public void onScanResults(String str, int type) {
    }
    /**
     * 定义广播接受
     */
    BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String scanResult = intent.getStringExtra(scanBean.getDataName());
            if (scanResult==null){return; }
            String scanStatus = "";
            if (!scanBean.getStatusName().isEmpty()){
                scanStatus = intent.getStringExtra(scanBean.getStatusName());
            }else{
                scanStatus = scanResult.isEmpty()? "" : "ok"; //有值 默认是扫码成功;
            }

            //新大陆(MT65,MT90) 需要手动关闭
            if (!scanBean.getActionStop().isEmpty()){
                Intent stopIntent = new Intent(scanBean.getActionStop());
                mContext.sendBroadcast(stopIntent);
            }

            if ("ok".equals(scanStatus)){
                setScanResult(scanResult);
            }else{
                showErrorToast(getString(R.string.scan_failed));
            }
        }
    };

    /**
     * 注册广播
     */
    private void initReceiver(){

        try {

            String scanStr = getScanSetting();
            scanBean = JsonUtil.getObject(scanStr, ScanBean.class);
            Integer is_broadcast = scanBean.getIsBroadcast();//是否广播

            if (is_broadcast ==1){
                IntentFilter mFilter = new IntentFilter(scanBean.getAction());
                this.registerReceiver(mReceiver, mFilter);
            }else{
                //不广播进行处理 jni模式
                String pdaBrand = StoTongJNI.getmPdaBrand();
                if (!pdaBrand.isEmpty()){
                    StoTongJNI.getIns(this).setmScanCB(this);
                    StoTongJNI.getIns(this).SetScannerOn();
                }
            }


        }catch (Exception e) {
            showErrorToast("获取扫码配置失败"+e.getMessage());
            XLog.e("获取扫码配置失败:" + e.getMessage());
        }
    }

    private void initEdit() {

    }


    private void iniData(){

        //@todo 测试需要删除

        RealmResults<TakePhotosRealm> realmResultsAll  = mRealm.where(TakePhotosRealm.class)
                .sort("pushStatus").findAll();
        realmResultsAll.load();
        if (realmResultsAll.size()>0){
            for (int i=0;i<realmResultsAll.size();i++){
                TakePhotosRealm a = realmResultsAll.get(i);
                XLog.e(a.toString());
            }
        }


        //检查已上传未推送成功数据
        RealmResults<TakePhotosRealm> realmResults  = mRealm.where(TakePhotosRealm.class)
                .equalTo("isDelete",0)
                .equalTo("pushStatus",2)
                .notEqualTo("isFinish",1)
                .sort("pushStatus").findAll();
        realmResults.load();
        if (realmResults.size()>0){
            for (int i=0;i<realmResults.size();i++){
                if (!realmResults.get(i).getOssUrl().isEmpty() && !realmResults.get(i).getId().isEmpty()){
                    pictureInbound(realmResults.get(i).getId(),realmResults.get(i).getOssUrl());
                }

            }
        }




    }

    protected void showBack() {
        super.showBack();
        tb_iv_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int num = awaitUploadList.size();

                if (num>0){

                    new AlertDialog.Builder(mContext).setTitle(R.string.dl_hint)
                            .setMessage("返回会取消上传还有"+num+"条数据未上传，确定要返回吗")
                            .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) {
                            doBack();
                        }
                    }).show();

                }else{
                    doBack();
                }

            }
        });
    }
    private void doBack(){
        HideUtil.hideSoftKeyboard(PutinPhotosMainActivity.this);
        if (isShowBackDialog) {
            onBackPressedSupport();
        } else {
            finish();
        }
    }





    private void setTotalData(){
        // 获取当前日期
        long timestamp = getCurrentDayStartTimestamp();

        long countPhotos = mRealm.where(TakePhotosRealm.class)
                .equalTo("isDelete",0)
                .greaterThan("createTime",  timestamp)
                .count();
        totalPhoto = (int)countPhotos;
        tvPhotos.setText(String.valueOf(totalPhoto));

        //上传数量
        long countUpload = mRealm.where(TakePhotosRealm.class)
                .equalTo("isDelete",0)
                .equalTo("pushStatus",2)
                .greaterThan("createTime",  timestamp)
                .count();
        totalUpload = (int)countUpload;
        tvUploaded.setText(String.valueOf(totalUpload));


        //异常
        long countAbnormal = mRealm.where(TakePhotosRealm.class)
                .equalTo("isDelete",0)
                .equalTo("pushStatus",1)
                .greaterThan("createTime",  timestamp)
                .count();
        totalAbnormal = (int) countAbnormal;
        tvUploadedException.setText(String.valueOf(totalAbnormal));
    }

    private void uploadedAbnormal(){
        if (awaitUploadList==null || awaitUploadList.size()==0){
            long timestamp = getYesterdayStartTimestamp();
            RealmResults<TakePhotosRealm> realmResults  = mRealm.where(TakePhotosRealm.class)
                    .equalTo("isDelete",0)
                    .equalTo("pushStatus",1)
                    .greaterThan("createTime",  timestamp)
                    .sort("pushStatus").findAll();
            realmResults.load();
            awaitUploadList.addAll(realmResults);
            asyncUpload();
        }
    }

    public static long getCurrentDayStartTimestamp() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY-1, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTimeInMillis();
    }

    public static long getYesterdayStartTimestamp() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, -2);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTimeInMillis();
    }
    /**
     * 添加拍照记录
     * @param localMedia
     */
    private void addTakePhotos(LocalMedia localMedia){
        String realmId = UUID.randomUUID().toString();
        String scan_date = DateUtil.getCurDateStr(DateUtil.FORMAT_YMDHMS);
        //同步操作写法一：
        mRealm.beginTransaction();
        //会创建对象和user表
        TakePhotosRealm takePhotosRealm = mRealm.createObject(TakePhotosRealm.class,realmId);
        //会自动更新表
        if (localMedia.isCompressed()){
            takePhotosRealm.setLocalPath(localMedia.getCompressPath());
        }else{
            takePhotosRealm.setLocalPath(localMedia.getPath());
        }

        takePhotosRealm.setMimeType(localMedia.getMimeType());
        takePhotosRealm.setOssUrl("");
        takePhotosRealm.setScanDate(scan_date);

        Date date = new Date();
        takePhotosRealm.setCreateTime(date.getTime());
        takePhotosRealm.setPushStatus(0);
        //提交事务，操作就被执行
        mRealm.commitTransaction();
        totalPhoto++;
        tvPhotos.setText(String.valueOf(totalPhoto));

        //无正在执行的
        if (awaitUploadList==null || awaitUploadList.size()==0){
            asyncUpload();
        }

    }



    private void asyncUpload(){

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

        if (awaitUploadList==null || awaitUploadList.size()==0){
            RealmResults<TakePhotosRealm> realmResults  = mRealm.where(TakePhotosRealm.class)
                    .equalTo("isDelete",0)
                    .equalTo("pushStatus",0)
                    .sort("pushStatus").findAll();
            realmResults.load();
            awaitUploadList.addAll(realmResults);

        }

        if (awaitUploadList.size()>0){
            TakePhotosRealm tmpRealm=  awaitUploadList.get(0);
            int sort = uploadMapSort.size();
            setUploadProgress(0);
            uploadMapSort.add(tmpRealm.getId());
            filedUpload.filedUpload(tmpRealm.getLocalPath(),uploadHandler,sort);

        }
    }

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

            int pushStatus = 2;
            if (status==0){
                pushStatus = rePush>4 ? 1 : 0;
                totalAbnormal++;
                tvUploadedException.setText(String.valueOf(totalAbnormal));
            }else{
                totalUpload++;
                tvUploaded.setText(String.valueOf(totalUpload));
            }
            //更新值
            mRealm.beginTransaction();
            TakePhotosRealm myObject = mRealm.where(TakePhotosRealm.class).equalTo("id",tmpRealmId).findFirst();
            myObject.setPushStatus(pushStatus);
            myObject.setOssUrl(photo_list);
            mRealm.commitTransaction();
            pictureInbound(tmpRealmId,photo_list);
        }
        //上传完，继续执行
        asyncUpload();

    }

    //必须在主线程更新
    protected void setUploadProgress(int diff){
        if (pbProgressbar!=null){
            pbProgressbar.setProgress(diff);
            tvPercentageTextView.setText(String.valueOf(diff).concat("%"));
        }
    }


    @SuppressLint("HandlerLeak")
    private Handler uploadHandler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                //XLog.e(msg);

                String tmpRealmId;
                switch (msg.what){
                    case 0:
                        Toast.makeText(mContext, "error", Toast.LENGTH_SHORT).show();
                        break;
                    case 1:
                        //失败   arg2 1、网络异常  2、服务异常
                        //String message = (String) msg.obj;

                        //网络异常不算进失败
                        currentNetwork = getIsNetwork();
                        if (currentNetwork){
                            resultUpload(uploadMapSort.get(msg.arg1),0,"");
                        }else{
                            awaitUploadList.clear();
                        }

                        break;
                    case 2://成功

                        //表示数据存在
                        //Toast.makeText(mContext, "上传成功", Toast.LENGTH_SHORT).show();
                        tmpRealmId = uploadMapSort.get(msg.arg1);
                        ArrayList<String> list =new ArrayList<>();
                        list.add((String) msg.obj);
                        resultUpload(tmpRealmId,1,(new Gson()).toJson(list));


                        break;
                    case 3:

                        //XLog.e("上传进度"+msg.arg1);
                        setUploadProgress(msg.arg2);
                        //设置进度条
                        //progressDialog.show();
                        return;
                    case 4:
                        //获取上传状态

                        return;
                    default:
                        break;
                }

            } catch (Exception e) {
                XLog.e("上传回调",e.getMessage());
                e.printStackTrace();
            }
        }
    };

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

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



    private OnRxScanerListener mScanerListener = new OnRxScanerListener() {
        @Override
        public void onSuccess(String type, Result result) {
            String scanResult = result.getText();
            switch (type){
                case BaseConfig.COMMON_SCANNER_ONLY:
                    setScanResult(scanResult);

                    break;
            }
        }
        @Override
        public void onFail(String type, String message) {

        }
    };

    //把扫描结果赋值
    private void setScanResult(String scanResult){
        //获取焦点的view对象
        View view=getWindow().getDecorView().findFocus();
        //如果是EditText
        if(view instanceof EditText)
        {
            ((EditText) view).setText(scanResult);

            switch (view.getId()) {

                default:
            }


        }
    }

    //拍照上传
    private void pictureInbound(String tmpRealmId, String labelImg){
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("realm_id",tmpRealmId);
            jsonObject.put("label_img",labelImg);

            final String tmpRealmId1 = tmpRealmId;
            OkGo.<String>post(Urls.getServiceAddress(this) + Urls.FXY_PICTURE_INBOUND).upJson(jsonObject)
                    .execute(new MyDialogCallback(this, 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){
                                    //showSuccessToast(bean.msg);
                                    JSONObject data = new JSONObject(bean.data);
                                    if (data.has("realm_id")){
                                        setIsFinish(data.getString("realm_id"),1);
                                    }

                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                XLog.e("添加理货数据结果返回错误",e.getMessage());
                                setIsFinish(tmpRealmId1,2);
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();

        }


    }


    /*
     * 校验必录
     */
    private boolean validate(){

        return true;
    }

    //sIsGoodinfoMatch,sIsBattery,sIsMagnetic,sIsWood,sIsExtra,sIsOther
    @OnClick({R.id.btn_photos,R.id.tv_abnormal_view})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.btn_photos:
                authCamera();
                break;
            case R.id.tv_abnormal_view:
                List<LocalMedia> selectList = new ArrayList<>();
                long timestamp = getCurrentDayStartTimestamp();
                RealmResults<TakePhotosRealm> realmResults  = mRealm.where(TakePhotosRealm.class)
                        .equalTo("isDelete",0)
                        .equalTo("pushStatus",2)
                        .greaterThan("createTime",  timestamp)
                        .sort("pushStatus").findAll();
                realmResults.load();
                if (realmResults.size()>0){
                    for (int i=0;i<realmResults.size();i++){
                        TakePhotosRealm tmpRealm = realmResults.get(i);
                        if (!realmResults.get(i).getLocalPath().isEmpty()){
                            String cutPath = tmpRealm.getLocalPath();
                            LocalMedia  media = new LocalMedia(cutPath, 0, false,i, 0, tmpRealm.getMimeType());
                            media.setCut(false);
                            media.setCutPath(cutPath);
                            String imageType = PictureMimeType.createImageType(cutPath);
                            media.setPictureType(imageType);
                            selectList.add(media);
                        }
                    }
                }

                if (selectList.size()>0){


                    PictureSelector.create(PutinPhotosMainActivity.this).externalPicturePreview(0, selectList);

                }else{
                    showErrorToast("暂时无照片");
                }


                break;

            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        unbinder.unbind();
        super.onDestroy();
        //注销
        unregisterReceiver(networkReceiver);

    }
    @Override
    protected void onResume() {
        super.onResume();
        initReceiver();

    }
    @Override
    protected void onPause() {
        super.onPause();
        //销毁在onResume()方法中的广播
        try {
            //停止扫描
            Integer is_broadcast = scanBean.getIsBroadcast();//是否广播
            if (is_broadcast==0){
                StoTongJNI.getIns(mContext).SetScannerStop();
                StoTongJNI.getIns(mContext).SetScannerOff();
            }else{
                unregisterReceiver(mReceiver);
            }
        }catch (Exception e){
            XLog.e("销毁广播失败：",e.getMessage());
        }

    }

    // 注册 NetworkChangeReceiver
    private void registerNetReceiver() {
        networkReceiver = new NetworkChangeReceiver();
        registerReceiver(networkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }



    // 自定义的广播接收器类 （重写onReceive）
    private  class NetworkChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ("android.net.conn.CONNECTIVITY_CHANGE".equals(intent.getAction())) {
                boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
                currentNetwork = !noConnectivity;
                if (currentNetwork){
                    asyncUpload();
                }

            }
        }
    }


}
