package com.phlx.anchorcollect.ui.setting;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Application;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseIntArray;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;

import com.google.gson.Gson;
import com.phlx.anchorcollect.App;
import com.phlx.anchorcollect.BR;
import com.phlx.anchorcollect.R;
import com.phlx.anchorcollect.ble.BluetoothEntity;
import com.phlx.anchorcollect.bt.BtService;
import com.phlx.anchorcollect.data.Repository;
import com.phlx.anchorcollect.db.DbUtil;
import com.phlx.anchorcollect.db.gen.BreedingRecordDetailEntityDao;
import com.phlx.anchorcollect.db.gen.BreedingRecordEntityDao;
import com.phlx.anchorcollect.db.gen.ImmuneBatchEntityDao;
import com.phlx.anchorcollect.db.gen.MedicalRecordEntityDao;
import com.phlx.anchorcollect.db.gen.PerformanceEntityDao;
import com.phlx.anchorcollect.db.gen.WeightManEntityDao;
import com.phlx.anchorcollect.db.interf.DbIDUCallBack;
import com.phlx.anchorcollect.db.interf.DbQueryCallBack;
import com.phlx.anchorcollect.entity.BreedingRecordDetailEntity;
import com.phlx.anchorcollect.entity.BreedingRecordEntity;
import com.phlx.anchorcollect.entity.CattleResumeEntity;
import com.phlx.anchorcollect.entity.ImmuneBatchEntity;
import com.phlx.anchorcollect.entity.MedicalRecordEntity;
import com.phlx.anchorcollect.entity.PerformanceEntity;
import com.phlx.anchorcollect.entity.WeightManEntity;
import com.phlx.anchorcollect.params.CollectResponse;
import com.phlx.anchorcollect.params.ListResponse;
import com.phlx.anchorcollect.rfid.InventoryManger;
import com.phlx.anchorcollect.util.TextUtil;
import com.uhf.structures.InventoryData;
import com.uhf.structures.InventoryParams;
import com.uhf.structures.OnInventoryListener;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.wandersnail.ble.Device;
import cn.wandersnail.bluetooth.BTManager;
import cn.wandersnail.bluetooth.DiscoveryListener;
import cn.wandersnail.commons.util.ToastUtils;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class SettingVM extends BaseViewModel<Repository> implements DiscoveryListener, OnInventoryListener {

    private SoundPool soundPool;//盘点到标签时的提示音
    private SparseIntArray musicId;
    private static Map<String, Integer> map;//去重
    private ArrayList<BluetoothEntity> mList;

    private boolean isInventory = false;

    //给RecyclerView添加ObservableList
    public ObservableList<BLEItem> observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<BLEItem> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_ble);

    private Device curDevice;


    //选中的蓝牙设备信息
    public static BluetoothEntity bluetoothEntity;

    //当前蓝牙搜索集合
    private List<BluetoothEntity> bluetoothList;

    public SingleLiveEvent<Integer> btRequestEvent = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> btParamEvent = new SingleLiveEvent<>();

    //错误提示
    public SingleLiveEvent<String> errorEvent = new SingleLiveEvent<>();

    public ObservableField<String> cattleresumeCount = new ObservableField<>("0");
    public ObservableField<String> performanceCount = new ObservableField<>("0");
    public ObservableField<String> weightManCount = new ObservableField<>("0");
    public ObservableField<String> medicalrecordsCount = new ObservableField<>("0");
    public ObservableField<String> immunebatchCount = new ObservableField<>("0");
    public ObservableField<String> cattlematingMasterCount = new ObservableField<>("0");
    public ObservableField<String> cattlematingDetaillCount = new ObservableField<>("0");

    public SettingVM(@NonNull Application application, Repository model) {
        super(application, model);

        initInventory();
        //设置盘点数据监听
        App.getInstance().getLinkage().setOnInventoryListener(this);

        initData();
    }

    private void initData() {

        QueryBuilder<PerformanceEntity> builder =
                DbUtil.getInstance().getQueryBuilder(PerformanceEntity.class)
                        .where(PerformanceEntityDao.Properties.UploadStatus.eq("0"));
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<PerformanceEntity>() {
            @Override
            public void onSuccess(List<PerformanceEntity> result) {
                if (result != null && result.size() > 0) {
                    performanceCount.set(result.size() + "");
                }
            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("查询性能测定数量失败！");
                dismissDialog();
            }
        }).queryAsyncAll(PerformanceEntity.class, builder);

    }

    private void initInventory() {

        map = new HashMap<>();
        mList = new ArrayList<>();
        soundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 5);
        musicId = new SparseIntArray();
        musicId.put(1, soundPool.load(getApplication(), R.raw.readcard, 1));
        musicId.put(2, soundPool.load(getApplication(), R.raw.failure, 1));

        //设置盘点内容：Epc + Tid
        InventoryParams inventoryParams = new InventoryParams();
        inventoryParams.address = 0;
        inventoryParams.inventoryArea = 1;
        inventoryParams.len = 6;
        App.getInstance().getLinkage().Radio_SetInventoryParams(inventoryParams);
        int filterStatus = setInventoryFilter();
        Log.e("filterStatus:", "" + filterStatus);
    }

    private int setInventoryFilter() {
        int tsh = 0;
        int maxRepeat = 1;
        int cacheTime = 0;
        int maxMonitorTagInRangeTimeMs = 0;
        int maxMonitorTagOutRangeTimeMs = 0;
        int filterMode = 0;
        maxRepeat |= (filterMode << 14);
        return InventoryManger.from().setInventoryFilter(tsh, maxRepeat, cacheTime, maxMonitorTagInRangeTimeMs, maxMonitorTagOutRangeTimeMs);
    }

    public void initBt(Context context) {

        bluetoothList = new ArrayList<>();
        BTManager.isDebugMode = true;
        BTManager.getInstance().addDiscoveryListener(this);
        btParamEvent.call();
    }

    public BindingCommand OnRefreshClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            BTManager.getInstance().stopDiscovery();
            doStartDiscovery();
        }
    });

    private void doStartDiscovery() {
        observableList.clear();
        bluetoothList.clear();
        BTManager.getInstance().startDiscovery();
    }

    public BindingCommand OnStopClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            BTManager.getInstance().stopDiscovery();
        }
    });

    public BindingCommand OnConnectionClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            mList.clear();
            map.clear();
            observableList.clear();
            if (isInventory)
                App.getInstance().getLinkage().stopInventory();
            else
                App.getInstance().getLinkage().startInventory(1, 0);
            isInventory = !isInventory;
        }
    });

    public BindingCommand OnDisconnectionClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            //断开指定连接
            stopBtService();
            if (bluetoothEntity != null)
                BTManager.getInstance().disconnectConnection(bluetoothEntity.getBluetoothDevice());
        }
    });

    public BindingCommand OnBaseArchivesSyncClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            requestBaseArchives();
        }
    });

    public BindingCommand OnSignMeasureSyncClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            querySignMeasure();
        }
    });

    public BindingCommand OnWeightingManageSyncClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            queryWeightMan();
        }
    });

    public BindingCommand OnTreatmentRecordSyncClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            queryMedicalRecord();
        }
    });

    public BindingCommand OnImmunRecordSyncClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            queryImmuneBatch();
        }
    });

    public BindingCommand OnBreedingRecordSyncClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            queryBreedingRecord();
        }
    });

    public BindingCommand OnBreedingRecordDetailSyncClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            queryBreedingRecordDetail();
        }
    });

    public void itemOnClick(BluetoothEntity btEntity) {
        BTManager.getInstance().stopDiscovery();
        stopBtService();
        bluetoothEntity = btEntity;

        Intent intent = new Intent(getApplication(), BtService.class);
        intent.putExtra("device", bluetoothEntity.getBluetoothDevice());
        if (!isServiceRunning(getApplication()))
            getApplication().startService(intent);
    }


    @Override
    public void onDiscoveryStart() {

    }

    @Override
    public void onDiscoveryStop() {

    }

    @Override
    public void onDeviceFound(@NonNull BluetoothDevice device, int rssi) {
        if (!TextUtils.isEmpty(device.getName())) {
            BluetoothEntity entity = new BluetoothEntity();
            entity.setName(device.getName());
            entity.setAddress(device.getAddress());
            entity.setRssi(rssi);
            entity.setBluetoothDevice(device);
            if (!bluetoothList.contains(entity)) {
                bluetoothList.add(entity);
                BLEItem bleItem = new BLEItem(this, entity);
                observableList.add(bleItem);
            }
        }
    }

    @Override
    public void onDiscoveryError(int errorCode, @NonNull String errorMsg) {
        switch (errorCode) {
            case DiscoveryListener.ERROR_LACK_LOCATION_PERMISSION://缺少定位权限
                ToastUtils.showShort("搜索出错：缺少定位权限" + errorCode);
                break;
            case DiscoveryListener.ERROR_LOCATION_SERVICE_CLOSED://位置服务未开启
                ToastUtils.showShort("搜索出错：位置服务未开启" + errorCode);
                break;
            case DiscoveryListener.ERROR_LACK_SCAN_PERMISSION://缺少搜索权限
                ToastUtils.showShort("搜索出错：缺少搜索权限" + errorCode);
                break;
            case DiscoveryListener.ERROR_SCAN_FAILED://搜索失败
                ToastUtils.showShort("搜索出错：" + errorCode);
                break;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (BTManager.getInstance().isInitialized()) {
            BTManager.getInstance().stopDiscovery();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d("Main", "onResume");
        if (BTManager.getInstance().isInitialized()) {
            if (BTManager.getInstance().isBluetoothOn()) {
//                doStartDiscovery();
            } else {
                //未开启蓝牙
                btRequestEvent.call();
            }
        }
    }

    /**
     * 判断服务是否在运行中
     *
     * @param context 即为Context对象
     * @return 是否在运行中
     */
    private boolean isServiceRunning(Context context) {
        if (context != null) {
            ActivityManager activityManager
                    = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            ArrayList<ActivityManager.RunningServiceInfo> runningServiceInfoList
                    =
                    (ArrayList<ActivityManager.RunningServiceInfo>) activityManager.getRunningServices(100);
            for (ActivityManager.RunningServiceInfo runningServiceInfo : runningServiceInfoList) {
                if ("BtService".equals(runningServiceInfo.service.getClassName())) {
                    return true;
                }
            }
        } else {
            return false;
        }
        return false;
    }


    public void stopBtService() {
        if (isServiceRunning(getApplication())) {
            Intent intent = new Intent(getApplication(), BtService.class);
            getApplication().stopService(intent);
        }
    }

    @Override
    public void getInventoryData(InventoryData inventoryData) {
        if (inventoryData != null) {
            Message messenger = handler.obtainMessage();
            messenger.what = 0x333;
            messenger.obj = inventoryData;
            handler.sendMessage(messenger);
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x333) {
                InventoryData inventoryData = (InventoryData) msg.obj;
                String epc = "";
                String tid_user = "";
                String rss = "";
                String port = "";
                if (inventoryData.getDataLength() > 0) {
                    tid_user = TextUtil.byteToHexString(inventoryData.getData(), inventoryData.getDataLength());
                }
                if (inventoryData.getEpcLength() > 0) {
                    epc = TextUtil.byteToHexString(inventoryData.getEPC_Data(), inventoryData.getEpcLength());
                    rss = String.valueOf(inventoryData.getRSSI());
                }
                String tag = epc + tid_user;
                if (!map.containsKey(tag)) {
                    BluetoothEntity entity = new BluetoothEntity();
                    entity.setName(tag);
                    entity.setAddress("");
                    BLEItem bleItem = new BLEItem(SettingVM.this, entity);
                    mList.add(entity);
                    observableList.add(bleItem);
                    soundPool.play(musicId.get(1), 1, 1, 0, 0, 1);
                    map.put(tag, mList.size() - 1);
                }
            }
        }
    };

    /**===========================================基础数据================================================= */

    /**
     * 下载基础数据
     */
    private void requestBaseArchives() {

        //SyncState 0根据记录更新，1重新更新
        Map<String, String> requestParam = new HashMap<>();
        List<CattleResumeEntity> queryList = DbUtil.getInstance().queryAll(CattleResumeEntity.class);

        if (queryList == null || queryList.size() == 0)
            requestParam.put("SyncState", "1");
        else
            requestParam.put("SyncState", "0");

        addSubscribe(model.downloadCattleList(requestParam)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(disposable -> showDialog("正在同步基础数据..."))
                .subscribe((Consumer<ListResponse<CattleResumeEntity>>) response -> {

                    if (response.getCode() == 0) {
                        if (response.getData() != null && response.getData().size() > 0) {
                            KLog.e("--CattleResumeEntity--" + response.getData().size());

                            List<String> ids = new ArrayList<>();
                            for (CattleResumeEntity cre : response.getData()) {
                                cre.setUploadStatus("1");
                                ids.add(cre.getUnid());
                            }

                            DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                @Override
                                public void onNotification(boolean result) {
                                    if (result) {
                                        requestBaseArchivesSync(ids);
                                    } else {
                                        dismissDialog();
                                        errorEvent.setValue("保存基础数据失败！");
                                    }
                                }
                            }).insertAsyncBatch(CattleResumeEntity.class, response.getData());
                        } else {
                            dismissDialog();
                        }

                    } else {
                        dismissDialog();
                        errorEvent.setValue("服务器 :" + response.getMsg());
                    }
                }, (Consumer<ResponseThrowable>) throwable -> {
                    dismissDialog();
                    KLog.e(throwable.message);
                })
        );
    }

    /**
     * 返回-基础数据-成功
     */
    private void requestBaseArchivesSync(List<String> ids) {

//        Map<String, String> syncParam = new HashMap<>();
//        syncParam.put("ids", new Gson().toJson(ids).toString());

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(ids));
//        KLog.e("label", postParams.toString());

        addSubscribe(model.downloadCattleListSync(body)
                        .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                        .compose(RxUtils.schedulersTransformer())
                        .compose(RxUtils.exceptionTransformer())
//                .doOnSubscribe(disposable -> showDialog("正在同步基础数据..."))
                        .subscribe((Consumer<CollectResponse>) response -> {

                            KLog.e("requestBaseArchivesSync", response.toString());
                            if (response.getCode() == 0) {
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("同步基础数据成功！");
                                requestBaseArchives();
                            } else {
                                dismissDialog();
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            dismissDialog();
                            me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                        })
        );
    }

    /**===========================================性能测定================================================= */

    /**
     * 下载-性能测定
     */
    private void requestSignMeasure() {

        //SyncState 0根据记录更新，1重新更新
        Map<String, String> requestParam = new HashMap<>();
        List<PerformanceEntity> queryList = DbUtil.getInstance().queryAll(PerformanceEntity.class);

        if (queryList == null || queryList.size() == 0)
            requestParam.put("SyncState", "1");
        else
            requestParam.put("SyncState", "0");

        addSubscribe(model.downloadPerformanceList(requestParam)
                        .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                        .compose(RxUtils.schedulersTransformer())
                        .compose(RxUtils.exceptionTransformer())
//                .doOnSubscribe(disposable -> showDialog("正在同步性能测定数据..."))
                        .subscribe((Consumer<ListResponse<PerformanceEntity>>) response -> {

                            if (response.getCode() == 0) {
                                if (response.getData() != null && response.getData().size() > 0) {
                                    KLog.e("--PerformanceEntity--" + response.getData().size());

                                    List<String> ids = new ArrayList<>();
                                    for (PerformanceEntity cre : response.getData()) {
                                        cre.setUploadStatus("1");
                                        ids.add(cre.getUnid());
                                    }

                                    DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                        @Override
                                        public void onNotification(boolean result) {
                                            if (result) {
                                                requestSignMeasureSync(ids);
                                            } else {
                                                dismissDialog();
                                                errorEvent.setValue("保存性能测定数据失败！");
                                            }
                                        }
                                    }).insertAsyncBatch(PerformanceEntity.class, response.getData());
                                } else {
                                    dismissDialog();
                                }

                            } else {
                                errorEvent.setValue("服务器 :" + response.getMsg());
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            querySignMeasure();
                            KLog.e(throwable.message);
                        })
        );

    }

    /**
     * 同步-性能测定-成功
     */
    private void requestSignMeasureSync(List<String> ids) {

//        Map<String, String> syncParam = new HashMap<>();
//        syncParam.put("ids", new Gson().toJson(ids).toString());

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(ids));
//        KLog.e("label", postParams.toString());

        addSubscribe(model.downloadPerformanceListSync(body)
                        .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                        .compose(RxUtils.schedulersTransformer())
                        .compose(RxUtils.exceptionTransformer())
//                .doOnSubscribe(disposable -> showDialog("正在同步基础数据..."))
                        .subscribe((Consumer<CollectResponse>) response -> {

                            KLog.e("requestSignMeasureSync", response.toString());
                            if (response.getCode() == 0) {
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("同步性能测定数据成功！");
                                requestSignMeasure();
                            } else {
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                                dismissDialog();
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            dismissDialog();
                            me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                        })
        );
    }

    /**
     * 查询-性能测定
     */
    private void querySignMeasure() {

        QueryBuilder<PerformanceEntity> builder =
                DbUtil.getInstance().getQueryBuilder(PerformanceEntity.class)
                        .where(PerformanceEntityDao.Properties.UploadStatus.eq("0"))
                        .limit(10);
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<PerformanceEntity>() {
            @Override
            public void onSuccess(List<PerformanceEntity> result) {
                if (result != null && result.size() > 0) {
                    uploadSignMeasure(result);
                } else {
                    requestSignMeasure();
                }
            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("查询性能测定失败！");
                dismissDialog();
            }
        }).queryAsyncAll(PerformanceEntity.class, builder);
    }

    /**
     * 上传-性能测定
     */
    private void uploadSignMeasure(List<PerformanceEntity> performanceEntities) {

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(performanceEntities));
//        KLog.e("label", postParams.toString());

        addSubscribe(model.uploadPerformanceList(body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(disposable -> showDialog("正在同步性能测定数据..."))
                .subscribe((Consumer<CollectResponse>) response -> {

                    dismissDialog();
                    KLog.e("requestSignMeasureSync", response.toString());
                    for (PerformanceEntity pe : performanceEntities) {
                        pe.setUploadStatus("1");
                    }
                    if (response.getCode() == 0) {
                        DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                            @Override
                            public void onNotification(boolean result) {
                                if (result) {
                                    me.goldze.mvvmhabit.utils.ToastUtils.showShort("上传性能测定数据成功！");
                                    querySignMeasure();
                                } else {
                                    me.goldze.mvvmhabit.utils.ToastUtils.showShort("修改性能测定数据失败");
                                }
                            }
                        }).updateAsyncBatch(PerformanceEntity.class, performanceEntities);
                    } else {
                        me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                        requestSignMeasure();
                    }
                }, (Consumer<ResponseThrowable>) throwable -> {
                    dismissDialog();
                    me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                })
        );

    }

    /**===========================================配种记录================================================= */

    /**
     * 下载-配种记录主表-
     */
    private void requestBreedingRecord() {

        //SyncState 0根据记录更新，1重新更新
        Map<String, String> requestParam = new HashMap<>();
        List<BreedingRecordEntity> queryList = DbUtil.getInstance().queryAll(BreedingRecordEntity.class);

        if (queryList == null || queryList.size() == 0)
            requestParam.put("SyncState", "1");
        else
            requestParam.put("SyncState", "0");

        addSubscribe(model.downloadBreedingRecordList(requestParam)
                        .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                        .compose(RxUtils.schedulersTransformer())
                        .compose(RxUtils.exceptionTransformer())
//                .doOnSubscribe(disposable -> showDialog("正在同步配种记录主表数据..."))
                        .subscribe((Consumer<ListResponse<BreedingRecordEntity>>) response -> {

                            if (response.getCode() == 0) {
                                if (response.getData() != null && response.getData().size() > 0) {
                                    KLog.e("--BreedingRecordEntity--" + response.getData().size());

                                    List<String> ids = new ArrayList<>();
                                    for (BreedingRecordEntity cre : response.getData()) {
                                        cre.setUploadStatus("1");
                                        ids.add(cre.getUnid());
                                    }

                                    DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                        @Override
                                        public void onNotification(boolean result) {
                                            if (result) {
                                                requestBreedingRecordSync(ids);
                                            } else {
                                                dismissDialog();
                                                errorEvent.setValue("保存配种记录主表数据失败！");
                                            }
                                        }
                                    }).insertAsyncBatch(BreedingRecordEntity.class, response.getData());
                                } else {
                                    dismissDialog();
                                }

                            } else {
                                errorEvent.setValue("服务器 :" + response.getMsg());
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            KLog.e(throwable.message);
                        })
        );

    }

    /**
     * 上传-配种记录主表-成功
     */
    private void requestBreedingRecordSync(List<String> ids) {

//        Map<String, String> syncParam = new HashMap<>();
//        syncParam.put("ids", new Gson().toJson(ids).toString());

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(ids));
//        KLog.e("label", postParams.toString());

        addSubscribe(model.downloadBreedingRecordListSync(body)
                        .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                        .compose(RxUtils.schedulersTransformer())
                        .compose(RxUtils.exceptionTransformer())
//                .doOnSubscribe(disposable -> showDialog("正在同步基础数据..."))
                        .subscribe((Consumer<CollectResponse>) response -> {

                            dismissDialog();
                            KLog.e("downloadBreedingRecordListSync", response.toString());
                            if (response.getCode() == 0) {
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("同步配种主表数据成功！");
                                requestBreedingRecord();
                            } else {
                                dismissDialog();
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            dismissDialog();
                            me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                        })
        );
    }

    /**
     * 查询-配种记录主表-
     */
    private void queryBreedingRecord() {

        QueryBuilder<BreedingRecordEntity> builder =
                DbUtil.getInstance().getQueryBuilder(BreedingRecordEntity.class)
                        .where(BreedingRecordEntityDao.Properties.UploadStatus.eq("0"))
                        .limit(10);
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<BreedingRecordEntity>() {
            @Override
            public void onSuccess(List<BreedingRecordEntity> result) {
                if (result != null && result.size() > 0) {
                    uploadBreedingRecord(result);
                } else {
                    requestBreedingRecord();
                }
            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("查询-配种记录主表-失败！");
                dismissDialog();
            }
        }).queryAsyncAll(BreedingRecordEntity.class, builder);
    }

    /**
     * 上传-配种记录主表-
     */
    private void uploadBreedingRecord(List<BreedingRecordEntity> breedingRecordEntities) {

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(breedingRecordEntities));
//        KLog.e("label", postParams.toString());

        addSubscribe(model.uploadBreedingRecordList(body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(disposable -> showDialog("正在同步-配种记录主表-数据..."))
                .subscribe((Consumer<CollectResponse>) response -> {

                    if (response.getCode() == 0) {
                        KLog.e("uploadBreedingRecord", response.toString());
                        for (BreedingRecordEntity pe : breedingRecordEntities) {
                            pe.setUploadStatus("1");
                        }
                        DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                            @Override
                            public void onNotification(boolean result) {
                                if (result) {
                                    queryBreedingRecord();
                                    me.goldze.mvvmhabit.utils.ToastUtils.showShort("上传-配种记录主表-数据成功！");
                                } else {
                                    me.goldze.mvvmhabit.utils.ToastUtils.showShort("修改-配种记录主表-数据失败");
                                }
                            }
                        }).updateAsyncBatch(BreedingRecordEntity.class, breedingRecordEntities);
                    } else {
                        dismissDialog();
                        me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                        requestBreedingRecord();
                    }
                }, (Consumer<ResponseThrowable>) throwable -> {
                    dismissDialog();
                    me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                })
        );

    }

    /**===========================================配种记录-子表================================================= */

    /**
     * 下载-配种记录子表-
     */
    private void requestBreedingRecordDetail() {

        //SyncState 0根据记录更新，1重新更新
        Map<String, String> requestParam = new HashMap<>();
        List<BreedingRecordDetailEntity> queryList = DbUtil.getInstance().queryAll(BreedingRecordDetailEntity.class);

        if (queryList == null || queryList.size() == 0)
            requestParam.put("SyncState", "1");
        else
            requestParam.put("SyncState", "0");

        addSubscribe(model.downloadBreedingRecordDetailList(requestParam)
                        .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                        .compose(RxUtils.schedulersTransformer())
                        .compose(RxUtils.exceptionTransformer())
//                .doOnSubscribe(disposable -> showDialog("正在同步配种记录主表数据..."))
                        .subscribe((Consumer<ListResponse<BreedingRecordDetailEntity>>) response -> {

                            if (response.getCode() == 0) {
                                if (response.getData() != null && response.getData().size() > 0) {
                                    KLog.e("--BreedingRecordDetailEntity--" + response.getData().size());

                                    List<String> ids = new ArrayList<>();
                                    for (BreedingRecordDetailEntity cre : response.getData()) {
                                        cre.setUploadStatus("1");
                                        ids.add(cre.getUnid());
                                    }

                                    DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                        @Override
                                        public void onNotification(boolean result) {
                                            if (result) {
                                                requestBreedingRecordDetailSync(ids);
                                            } else {
                                                dismissDialog();
                                                errorEvent.setValue("保存配种记录子表数据失败！");
                                            }
                                        }
                                    }).insertAsyncBatch(BreedingRecordDetailEntity.class, response.getData());
                                } else {
                                    dismissDialog();
                                }

                            } else {
                                errorEvent.setValue("服务器 :" + response.getMsg());
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            KLog.e(throwable.message);
                        })
        );

    }

    /**
     * 上传-配种记录子表-成功
     */
    private void requestBreedingRecordDetailSync(List<String> ids) {

//        Map<String, String> syncParam = new HashMap<>();
//        syncParam.put("ids", new Gson().toJson(ids).toString());

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(ids));
//        KLog.e("label", postParams.toString());

        addSubscribe(model.downloadBreedingRecordDetailListSync(body)
                        .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                        .compose(RxUtils.schedulersTransformer())
                        .compose(RxUtils.exceptionTransformer())
//                .doOnSubscribe(disposable -> showDialog("正在同步基础数据..."))
                        .subscribe((Consumer<CollectResponse>) response -> {

                            dismissDialog();
                            KLog.e("requestBreedingRecordDetailSync", response.toString());
                            if (response.getCode() == 0) {
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("同步配种记录子表数据成功！");
                                queryBreedingRecordDetail();
                            } else {
                                dismissDialog();
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            dismissDialog();
                            me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                        })
        );
    }

    /**
     * 查询-配种记录子表-
     */
    private void queryBreedingRecordDetail() {

        QueryBuilder<BreedingRecordDetailEntity> builder =
                DbUtil.getInstance().getQueryBuilder(BreedingRecordDetailEntity.class)
                        .where(BreedingRecordDetailEntityDao.Properties.UploadStatus.eq("0"))
                        .limit(10);
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<BreedingRecordDetailEntity>() {
            @Override
            public void onSuccess(List<BreedingRecordDetailEntity> result) {
                if (result != null && result.size() > 0) {
                    uploadBreedingRecordDetail(result);
                } else {
                    requestBreedingRecordDetail();
                }
            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("查询-配种记录子表-失败！");
                dismissDialog();
            }
        }).queryAsyncAll(BreedingRecordDetailEntity.class, builder);
    }

    /**
     * 上传-配种记录子表-
     */
    private void uploadBreedingRecordDetail(List<BreedingRecordDetailEntity> breedingRecordDetailEntities) {

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(breedingRecordDetailEntities));
//        KLog.e("label", postParams.toString());

        addSubscribe(model.uploadBreedingRecordDetailList(body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(disposable -> showDialog("正在同步-配种记录子表-数据..."))
                .subscribe((Consumer<CollectResponse>) response -> {

                    if (response.getCode() == 0) {
                        KLog.e("uploadBreedingRecordDetail", response.toString());
                        for (BreedingRecordDetailEntity pe : breedingRecordDetailEntities) {
                            pe.setUploadStatus("1");
                        }
                        DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                            @Override
                            public void onNotification(boolean result) {
                                if (result) {
                                    queryBreedingRecordDetail();
                                    me.goldze.mvvmhabit.utils.ToastUtils.showShort("上传-配种记录子表-数据成功！");
                                } else {
                                    me.goldze.mvvmhabit.utils.ToastUtils.showShort("修改-配种记录子表-数据失败");
                                }
                            }
                        }).updateAsyncBatch(BreedingRecordDetailEntity.class, breedingRecordDetailEntities);
                    } else {
                        dismissDialog();
                        me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                        requestBreedingRecordDetail();
                    }
                }, (Consumer<ResponseThrowable>) throwable -> {
                    dismissDialog();
                    me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                })
        );

    }


    /**===========================================称重管理================================================= */

    /**
     * 下载-称重管理-
     */
    private void requestWeightMan() {

        //SyncState 0根据记录更新，1重新更新
        Map<String, String> requestParam = new HashMap<>();
        List<WeightManEntity> queryList = DbUtil.getInstance().queryAll(WeightManEntity.class);

        if (queryList == null || queryList.size() == 0)
            requestParam.put("SyncState", "1");
        else
            requestParam.put("SyncState", "0");

        addSubscribe(model.downloadWeightManList(requestParam)
                        .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                        .compose(RxUtils.schedulersTransformer())
                        .compose(RxUtils.exceptionTransformer())
//                .doOnSubscribe(disposable -> showDialog("正在同步称重管理数据..."))
                        .subscribe((Consumer<ListResponse<WeightManEntity>>) response -> {

                            if (response.getCode() == 0) {
                                if (response.getData() != null && response.getData().size() > 0) {
                                    KLog.e("--requestWeightManDetail--" + response.getData().size());

                                    List<String> ids = new ArrayList<>();
                                    for (WeightManEntity cre : response.getData()) {
                                        cre.setUploadStatus("1");
                                        ids.add(cre.getUnid());
                                    }

                                    DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                        @Override
                                        public void onNotification(boolean result) {
                                            if (result) {
                                                requestWeightManSync(ids);
                                            } else {
                                                dismissDialog();
                                                errorEvent.setValue("保存称重管理数据失败！");
                                            }
                                        }
                                    }).insertAsyncBatch(WeightManEntity.class, response.getData());
                                } else {
                                    dismissDialog();
                                }

                            } else {
                                errorEvent.setValue("服务器 :" + response.getMsg());
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            KLog.e(throwable.message);
                        })
        );

    }

    /**
     * 上传-称重管理-成功
     */
    private void requestWeightManSync(List<String> ids) {

//        Map<String, String> syncParam = new HashMap<>();
//        syncParam.put("ids", new Gson().toJson(ids).toString());

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(ids));
//        KLog.e("label", postParams.toString());

        addSubscribe(model.downloadWeightManListSync(body)
                        .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                        .compose(RxUtils.schedulersTransformer())
                        .compose(RxUtils.exceptionTransformer())
//                .doOnSubscribe(disposable -> showDialog("正在同步称重管理数据..."))
                        .subscribe((Consumer<CollectResponse>) response -> {

                            dismissDialog();
                            KLog.e("requestWeightManSync", response.toString());
                            if (response.getCode() == 0) {
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("同步称重管理数据成功！");
                                queryWeightMan();
                            } else {
                                dismissDialog();
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            dismissDialog();
                            me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                        })
        );
    }

    /**
     * 查询-称重管理-
     */
    private void queryWeightMan() {

        QueryBuilder<WeightManEntity> builder =
                DbUtil.getInstance().getQueryBuilder(WeightManEntity.class)
                        .where(WeightManEntityDao.Properties.UploadStatus.eq("0"))
                        .limit(10);
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<WeightManEntity>() {
            @Override
            public void onSuccess(List<WeightManEntity> result) {
                if (result != null && result.size() > 0) {
                    uploadWeightMan(result);
                } else {
                    requestWeightMan();
                }
            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("查询-称重管理-失败！");
                dismissDialog();
            }
        }).queryAsyncAll(WeightManEntity.class, builder);
    }

    /**
     * 上传-称重管理-
     */
    private void uploadWeightMan(List<WeightManEntity> weightManEntities) {

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(weightManEntities));
//        KLog.e("label", postParams.toString());

        addSubscribe(model.uploadWeightManList(body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(disposable -> showDialog("正在同步-称重管理-数据..."))
                .subscribe((Consumer<CollectResponse>) response -> {

                    if (response.getCode() == 0) {
                        KLog.e("uploadWeightMan", response.toString());
                        for (WeightManEntity pe : weightManEntities) {
                            pe.setUploadStatus("1");
                        }
                        DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                            @Override
                            public void onNotification(boolean result) {
                                if (result) {
                                    queryWeightMan();
                                    me.goldze.mvvmhabit.utils.ToastUtils.showShort("上传-称重管理-数据成功！");
                                } else {
                                    me.goldze.mvvmhabit.utils.ToastUtils.showShort("修改-称重管理-数据失败");
                                }
                            }
                        }).updateAsyncBatch(WeightManEntity.class, weightManEntities);
                    } else {
                        dismissDialog();
                        me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                        requestWeightMan();
                    }
                }, (Consumer<ResponseThrowable>) throwable -> {
                    dismissDialog();
                    me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                })
        );

    }


    /**===========================================诊疗记录================================================= */

    /**
     * 下载-诊疗记录-
     */
    private void requestMedicalRecord() {

        //SyncState 0根据记录更新，1重新更新
        Map<String, String> requestParam = new HashMap<>();
        List<MedicalRecordEntity> queryList = DbUtil.getInstance().queryAll(MedicalRecordEntity.class);

        if (queryList == null || queryList.size() == 0)
            requestParam.put("SyncState", "1");
        else
            requestParam.put("SyncState", "0");

        addSubscribe(model.downloadMedicalRecordList(requestParam)
                        .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                        .compose(RxUtils.schedulersTransformer())
                        .compose(RxUtils.exceptionTransformer())
//                .doOnSubscribe(disposable -> showDialog("正在同步诊疗记录数据..."))
                        .subscribe((Consumer<ListResponse<MedicalRecordEntity>>) response -> {

                            if (response.getCode() == 0) {
                                if (response.getData() != null && response.getData().size() > 0) {
                                    KLog.e("--requestMedicalRecord--" + response.getData().size());

                                    List<String> ids = new ArrayList<>();
                                    for (MedicalRecordEntity cre : response.getData()) {
                                        cre.setUploadStatus("1");
                                        ids.add(cre.getUnid());
                                    }

                                    DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                        @Override
                                        public void onNotification(boolean result) {
                                            if (result) {
                                                requestMedicalRecordSync(ids);
                                            } else {
                                                dismissDialog();
                                                errorEvent.setValue("保存诊疗记录数据失败！");
                                            }
                                        }
                                    }).insertAsyncBatch(MedicalRecordEntity.class, response.getData());
                                } else {
                                    dismissDialog();
                                }

                            } else {
                                errorEvent.setValue("服务器 :" + response.getMsg());
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            KLog.e(throwable.message);
                        })
        );

    }

    /**
     * 上传-诊疗记录-成功
     */
    private void requestMedicalRecordSync(List<String> ids) {

//        Map<String, String> syncParam = new HashMap<>();
//        syncParam.put("ids", new Gson().toJson(ids).toString());

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(ids));
//        KLog.e("label", postParams.toString());

        addSubscribe(model.downloadMedicalRecordListSync(body)
                        .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                        .compose(RxUtils.schedulersTransformer())
                        .compose(RxUtils.exceptionTransformer())
//                .doOnSubscribe(disposable -> showDialog("正在同步称重管理数据..."))
                        .subscribe((Consumer<CollectResponse>) response -> {

                            dismissDialog();
                            KLog.e("requestMedicalRecordSync", response.toString());
                            if (response.getCode() == 0) {
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("同步诊疗记录数据成功！");
                                queryMedicalRecord();
                            } else {
                                dismissDialog();
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            dismissDialog();
                            me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                        })
        );
    }

    /**
     * 查询-诊疗记录-
     */
    private void queryMedicalRecord() {

        QueryBuilder<MedicalRecordEntity> builder =
                DbUtil.getInstance().getQueryBuilder(MedicalRecordEntity.class)
                        .where(MedicalRecordEntityDao.Properties.UploadStatus.eq("0"))
                        .limit(10);
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<MedicalRecordEntity>() {
            @Override
            public void onSuccess(List<MedicalRecordEntity> result) {
                if (result != null && result.size() > 0) {
                    uploadMedicalRecord(result);
                } else {
                    requestMedicalRecord();
                }
            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("查询-诊疗记录-失败！");
                dismissDialog();
            }
        }).queryAsyncAll(MedicalRecordEntity.class, builder);
    }

    /**
     * 上传-诊疗记录-
     */
    private void uploadMedicalRecord(List<MedicalRecordEntity> medicalRecordEntities) {

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(medicalRecordEntities));
//        KLog.e("label", postParams.toString());

        addSubscribe(model.uploadMedicalRecordList(body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(disposable -> showDialog("正在同步-诊疗记录-数据..."))
                .subscribe((Consumer<CollectResponse>) response -> {

                    if (response.getCode() == 0) {
                        KLog.e("uploadMedicalRecord", response.toString());
                        for (MedicalRecordEntity pe : medicalRecordEntities) {
                            pe.setUploadStatus("1");
                        }
                        DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                            @Override
                            public void onNotification(boolean result) {
                                if (result) {
                                    queryMedicalRecord();
                                    me.goldze.mvvmhabit.utils.ToastUtils.showShort("上传-诊疗记录-数据成功！");
                                } else {
                                    me.goldze.mvvmhabit.utils.ToastUtils.showShort("修改-诊疗记录-数据失败");
                                }
                            }
                        }).updateAsyncBatch(MedicalRecordEntity.class, medicalRecordEntities);
                    } else {
                        dismissDialog();
                        me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                        requestMedicalRecord();
                    }
                }, (Consumer<ResponseThrowable>) throwable -> {
                    dismissDialog();
                    me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                })
        );

    }


    /**===========================================免疫记录================================================= */

    /**
     * 下载-免疫记录-
     */
    private void requestImmuneBatch() {

        //SyncState 0根据记录更新，1重新更新
        Map<String, String> requestParam = new HashMap<>();
        List<ImmuneBatchEntity> queryList = DbUtil.getInstance().queryAll(ImmuneBatchEntity.class);

        if (queryList == null || queryList.size() == 0)
            requestParam.put("SyncState", "1");
        else
            requestParam.put("SyncState", "0");

        addSubscribe(model.downloadImmuneBatchList(requestParam)
                        .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                        .compose(RxUtils.schedulersTransformer())
                        .compose(RxUtils.exceptionTransformer())
//                .doOnSubscribe(disposable -> showDialog("正在同步免疫记录数据..."))
                        .subscribe((Consumer<ListResponse<ImmuneBatchEntity>>) response -> {

                            if (response.getCode() == 0) {
                                if (response.getData() != null && response.getData().size() > 0) {
                                    KLog.e("--requestImmuneBatch--" + response.getData().size());

                                    List<String> ids = new ArrayList<>();
                                    for (ImmuneBatchEntity cre : response.getData()) {
                                        cre.setUploadStatus("1");
                                        ids.add(cre.getUnid());
                                    }

                                    DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                        @Override
                                        public void onNotification(boolean result) {
                                            if (result) {
                                                requestImmuneBatchSync(ids);
                                            } else {
                                                dismissDialog();
                                                errorEvent.setValue("保存免疫记录数据失败！");
                                            }
                                        }
                                    }).insertAsyncBatch(ImmuneBatchEntity.class, response.getData());
                                } else {
                                    dismissDialog();
                                }

                            } else {
                                errorEvent.setValue("服务器 :" + response.getMsg());
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            KLog.e(throwable.message);
                        })
        );

    }

    /**
     * 上传-免疫记录-成功
     */
    private void requestImmuneBatchSync(List<String> ids) {

//        Map<String, String> syncParam = new HashMap<>();
//        syncParam.put("ids", new Gson().toJson(ids).toString());

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(ids));
//        KLog.e("label", postParams.toString());

        addSubscribe(model.downloadImmuneBatchListSync(body)
                        .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                        .compose(RxUtils.schedulersTransformer())
                        .compose(RxUtils.exceptionTransformer())
//                .doOnSubscribe(disposable -> showDialog("正在同步称重管理数据..."))
                        .subscribe((Consumer<CollectResponse>) response -> {

                            dismissDialog();
                            KLog.e("requestImmuneBatchSync", response.toString());
                            if (response.getCode() == 0) {
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("同步免疫记录数据成功！");
                                queryImmuneBatch();
                            } else {
                                dismissDialog();
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            dismissDialog();
                            me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                        })
        );
    }

    /**
     * 查询-免疫记录-
     */
    private void queryImmuneBatch() {

        QueryBuilder<ImmuneBatchEntity> builder =
                DbUtil.getInstance().getQueryBuilder(ImmuneBatchEntity.class)
                        .where(ImmuneBatchEntityDao.Properties.UploadStatus.eq("0"))
                        .limit(10);
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<ImmuneBatchEntity>() {
            @Override
            public void onSuccess(List<ImmuneBatchEntity> result) {
                if (result != null && result.size() > 0) {
                    uploadImmuneBatch(result);
                } else {
                    requestImmuneBatch();
                }
            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("查询-免疫记录-失败！");
                dismissDialog();
            }
        }).queryAsyncAll(ImmuneBatchEntity.class, builder);
    }

    /**
     * 上传-诊疗记录-
     */
    private void uploadImmuneBatch(List<ImmuneBatchEntity> immuneBatchEntities) {

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(immuneBatchEntities));
//        KLog.e("label", postParams.toString());

        addSubscribe(model.uploadImmuneBatchList(body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(disposable -> showDialog("正在同步-免疫记录-数据..."))
                .subscribe((Consumer<CollectResponse>) response -> {

                    if (response.getCode() == 0) {
                        KLog.e("uploadImmuneBatch", response.toString());
                        for (ImmuneBatchEntity pe : immuneBatchEntities) {
                            pe.setUploadStatus("1");
                        }
                        DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                            @Override
                            public void onNotification(boolean result) {
                                if (result) {
                                    queryImmuneBatch();
                                    me.goldze.mvvmhabit.utils.ToastUtils.showShort("上传-免疫记录-数据成功！");
                                } else {
                                    me.goldze.mvvmhabit.utils.ToastUtils.showShort("修改-免疫记录-数据失败");
                                }
                            }
                        }).updateAsyncBatch(ImmuneBatchEntity.class, immuneBatchEntities);
                    } else {
                        dismissDialog();
                        me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                        requestImmuneBatch();
                    }
                }, (Consumer<ResponseThrowable>) throwable -> {
                    dismissDialog();
                    me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                })
        );

    }

}
