package com.phlx.anchorcollect_p.ui.setting;

import android.app.Application;
import android.os.Bundle;
import android.os.Environment;

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

import com.google.gson.Gson;
import com.phlx.anchorcollect_p.Configs;
import com.phlx.anchorcollect_p.data.Repository;
import com.phlx.anchorcollect_p.db.DbUtil;
import com.phlx.anchorcollect_p.db.gen.BreedingRecordDetailEntityDao;
import com.phlx.anchorcollect_p.db.gen.BreedingRecordEntityDao;
import com.phlx.anchorcollect_p.db.gen.CattleResumeEntityDao;
import com.phlx.anchorcollect_p.db.gen.ImmuneBatchDetailEntityDao;
import com.phlx.anchorcollect_p.db.gen.ImmuneBatchEntityDao;
import com.phlx.anchorcollect_p.db.gen.MedicalRecordEntityDao;
import com.phlx.anchorcollect_p.db.gen.PerformanceEntityDao;
import com.phlx.anchorcollect_p.db.gen.WeightManEntityDao;
import com.phlx.anchorcollect_p.db.interf.DbIDUCallBack;
import com.phlx.anchorcollect_p.db.interf.DbQueryCallBack;
import com.phlx.anchorcollect_p.entity.BreedingRecordDetailEntity;
import com.phlx.anchorcollect_p.entity.BreedingRecordEntity;
import com.phlx.anchorcollect_p.entity.CattleResumeEntity;
import com.phlx.anchorcollect_p.entity.ErrorEntity;
import com.phlx.anchorcollect_p.entity.ImmuneBatchDetailEntity;
import com.phlx.anchorcollect_p.entity.ImmuneBatchEntity;
import com.phlx.anchorcollect_p.entity.MedicalRecordEntity;
import com.phlx.anchorcollect_p.entity.PerformanceEntity;
import com.phlx.anchorcollect_p.entity.WeightManEntity;
import com.phlx.anchorcollect_p.params.CollectResponse;
import com.phlx.anchorcollect_p.params.ListResponse;
import com.phlx.anchorcollect_p.ui.login.LoginActivity;
import com.phlx.anchorcollect_p.util.BaseImageUtils;

import org.greenrobot.greendao.query.QueryBuilder;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.goldze.mvvmhabit.utils.SPUtils;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class SyncVM extends BaseViewModel<Repository> {

    final private static String UPLOAD_STATUS_HAVE_NOT = "0";
    final private static String UPLOAD_STATUS_HAVE = "1";
    final private static String UPLOAD_STATUS_ERROR = "2";


    //错误提示
    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> immunebatchDetailCount = new ObservableField<>("0");
    public ObservableField<String> cattlematingMasterCount = new ObservableField<>("0");
    public ObservableField<String> cattlematingDetaillCount = new ObservableField<>("0");

    public ObservableField<String> cattleresumeErrorCount = new ObservableField<>("0");
    public ObservableField<String> performanceErrorCount = new ObservableField<>("0");
    public ObservableField<String> weightManErrorCount = new ObservableField<>("0");
    public ObservableField<String> medicalrecordsErrorCount = new ObservableField<>("0");
    public ObservableField<String> immunebatchErrorCount = new ObservableField<>("0");
    public ObservableField<String> immunebatchDetailErrorCount = new ObservableField<>("0");
    public ObservableField<String> cattlematingMasterErrorCount = new ObservableField<>("0");
    public ObservableField<String> cattlematingDetaillErrorCount = new ObservableField<>("0");

    public ObservableField<String> cattleresumeDate = new ObservableField<>("");
    public ObservableField<String> performanceDate = new ObservableField<>("");
    public ObservableField<String> weightManDate = new ObservableField<>("");
    public ObservableField<String> medicalrecordsDate = new ObservableField<>("");
    public ObservableField<String> immunebatchDate = new ObservableField<>("");
    public ObservableField<String> immunebatchDetailDate = new ObservableField<>("");
    public ObservableField<String> cattlematingMasterDate = new ObservableField<>("");
    public ObservableField<String> cattlematingDetaillDate = new ObservableField<>("");

    //照片路径
    private String imgUrl;


    private SimpleDateFormat dateFormat;

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

        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        queryUpdateTime();

        queryUploadCount(true);
    }

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

    public BindingCommand OnSignMeasureSyncClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            showDialog("正在同步性能测定数据...");
            querySignMeasure();
        }
    });

    public BindingCommand OnWeightingManageSyncClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            showDialog("正在同步称重管理数据...");
            queryWeightMan();
        }
    });

    public BindingCommand OnMedicalRecordSyncClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            showDialog("正在同步诊疗记录数据...");
            queryMedicalRecord();
        }
    });

    public BindingCommand OnImmunRecordSyncClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            showDialog("正在同步免疫记录-主表数据...");
            queryImmuneBatch();
        }
    });

    public BindingCommand OnImmunRecordDetailSyncClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            showDialog("正在同步免疫记录-子表数据...");
            queryImmuneBatchDetail();
        }
    });

    public BindingCommand OnBreedingRecordSyncClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            showDialog("正在同步配种记录-主表数据...");
            queryBreedingRecord();
        }
    });

    public BindingCommand OnBreedingRecordDetailSyncClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            showDialog("正在同步配种记录-子表数据...");
            queryBreedingRecordDetail();
        }
    });

    public BindingCommand OnErrorDataUploadClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            showDialog("正在上报错误数据...");
            uploadErrorData();
        }
    });

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

    /**
     * 下载基础数据
     */
    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) {

                                //存下最后更新的时间
                                SPUtils.getInstance().put(Configs.SP_CATTLE_RESUME_UPDATE_DATE, dateFormat.format(new Date()));
                                cattleresumeDate.set(SPUtils.getInstance().getString(Configs.SP_CATTLE_RESUME_UPDATE_DATE));

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

                                    List<Long> ids = new ArrayList<>();

//                            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
//                                    "/collect/picture/");
//                                    String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/collect/picture/";
                                    // getExternalFilesDir() 用于获取SDCard/Android/data/你的应用的包名/files/ 目录
                                    File externalFileRootDir = getApplication().getExternalFilesDir("/collect/picture/");
//                                    externalFileRootDir.mkdirs();
                                    String savePath = externalFileRootDir.getAbsolutePath();

                                    for (CattleResumeEntity cre : response.getData()) {
                                        imgUrl = savePath + "/anchorCiq" + cre.getUnid() + ".jpg";
                                        cre.setPhotoPath(imgUrl);
                                        BaseImageUtils.saveBaseImage(cre.getPhoto(), imgUrl);
                                        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 {
                                    me.goldze.mvvmhabit.utils.ToastUtils.showShort("同步基础数据成功！");
                                    queryCattleResumeUploadCount(false, "0");
                                    dismissDialog();
                                }

                            } else if (response.getCode() == 401) {
                                dismissDialog();
                                Bundle bundle = new Bundle();
                                bundle.putInt("loginType", 1);
                                startActivity(LoginActivity.class, bundle);
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                            } else {
                                dismissDialog();
                                errorEvent.setValue("服务器 :" + response.getMsg());
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            dismissDialog();
                            KLog.e(throwable.message);
                        })
        );
    }

    /**
     * 返回-基础数据-成功
     */
    private void requestBaseArchivesSync(List<Long> 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) {
                                requestBaseArchives();
                            } else if (response.getCode() == 401) {
                                dismissDialog();
                                Bundle bundle = new Bundle();
                                bundle.putInt("loginType", 1);
                                startActivity(LoginActivity.class, bundle);
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                            } else {
                                dismissDialog();
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            dismissDialog();
                            me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                        })
        );
    }

    /**
     * 查询-基础数据
     */
    private void queryBaseArchives() {

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

            @Override
            public void onFailed() {
                ToastUtils.showShort("查询基础信息失败！");
                dismissDialog();
            }
        }).queryAsyncAll(CattleResumeEntity.class, builder);
    }

    /**
     * 上传-基础数据
     */
    private void uploadBaseArchives(List<CattleResumeEntity> cattleResumeEntities) {

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

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

                            dismissDialog();
                            KLog.e("uploadBaseArchives", response.toString());
                            //先都设置成错误数据
                            for (CattleResumeEntity pe : cattleResumeEntities) {
                                pe.setUploadStatus("2");
                            }
                            if (response.getCode() == 0) {
                                if (response.getData() != null && response.getData().size() > 0) {
                                    for (CattleResumeEntity pe : cattleResumeEntities) {
                                        for (Long ids : response.getData()) {
                                            if (pe.getUnid().equals(ids)) {
                                                pe.setUploadStatus("1");
                                                break;
                                            }
                                        }
                                    }
                                }
                                DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                    @Override
                                    public void onNotification(boolean result) {
                                        if (result) {
                                            me.goldze.mvvmhabit.utils.ToastUtils.showShort("上传基础信息数据成功！");
                                            queryBaseArchives();
                                        } else {
                                            dismissDialog();
                                            me.goldze.mvvmhabit.utils.ToastUtils.showShort("修改基础信息数据失败");
                                        }
                                    }
                                }).updateAsyncBatch(CattleResumeEntity.class, cattleResumeEntities);
                            } else if (response.getCode() == 401) {
                                dismissDialog();
                                Bundle bundle = new Bundle();
                                bundle.putInt("loginType", 1);
                                startActivity(LoginActivity.class, bundle);
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                            } else {
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                                requestBaseArchives();
                            }
                        }, (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) {

                                //存下最后更新的时间
                                SPUtils.getInstance().put(Configs.SP_PERFORMANCE_UPDATE_DATE, dateFormat.format(new Date()));
                                performanceDate.set(SPUtils.getInstance().getString(Configs.SP_PERFORMANCE_UPDATE_DATE));

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

                                    List<Long> 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();
                                    ToastUtils.showShort("性能测定数据同步完成！");
                                    queryPerformanceUploadCount(false, "0");
                                }

                            } else if (response.getCode() == 401) {
                                dismissDialog();
                                Bundle bundle = new Bundle();
                                bundle.putInt("loginType", 1);
                                startActivity(LoginActivity.class, bundle);
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                            } else {
                                errorEvent.setValue("服务器 :" + response.getMsg());
                                dismissDialog();
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            dismissDialog();
                            KLog.e(throwable.message);
                        })
        );

    }

    /**
     * 同步-性能测定-成功
     */
    private void requestSignMeasureSync(List<Long> 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 if (response.getCode() == 401) {
                                dismissDialog();
                                Bundle bundle = new Bundle();
                                bundle.putInt("loginType", 1);
                                startActivity(LoginActivity.class, bundle);
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                            } 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<ListResponse<Long>>) response -> {

                            dismissDialog();
                            KLog.e("uploadSignMeasure", response.toString());
                            //先都设置成错误数据
                            for (PerformanceEntity pe : performanceEntities) {
                                pe.setUploadStatus("2");
                            }
                            if (response.getCode() == 0) {
                                if (response.getData() != null && response.getData().size() > 0) {
                                    for (PerformanceEntity pe : performanceEntities) {
                                        for (Long ids : response.getData()) {
                                            if (pe.getUnid().equals(ids)) {
                                                pe.setUploadStatus("1");
                                                break;
                                            }
                                        }
                                    }
                                }
                                DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                    @Override
                                    public void onNotification(boolean result) {
                                        if (result) {
                                            me.goldze.mvvmhabit.utils.ToastUtils.showShort("上传性能测定数据成功！");
                                            querySignMeasure();
                                        } else {
                                            dismissDialog();
                                            me.goldze.mvvmhabit.utils.ToastUtils.showShort("修改性能测定数据失败");
                                        }
                                    }
                                }).updateAsyncBatch(PerformanceEntity.class, performanceEntities);
                            } else if (response.getCode() == 401) {
                                dismissDialog();
                                Bundle bundle = new Bundle();
                                bundle.putInt("loginType", 1);
                                startActivity(LoginActivity.class, bundle);
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                            } 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) {

                                //存下最后更新的时间
                                SPUtils.getInstance().put(Configs.SP_BREEDING_RECORD_UPDATE_DATE, dateFormat.format(new Date()));
                                cattlematingMasterDate.set(SPUtils.getInstance().getString(Configs.SP_BREEDING_RECORD_UPDATE_DATE));

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

                                    List<Long> 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();
                                    me.goldze.mvvmhabit.utils.ToastUtils.showShort("同步配种主表数据成功！");
                                    queryBreedingRecordUploadCount(false, "0");
                                }

                            } else if (response.getCode() == 401) {
                                dismissDialog();
                                Bundle bundle = new Bundle();
                                bundle.putInt("loginType", 1);
                                startActivity(LoginActivity.class, bundle);
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                            } else {
                                errorEvent.setValue("服务器 :" + response.getMsg());
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            KLog.e(throwable.message);
                        })
        );

    }

    /**
     * 上传-配种记录主表-成功
     */
    private void requestBreedingRecordSync(List<Long> 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) {
                                requestBreedingRecord();
                            } else if (response.getCode() == 401) {
                                dismissDialog();
                                Bundle bundle = new Bundle();
                                bundle.putInt("loginType", 1);
                                startActivity(LoginActivity.class, bundle);
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                            } 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<ListResponse<Long>>) response -> {

                    if (response.getCode() == 0) {
                        KLog.e("uploadBreedingRecord", response.toString());
                        for (BreedingRecordEntity pe : breedingRecordEntities) {
                            pe.setUploadStatus("2");
                        }
                        if (response.getData() != null && response.getData().size() > 0) {
                            for (BreedingRecordEntity pe : breedingRecordEntities) {
                                for (Long ids : response.getData()) {
                                    if (pe.getUnid().equals(ids)) {
                                        pe.setUploadStatus("1");
                                        break;
                                    }
                                }
                            }
                        }
                        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 if (response.getCode() == 401) {
                        dismissDialog();
                        Bundle bundle = new Bundle();
                        bundle.putInt("loginType", 1);
                        startActivity(LoginActivity.class, bundle);
                        me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                    } 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) {

                                //存下最后更新的时间
                                SPUtils.getInstance().put(Configs.SP_BREEDING_RECORD_DETAIL_UPDATE_DATE, dateFormat.format(new Date()));
                                cattlematingDetaillDate.set(SPUtils.getInstance().getString(Configs.SP_BREEDING_RECORD_DETAIL_UPDATE_DATE));

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

                                    List<Long> 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();
                                    me.goldze.mvvmhabit.utils.ToastUtils.showShort("同步配种记录子表数据成功！");
                                    queryBreedingRecordDetailUploadCount(false, "0");
                                }

                            } else if (response.getCode() == 401) {
                                dismissDialog();
                                Bundle bundle = new Bundle();
                                bundle.putInt("loginType", 1);
                                startActivity(LoginActivity.class, bundle);
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                            } else {
                                errorEvent.setValue("服务器 :" + response.getMsg());
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            KLog.e(throwable.message);
                        })
        );

    }

    /**
     * 上传-配种记录子表-成功
     */
    private void requestBreedingRecordDetailSync(List<Long> 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) {
                                queryBreedingRecordDetail();
                            } else if (response.getCode() == 401) {
                                dismissDialog();
                                Bundle bundle = new Bundle();
                                bundle.putInt("loginType", 1);
                                startActivity(LoginActivity.class, bundle);
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                            } 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<ListResponse<Long>>) response -> {

                    if (response.getCode() == 0) {
                        KLog.e("uploadBreedingRecordDetail", response.toString());
                        for (BreedingRecordDetailEntity pe : breedingRecordDetailEntities) {
                            pe.setUploadStatus("2");
                        }
                        if (response.getData() != null && response.getData().size() > 0) {
                            for (BreedingRecordDetailEntity pe : breedingRecordDetailEntities) {
                                for (Long ids : response.getData()) {
                                    if (pe.getUnid().equals(ids)) {
                                        pe.setUploadStatus("1");
                                        break;
                                    }
                                }
                            }
                        }
                        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 if (response.getCode() == 401) {
                        dismissDialog();
                        Bundle bundle = new Bundle();
                        bundle.putInt("loginType", 1);
                        startActivity(LoginActivity.class, bundle);
                        me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                    } 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) {

                                //存下最后更新的时间
                                SPUtils.getInstance().put(Configs.SP_WEIGHT_MAN_UPDATE_DATE, dateFormat.format(new Date()));
                                weightManDate.set(SPUtils.getInstance().getString(Configs.SP_WEIGHT_MAN_UPDATE_DATE));

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

                                    List<Long> 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 {
                                    me.goldze.mvvmhabit.utils.ToastUtils.showShort("同步称重管理数据成功！");
                                    dismissDialog();
                                    queryWeightManUploadCount(false, "0");
                                }

                            } else if (response.getCode() == 401) {
                                dismissDialog();
                                Bundle bundle = new Bundle();
                                bundle.putInt("loginType", 1);
                                startActivity(LoginActivity.class, bundle);
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                            } else {
                                errorEvent.setValue("服务器 :" + response.getMsg());
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            KLog.e(throwable.message);
                        })
        );

    }

    /**
     * 上传-称重管理-成功
     */
    private void requestWeightManSync(List<Long> 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) {
                                queryWeightMan();
                            } else if (response.getCode() == 401) {
                                dismissDialog();
                                Bundle bundle = new Bundle();
                                bundle.putInt("loginType", 1);
                                startActivity(LoginActivity.class, bundle);
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                            } 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<ListResponse<Long>>) response -> {

                    if (response.getCode() == 0) {
                        KLog.e("uploadWeightMan", response.toString());
                        for (WeightManEntity pe : weightManEntities) {
                            pe.setUploadStatus("2");
                        }
                        if (response.getData() != null && response.getData().size() > 0) {
                            for (WeightManEntity pe : weightManEntities) {
                                for (Long ids : response.getData()) {
                                    if (pe.getUnid().equals(ids)) {
                                        pe.setUploadStatus("1");
                                        break;
                                    }
                                }
                            }
                        }
                        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("修改-称重管理-数据失败");
                                    dismissDialog();
                                }
                            }
                        }).updateAsyncBatch(WeightManEntity.class, weightManEntities);
                    } else if (response.getCode() == 401) {
                        dismissDialog();
                        Bundle bundle = new Bundle();
                        bundle.putInt("loginType", 1);
                        startActivity(LoginActivity.class, bundle);
                        me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                    } else {
                        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) {

                                //存下最后更新的时间
                                SPUtils.getInstance().put(Configs.SP_MEDICAL_RECORD_UPDATE_DATE, dateFormat.format(new Date()));
                                medicalrecordsDate.set(SPUtils.getInstance().getString(Configs.SP_MEDICAL_RECORD_UPDATE_DATE));

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

                                    List<Long> 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();
                                    me.goldze.mvvmhabit.utils.ToastUtils.showShort("同步诊疗记录数据成功！");
                                    queryMedicalRecordUploadCount(false, "0");
                                }

                            } else if (response.getCode() == 401) {
                                dismissDialog();
                                Bundle bundle = new Bundle();
                                bundle.putInt("loginType", 1);
                                startActivity(LoginActivity.class, bundle);
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                            } else {
                                errorEvent.setValue("服务器 :" + response.getMsg());
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            KLog.e(throwable.message);
                        })
        );

    }

    /**
     * 上传-诊疗记录-成功
     */
    private void requestMedicalRecordSync(List<Long> 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) {
                                queryMedicalRecord();
                            } else if (response.getCode() == 401) {
                                dismissDialog();
                                Bundle bundle = new Bundle();
                                bundle.putInt("loginType", 1);
                                startActivity(LoginActivity.class, bundle);
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                            } 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<ListResponse<Long>>) response -> {

                    if (response.getCode() == 0) {
                        KLog.e("uploadMedicalRecord", response.toString());
                        for (MedicalRecordEntity pe : medicalRecordEntities) {
                            pe.setUploadStatus("2");
                        }
                        if (response.getData() != null && response.getData().size() > 0) {
                            for (MedicalRecordEntity pe : medicalRecordEntities) {
                                for (Long ids : response.getData()) {
                                    if (pe.getUnid().equals(ids)) {
                                        pe.setUploadStatus("1");
                                        break;
                                    }
                                }
                            }
                        }
                        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("修改-诊疗记录-数据失败");
                                    dismissDialog();
                                }
                            }
                        }).updateAsyncBatch(MedicalRecordEntity.class, medicalRecordEntities);
                    } else if (response.getCode() == 401) {
                        dismissDialog();
                        Bundle bundle = new Bundle();
                        bundle.putInt("loginType", 1);
                        startActivity(LoginActivity.class, bundle);
                        me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                    } 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) {

                                //存下最后更新的时间
                                SPUtils.getInstance().put(Configs.SP_IMMUNE_BATCH_UPDATE_DATE, dateFormat.format(new Date()));
                                immunebatchDate.set(SPUtils.getInstance().getString(Configs.SP_IMMUNE_BATCH_UPDATE_DATE));

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

                                    List<Long> 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();
                                    me.goldze.mvvmhabit.utils.ToastUtils.showShort("同步免疫记录-主表数据成功！");
                                    queryImmuneBatchUploadCount(false, "0");
                                }

                            } else if (response.getCode() == 401) {
                                dismissDialog();
                                Bundle bundle = new Bundle();
                                bundle.putInt("loginType", 1);
                                startActivity(LoginActivity.class, bundle);
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                            } else {
                                dismissDialog();
                                errorEvent.setValue("服务器 :" + response.getMsg());
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            dismissDialog();
                            KLog.e(throwable.message);
                        })
        );

    }

    /**
     * 上传-免疫记录-主表-成功
     */
    private void requestImmuneBatchSync(List<Long> 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) {
                                queryImmuneBatch();
                            } else if (response.getCode() == 401) {
                                dismissDialog();
                                Bundle bundle = new Bundle();
                                bundle.putInt("loginType", 1);
                                startActivity(LoginActivity.class, bundle);
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                            } 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<ListResponse<Long>>) response -> {

                    if (response.getCode() == 0) {
                        KLog.e("uploadImmuneBatch", response.toString());
                        for (ImmuneBatchEntity pe : immuneBatchEntities) {
                            pe.setUploadStatus("2");
                        }
                        if (response.getData() != null && response.getData().size() > 0) {
                            for (ImmuneBatchEntity pe : immuneBatchEntities) {
                                for (Long ids : response.getData()) {
                                    if (pe.getUnid().equals(ids)) {
                                        pe.setUploadStatus("1");
                                        break;
                                    }
                                }
                            }
                        }
                        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("修改-免疫记录-主表-数据失败");
                                    dismissDialog();
                                }
                            }
                        }).updateAsyncBatch(ImmuneBatchEntity.class, immuneBatchEntities);
                    } else if (response.getCode() == 401) {
                        dismissDialog();
                        Bundle bundle = new Bundle();
                        bundle.putInt("loginType", 1);
                        startActivity(LoginActivity.class, bundle);
                        me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                    } else {
                        dismissDialog();
                        me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                        requestImmuneBatch();
                    }
                }, (Consumer<ResponseThrowable>) throwable -> {
                    dismissDialog();
                    me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                })
        );

    }


    /**===========================================免疫记录-子表================================================= */

    /**
     * 下载-免疫记录-子表
     */
    private void requestImmuneBatchDetail() {

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

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

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

                            if (response.getCode() == 0) {

                                //存下最后更新的时间
                                SPUtils.getInstance().put(Configs.SP_IMMUNE_BATCH_DETAIL_UPDATE_DATE, dateFormat.format(new Date()));
                                immunebatchDetailDate.set(SPUtils.getInstance().getString(Configs.SP_IMMUNE_BATCH_DETAIL_UPDATE_DATE));

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

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

                                    DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                        @Override
                                        public void onNotification(boolean result) {
                                            if (result) {
                                                requestImmuneBatchDetailSync(ids);
                                            } else {
                                                dismissDialog();
                                                errorEvent.setValue("保存免疫记录-子表数据失败！");
                                            }
                                        }
                                    }).insertAsyncBatch(ImmuneBatchDetailEntity.class, response.getData());
                                } else {
                                    dismissDialog();
                                    me.goldze.mvvmhabit.utils.ToastUtils.showShort("同步免疫记录-子表数据成功！");
                                    queryImmuneBatchDetailUploadCount(false, "0");
                                }

                            } else if (response.getCode() == 401) {
                                dismissDialog();
                                Bundle bundle = new Bundle();
                                bundle.putInt("loginType", 1);
                                startActivity(LoginActivity.class, bundle);
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                            } else {
                                errorEvent.setValue("服务器 :" + response.getMsg());
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            KLog.e(throwable.message);
                        })
        );

    }

    /**
     * 上传-免疫记录-子表-成功
     */
    private void requestImmuneBatchDetailSync(List<Long> 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.downloadImmuneBatchDetailListSync(body)
                        .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                        .compose(RxUtils.schedulersTransformer())
                        .compose(RxUtils.exceptionTransformer())
//                .doOnSubscribe(disposable -> showDialog("正在同步免疫记录-子表数据..."))
                        .subscribe((Consumer<CollectResponse>) response -> {

                            dismissDialog();
                            KLog.e("requestImmuneBatchDetailSync", response.toString());
                            if (response.getCode() == 0) {
                                queryImmuneBatchDetail();
                            } else if (response.getCode() == 401) {
                                dismissDialog();
                                Bundle bundle = new Bundle();
                                bundle.putInt("loginType", 1);
                                startActivity(LoginActivity.class, bundle);
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                            } else {
                                dismissDialog();
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            dismissDialog();
                            me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                        })
        );
    }

    /**
     * 查询-免疫记录-子表
     */
    private void queryImmuneBatchDetail() {

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

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

    /**
     * 上传-免疫记录-子表
     */
    private void uploadImmuneBatchDetail(List<ImmuneBatchDetailEntity> immuneBatchEntities) {

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

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

                    if (response.getCode() == 0) {
                        KLog.e("uploadImmuneBatchDetail", response.toString());
                        for (ImmuneBatchDetailEntity pe : immuneBatchEntities) {
                            pe.setUploadStatus("2");
                        }
                        if (response.getData() != null && response.getData().size() > 0) {
                            for (ImmuneBatchDetailEntity pe : immuneBatchEntities) {
                                for (Long ids : response.getData()) {
                                    if (pe.getUnid().equals(ids)) {
                                        pe.setUploadStatus("1");
                                        break;
                                    }
                                }
                            }
                        }
                        DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                            @Override
                            public void onNotification(boolean result) {
                                if (result) {
                                    queryImmuneBatchDetail();
                                    me.goldze.mvvmhabit.utils.ToastUtils.showShort("上传-免疫记录-子表-数据成功！");
                                } else {
                                    me.goldze.mvvmhabit.utils.ToastUtils.showShort("修改-免疫记录-子表-数据失败");
                                    dismissDialog();
                                }
                            }
                        }).updateAsyncBatch(ImmuneBatchDetailEntity.class, immuneBatchEntities);
                    } else if (response.getCode() == 401) {
                        dismissDialog();
                        Bundle bundle = new Bundle();
                        bundle.putInt("loginType", 1);
                        startActivity(LoginActivity.class, bundle);
                        me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                    } else {
                        dismissDialog();
                        me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                        requestImmuneBatchDetail();
                    }
                }, (Consumer<ResponseThrowable>) throwable -> {
                    dismissDialog();
                    me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                })
        );

    }

    //刷新待上传数量
    private void queryUploadCount(boolean isContinue) {
        queryCattleResumeUploadCount(isContinue, UPLOAD_STATUS_HAVE_NOT);
    }

    //刷新数据更新时间
    private void queryUpdateTime() {

        cattleresumeDate.set(SPUtils.getInstance().getString(Configs.SP_CATTLE_RESUME_UPDATE_DATE));
        performanceDate.set(SPUtils.getInstance().getString(Configs.SP_PERFORMANCE_UPDATE_DATE));
        weightManDate.set(SPUtils.getInstance().getString(Configs.SP_WEIGHT_MAN_UPDATE_DATE));
        medicalrecordsDate.set(SPUtils.getInstance().getString(Configs.SP_MEDICAL_RECORD_UPDATE_DATE));
        immunebatchDate.set(SPUtils.getInstance().getString(Configs.SP_IMMUNE_BATCH_UPDATE_DATE));
        immunebatchDetailDate.set(SPUtils.getInstance().getString(Configs.SP_IMMUNE_BATCH_DETAIL_UPDATE_DATE));
        cattlematingMasterDate.set(SPUtils.getInstance().getString(Configs.SP_BREEDING_RECORD_UPDATE_DATE));
        cattlematingDetaillDate.set(SPUtils.getInstance().getString(Configs.SP_BREEDING_RECORD_DETAIL_UPDATE_DATE));
    }

    /**
     * 基础数据
     */
    private void queryCattleResumeUploadCount(boolean isContinue, String uploadType) {
        QueryBuilder<CattleResumeEntity> builder0 =
                DbUtil.getInstance().getQueryBuilder(CattleResumeEntity.class)
                        .where(CattleResumeEntityDao.Properties.UploadStatus.eq(uploadType));
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<CattleResumeEntity>() {
            @Override
            public void onSuccess(List<CattleResumeEntity> result) {
                if (result != null) {
                    switch (uploadType) {
                        case UPLOAD_STATUS_HAVE_NOT:
                            cattleresumeCount.set(result.size() + "");
                            break;
                        case UPLOAD_STATUS_ERROR:
                            cattleresumeErrorCount.set(result.size() + "");
                            break;
                    }
                }

                //如果是未上传就继续查错误数据，如果不是就看状态是否继续
                if (UPLOAD_STATUS_HAVE_NOT.equals(uploadType)) {
                    queryCattleResumeUploadCount(isContinue, UPLOAD_STATUS_ERROR);
                } else if (isContinue)
                    queryPerformanceUploadCount(isContinue, UPLOAD_STATUS_HAVE_NOT);
            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("查询基础数据数量失败！");
                dismissDialog();
            }
        }).queryAsyncAll(CattleResumeEntity.class, builder0);

    }

    /**
     * 性能测定
     */
    private void queryPerformanceUploadCount(boolean isContinue, String uploadType) {
        QueryBuilder<PerformanceEntity> builder1 =
                DbUtil.getInstance().getQueryBuilder(PerformanceEntity.class)
                        .where(PerformanceEntityDao.Properties.UploadStatus.eq(uploadType));
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<PerformanceEntity>() {
            @Override
            public void onSuccess(List<PerformanceEntity> result) {
                if (result != null) {
                    switch (uploadType) {
                        case UPLOAD_STATUS_HAVE_NOT:
                            performanceCount.set(result.size() + "");
                            break;
                        case UPLOAD_STATUS_ERROR:
                            performanceErrorCount.set(result.size() + "");
                            break;
                    }
                }

                //如果是未上传就继续查错误数据，如果不是就看状态是否继续
                if (UPLOAD_STATUS_HAVE_NOT.equals(uploadType)) {
                    queryPerformanceUploadCount(isContinue, UPLOAD_STATUS_ERROR);
                } else if (isContinue)
                    queryWeightManUploadCount(isContinue, UPLOAD_STATUS_HAVE_NOT);

            }

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

    }

    /**
     * 称重管理
     */
    private void queryWeightManUploadCount(boolean isContinue, String uploadType) {
        QueryBuilder<WeightManEntity> builder2 =
                DbUtil.getInstance().getQueryBuilder(WeightManEntity.class)
                        .where(WeightManEntityDao.Properties.UploadStatus.eq(uploadType));
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<WeightManEntity>() {
            @Override
            public void onSuccess(List<WeightManEntity> result) {
                if (result != null) {
                    switch (uploadType) {
                        case UPLOAD_STATUS_HAVE_NOT:
                            weightManCount.set(result.size() + "");
                            break;
                        case UPLOAD_STATUS_ERROR:
                            weightManErrorCount.set(result.size() + "");
                            break;
                    }
                }

                //如果是未上传就继续查错误数据，如果不是就看状态是否继续
                if (UPLOAD_STATUS_HAVE_NOT.equals(uploadType)) {
                    queryWeightManUploadCount(isContinue, UPLOAD_STATUS_ERROR);
                } else if (isContinue)
                    queryMedicalRecordUploadCount(isContinue, UPLOAD_STATUS_HAVE_NOT);

            }

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

    }

    /**
     * 诊疗记录
     */
    private void queryMedicalRecordUploadCount(boolean isContinue, String uploadType) {
        QueryBuilder<MedicalRecordEntity> builder3 =
                DbUtil.getInstance().getQueryBuilder(MedicalRecordEntity.class)
                        .where(MedicalRecordEntityDao.Properties.UploadStatus.eq(uploadType));
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<MedicalRecordEntity>() {
            @Override
            public void onSuccess(List<MedicalRecordEntity> result) {
                if (result != null) {
                    switch (uploadType) {
                        case UPLOAD_STATUS_HAVE_NOT:
                            medicalrecordsCount.set(result.size() + "");
                            break;
                        case UPLOAD_STATUS_ERROR:
                            medicalrecordsErrorCount.set(result.size() + "");
                            break;
                    }
                }

                //如果是未上传就继续查错误数据，如果不是就看状态是否继续
                if (UPLOAD_STATUS_HAVE_NOT.equals(uploadType)) {
                    queryMedicalRecordUploadCount(isContinue, UPLOAD_STATUS_ERROR);
                } else if (isContinue)
                    queryImmuneBatchUploadCount(isContinue, UPLOAD_STATUS_HAVE_NOT);

            }

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

    }

    /**
     * 免疫记录-主表
     */
    private void queryImmuneBatchUploadCount(boolean isContinue, String uploadType) {
        QueryBuilder<ImmuneBatchEntity> builder4 =
                DbUtil.getInstance().getQueryBuilder(ImmuneBatchEntity.class)
                        .where(ImmuneBatchEntityDao.Properties.UploadStatus.eq(uploadType));
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<ImmuneBatchEntity>() {
            @Override
            public void onSuccess(List<ImmuneBatchEntity> result) {
                if (result != null) {
                    switch (uploadType) {
                        case UPLOAD_STATUS_HAVE_NOT:
                            immunebatchCount.set(result.size() + "");
                            break;
                        case UPLOAD_STATUS_ERROR:
                            immunebatchErrorCount.set(result.size() + "");
                            break;
                    }
                }

                //如果是未上传就继续查错误数据，如果不是就看状态是否继续
                if (UPLOAD_STATUS_HAVE_NOT.equals(uploadType)) {
                    queryImmuneBatchUploadCount(isContinue, UPLOAD_STATUS_ERROR);
                } else if (isContinue)
                    queryImmuneBatchDetailUploadCount(isContinue, UPLOAD_STATUS_HAVE_NOT);

            }

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

    }

    /**
     * 免疫记录-子表
     */
    private void queryImmuneBatchDetailUploadCount(boolean isContinue, String uploadType) {
        QueryBuilder<ImmuneBatchDetailEntity> builder5 =
                DbUtil.getInstance().getQueryBuilder(ImmuneBatchDetailEntity.class)
                        .where(ImmuneBatchDetailEntityDao.Properties.UploadStatus.eq(uploadType));
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<ImmuneBatchDetailEntity>() {
            @Override
            public void onSuccess(List<ImmuneBatchDetailEntity> result) {
                if (result != null) {
                    switch (uploadType) {
                        case UPLOAD_STATUS_HAVE_NOT:
                            immunebatchDetailCount.set(result.size() + "");
                            break;
                        case UPLOAD_STATUS_ERROR:
                            immunebatchDetailErrorCount.set(result.size() + "");
                            break;
                    }
                }

                //如果是未上传就继续查错误数据，如果不是就看状态是否继续
                if (UPLOAD_STATUS_HAVE_NOT.equals(uploadType)) {
                    queryImmuneBatchDetailUploadCount(isContinue, UPLOAD_STATUS_ERROR);
                } else if (isContinue)
                    queryBreedingRecordUploadCount(isContinue, UPLOAD_STATUS_HAVE_NOT);

            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("查询免疫记录-子表数量失败！");
                dismissDialog();
            }
        }).queryAsyncAll(ImmuneBatchDetailEntity.class, builder5);

    }

    /**
     * 配种记录-主表
     */
    private void queryBreedingRecordUploadCount(boolean isContinue, String uploadType) {
        QueryBuilder<BreedingRecordEntity> builder6 =
                DbUtil.getInstance().getQueryBuilder(BreedingRecordEntity.class)
                        .where(BreedingRecordEntityDao.Properties.UploadStatus.eq(uploadType));
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<BreedingRecordEntity>() {
            @Override
            public void onSuccess(List<BreedingRecordEntity> result) {
                if (result != null) {
                    switch (uploadType) {
                        case UPLOAD_STATUS_HAVE_NOT:
                            cattlematingMasterCount.set(result.size() + "");
                            break;
                        case UPLOAD_STATUS_ERROR:
                            cattlematingMasterErrorCount.set(result.size() + "");
                            break;
                    }
                }

                //如果是未上传就继续查错误数据，如果不是就看状态是否继续
                if (UPLOAD_STATUS_HAVE_NOT.equals(uploadType)) {
                    queryBreedingRecordUploadCount(isContinue, UPLOAD_STATUS_ERROR);
                } else if (isContinue)
                    queryBreedingRecordDetailUploadCount(isContinue, UPLOAD_STATUS_HAVE_NOT);

            }

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

    }

    /**
     * 配种记录-子表
     */
    private void queryBreedingRecordDetailUploadCount(boolean isContinue, String uploadType) {
        QueryBuilder<BreedingRecordDetailEntity> builder7 =
                DbUtil.getInstance().getQueryBuilder(BreedingRecordDetailEntity.class)
                        .where(BreedingRecordDetailEntityDao.Properties.UploadStatus.eq(uploadType));
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<BreedingRecordDetailEntity>() {
            @Override
            public void onSuccess(List<BreedingRecordDetailEntity> result) {
                if (result != null) {
                    switch (uploadType) {
                        case UPLOAD_STATUS_HAVE_NOT:
                            cattlematingDetaillCount.set(result.size() + "");
                            break;
                        case UPLOAD_STATUS_ERROR:
                            cattlematingDetaillErrorCount.set(result.size() + "");
                            break;
                    }
                }

                //如果是未上传就继续查错误数据，如果不是就停止
                if (UPLOAD_STATUS_HAVE_NOT.equals(uploadType)) {
                    queryBreedingRecordDetailUploadCount(isContinue, UPLOAD_STATUS_ERROR);
                }


            }

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

    /**
     * 错误数据上传
     */
    private void uploadErrorData() {
        uploadBaseArchivesError();
    }

    private void uploadBaseArchivesError() {

        QueryBuilder<CattleResumeEntity> builder =
                DbUtil.getInstance().getQueryBuilder(CattleResumeEntity.class)
                        .where(CattleResumeEntityDao.Properties.UploadStatus.eq(UPLOAD_STATUS_ERROR)).limit(1);
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<CattleResumeEntity>() {
            @Override
            public void onSuccess(List<CattleResumeEntity> result) {
                if (result != null && result.size() > 0) {

                    dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    ErrorEntity errorEntity = new ErrorEntity();
                    errorEntity.setDeptId(Long.parseLong(SPUtils.getInstance().getString(Configs.SP_DEPT_ID)));
                    errorEntity.setContent(new Gson().toJson(result.get(0)).toString());
                    errorEntity.setType("cattle_resume_error");
                    errorEntity.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
                    errorEntity.setCreateTime(dateFormat.format(new Date()));

                    RequestBody body = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(errorEntity));

                    addSubscribe(model.uploadErrorData(body)
                            .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                            .compose(RxUtils.schedulersTransformer())
                            .compose(RxUtils.exceptionTransformer())
//                            .doOnSubscribe(disposable -> showDialog("正在上传-错误数据..."))
                            .subscribe((Consumer<CollectResponse>) response -> {

                                if (response.getCode() == 0) {

                                    DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                        @Override
                                        public void onNotification(boolean result) {
                                            if (result) {
                                                uploadBaseArchivesError();
                                            } else {
                                                uploadPerformanceError();
                                            }
                                        }
                                    }).deleteAsyncBatch(CattleResumeEntity.class, result);

                                } else if (response.getCode() == 401) {
                                    dismissDialog();
                                    Bundle bundle = new Bundle();
                                    bundle.putInt("loginType", 1);
                                    startActivity(LoginActivity.class, bundle);
                                    me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                                } else {
                                    me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                                    uploadPerformanceError();
                                }
                            }, (Consumer<ResponseThrowable>) throwable -> {
                                dismissDialog();
                                me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                            })
                    );

                } else {
                    uploadPerformanceError();
                }

            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("查询基础数据错误数据失败！");
                uploadPerformanceError();
            }
        }).queryAsyncAll(CattleResumeEntity.class, builder);
    }

    private void uploadPerformanceError() {

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

                    dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    ErrorEntity errorEntity = new ErrorEntity();
                    errorEntity.setDeptId(Long.parseLong(SPUtils.getInstance().getString(Configs.SP_DEPT_ID)));
                    errorEntity.setContent(new Gson().toJson(result.get(0)).toString());
                    errorEntity.setType("performance_error");
                    errorEntity.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
                    errorEntity.setCreateTime(dateFormat.format(new Date()));

                    RequestBody body = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(errorEntity));

                    addSubscribe(model.uploadErrorData(body)
                                    .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                                    .compose(RxUtils.schedulersTransformer())
                                    .compose(RxUtils.exceptionTransformer())
//                            .doOnSubscribe(disposable -> showDialog("正在上传-错误数据..."))
                                    .subscribe((Consumer<CollectResponse>) response -> {

                                        if (response.getCode() == 0) {

                                            DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                                @Override
                                                public void onNotification(boolean result) {
                                                    if (result) {
                                                        uploadPerformanceError();
                                                    } else {
                                                        uploadWeightManError();
                                                    }
                                                }
                                            }).deleteAsyncBatch(PerformanceEntity.class, result);

                                        } else if (response.getCode() == 401) {
                                            dismissDialog();
                                            Bundle bundle = new Bundle();
                                            bundle.putInt("loginType", 1);
                                            startActivity(LoginActivity.class, bundle);
                                            me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                                        } else {
                                            me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                                            uploadWeightManError();
                                        }
                                    }, (Consumer<ResponseThrowable>) throwable -> {
                                        dismissDialog();
                                        me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                                    })
                    );

                } else {
                    uploadWeightManError();
                }

            }

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

    }

    private void uploadWeightManError() {

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

                    dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    ErrorEntity errorEntity = new ErrorEntity();
                    errorEntity.setDeptId(Long.parseLong(SPUtils.getInstance().getString(Configs.SP_DEPT_ID)));
                    errorEntity.setContent(new Gson().toJson(result.get(0)).toString());
                    errorEntity.setType("weightman_error");
                    errorEntity.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
                    errorEntity.setCreateTime(dateFormat.format(new Date()));

                    RequestBody body = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(errorEntity));

                    addSubscribe(model.uploadErrorData(body)
                                    .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                                    .compose(RxUtils.schedulersTransformer())
                                    .compose(RxUtils.exceptionTransformer())
//                            .doOnSubscribe(disposable -> showDialog("正在上传-错误数据..."))
                                    .subscribe((Consumer<CollectResponse>) response -> {

                                        if (response.getCode() == 0) {

                                            DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                                @Override
                                                public void onNotification(boolean result) {
                                                    if (result) {
                                                        uploadWeightManError();
                                                    } else {
                                                        uploadMedicalRecordError();
                                                    }
                                                }
                                            }).deleteAsyncBatch(WeightManEntity.class, result);

                                        } else if (response.getCode() == 401) {
                                            dismissDialog();
                                            Bundle bundle = new Bundle();
                                            bundle.putInt("loginType", 1);
                                            startActivity(LoginActivity.class, bundle);
                                            me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                                        } else {
                                            me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                                            uploadMedicalRecordError();
                                        }
                                    }, (Consumer<ResponseThrowable>) throwable -> {
                                        dismissDialog();
                                        me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                                    })
                    );

                } else {
                    uploadMedicalRecordError();
                }

            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("查询称重错误数据失败！");
                uploadMedicalRecordError();
            }
        }).queryAsyncAll(WeightManEntity.class, builder);
    }

    private void uploadMedicalRecordError() {

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

                    dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    ErrorEntity errorEntity = new ErrorEntity();
                    errorEntity.setDeptId(Long.parseLong(SPUtils.getInstance().getString(Configs.SP_DEPT_ID)));
                    errorEntity.setContent(new Gson().toJson(result.get(0)).toString());
                    errorEntity.setType("medical_record_error");
                    errorEntity.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
                    errorEntity.setCreateTime(dateFormat.format(new Date()));

                    RequestBody body = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(errorEntity));

                    addSubscribe(model.uploadErrorData(body)
                                    .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                                    .compose(RxUtils.schedulersTransformer())
                                    .compose(RxUtils.exceptionTransformer())
//                            .doOnSubscribe(disposable -> showDialog("正在上传-错误数据..."))
                                    .subscribe((Consumer<CollectResponse>) response -> {

                                        if (response.getCode() == 0) {

                                            DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                                @Override
                                                public void onNotification(boolean result) {
                                                    if (result) {
                                                        uploadMedicalRecordError();
                                                    } else {
                                                        uploadImmuneBatchError();
                                                    }
                                                }
                                            }).deleteAsyncBatch(MedicalRecordEntity.class, result);

                                        } else if (response.getCode() == 401) {
                                            dismissDialog();
                                            Bundle bundle = new Bundle();
                                            bundle.putInt("loginType", 1);
                                            startActivity(LoginActivity.class, bundle);
                                            me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                                        } else {
                                            me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                                            uploadImmuneBatchError();
                                        }
                                    }, (Consumer<ResponseThrowable>) throwable -> {
                                        dismissDialog();
                                        me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                                    })
                    );

                } else {
                    uploadImmuneBatchError();
                }

            }

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


    }

    private void uploadImmuneBatchError() {

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

                    dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    ErrorEntity errorEntity = new ErrorEntity();
                    errorEntity.setDeptId(Long.parseLong(SPUtils.getInstance().getString(Configs.SP_DEPT_ID)));
                    errorEntity.setContent(new Gson().toJson(result.get(0)).toString());
                    errorEntity.setType("immune_batch_error");
                    errorEntity.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
                    errorEntity.setCreateTime(dateFormat.format(new Date()));

                    RequestBody body = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(errorEntity));

                    addSubscribe(model.uploadErrorData(body)
                                    .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                                    .compose(RxUtils.schedulersTransformer())
                                    .compose(RxUtils.exceptionTransformer())
//                            .doOnSubscribe(disposable -> showDialog("正在上传-错误数据..."))
                                    .subscribe((Consumer<CollectResponse>) response -> {

                                        if (response.getCode() == 0) {

                                            DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                                @Override
                                                public void onNotification(boolean result) {
                                                    if (result) {
                                                        uploadImmuneBatchError();
                                                    } else {
                                                        uploadImmuneBatchDetailError();
                                                    }
                                                }
                                            }).deleteAsyncBatch(ImmuneBatchEntity.class, result);

                                        } else if (response.getCode() == 401) {
                                            dismissDialog();
                                            Bundle bundle = new Bundle();
                                            bundle.putInt("loginType", 1);
                                            startActivity(LoginActivity.class, bundle);
                                            me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                                        } else {
                                            me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                                            uploadImmuneBatchDetailError();
                                        }
                                    }, (Consumer<ResponseThrowable>) throwable -> {
                                        dismissDialog();
                                        me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                                    })
                    );

                } else {
                    uploadImmuneBatchDetailError();
                }

            }

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


    }


    private void uploadImmuneBatchDetailError() {

        QueryBuilder<ImmuneBatchDetailEntity> builder =
                DbUtil.getInstance().getQueryBuilder(ImmuneBatchDetailEntity.class)
                        .where(ImmuneBatchDetailEntityDao.Properties.UploadStatus.eq(UPLOAD_STATUS_ERROR)).limit(1);
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<ImmuneBatchDetailEntity>() {
            @Override
            public void onSuccess(List<ImmuneBatchDetailEntity> result) {
                if (result != null && result.size() > 0) {

                    dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    ErrorEntity errorEntity = new ErrorEntity();
                    errorEntity.setDeptId(Long.parseLong(SPUtils.getInstance().getString(Configs.SP_DEPT_ID)));
                    errorEntity.setContent(new Gson().toJson(result.get(0)).toString());
                    errorEntity.setType("immune_batch_detail_error");
                    errorEntity.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
                    errorEntity.setCreateTime(dateFormat.format(new Date()));

                    RequestBody body = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(errorEntity));

                    addSubscribe(model.uploadErrorData(body)
                                    .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                                    .compose(RxUtils.schedulersTransformer())
                                    .compose(RxUtils.exceptionTransformer())
//                            .doOnSubscribe(disposable -> showDialog("正在上传-错误数据..."))
                                    .subscribe((Consumer<CollectResponse>) response -> {

                                        if (response.getCode() == 0) {

                                            DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                                @Override
                                                public void onNotification(boolean result) {
                                                    if (result) {
                                                        uploadImmuneBatchDetailError();
                                                    } else {
                                                        uploadBreedingRecordError();
                                                    }
                                                }
                                            }).deleteAsyncBatch(ImmuneBatchDetailEntity.class, result);

                                        } else if (response.getCode() == 401) {
                                            dismissDialog();
                                            Bundle bundle = new Bundle();
                                            bundle.putInt("loginType", 1);
                                            startActivity(LoginActivity.class, bundle);
                                            me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                                        } else {
                                            me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                                            uploadBreedingRecordError();
                                        }
                                    }, (Consumer<ResponseThrowable>) throwable -> {
                                        dismissDialog();
                                        me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                                    })
                    );

                } else {
                    uploadBreedingRecordError();
                }

            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("查询免疫记录-子表错误数据失败！");
                uploadBreedingRecordError();
            }
        }).queryAsyncAll(ImmuneBatchDetailEntity.class, builder);


    }

    private void uploadBreedingRecordError() {

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

                    dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    ErrorEntity errorEntity = new ErrorEntity();
                    errorEntity.setDeptId(Long.parseLong(SPUtils.getInstance().getString(Configs.SP_DEPT_ID)));
                    errorEntity.setContent(new Gson().toJson(result.get(0)).toString());
                    errorEntity.setType("breeding_record_error");
                    errorEntity.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
                    errorEntity.setCreateTime(dateFormat.format(new Date()));

                    RequestBody body = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(errorEntity));

                    addSubscribe(model.uploadErrorData(body)
                                    .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                                    .compose(RxUtils.schedulersTransformer())
                                    .compose(RxUtils.exceptionTransformer())
//                            .doOnSubscribe(disposable -> showDialog("正在上传-错误数据..."))
                                    .subscribe((Consumer<CollectResponse>) response -> {

                                        if (response.getCode() == 0) {

                                            DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                                @Override
                                                public void onNotification(boolean result) {
                                                    if (result) {
                                                        uploadBreedingRecordError();
                                                    } else {
                                                        uploadBreedingRecordDetailError();
                                                    }
                                                }
                                            }).deleteAsyncBatch(BreedingRecordEntity.class, result);

                                        } else if (response.getCode() == 401) {
                                            dismissDialog();
                                            Bundle bundle = new Bundle();
                                            bundle.putInt("loginType", 1);
                                            startActivity(LoginActivity.class, bundle);
                                            me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                                        } else {
                                            me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                                            uploadBreedingRecordDetailError();
                                        }
                                    }, (Consumer<ResponseThrowable>) throwable -> {
                                        dismissDialog();
                                        me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                                    })
                    );

                } else {
                    uploadBreedingRecordDetailError();
                }

            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("查询配种记录错误数据失败！");
                uploadBreedingRecordDetailError();
            }
        }).queryAsyncAll(BreedingRecordEntity.class, builder);


    }

    private void uploadBreedingRecordDetailError() {

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

                    dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    ErrorEntity errorEntity = new ErrorEntity();
                    errorEntity.setDeptId(Long.parseLong(SPUtils.getInstance().getString(Configs.SP_DEPT_ID)));
                    errorEntity.setContent(new Gson().toJson(result.get(0)).toString());
                    errorEntity.setType("breeding_record_detail_error");
                    errorEntity.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
                    errorEntity.setCreateTime(dateFormat.format(new Date()));

                    RequestBody body = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(errorEntity));

                    addSubscribe(model.uploadErrorData(body)
                                    .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                                    .compose(RxUtils.schedulersTransformer())
                                    .compose(RxUtils.exceptionTransformer())
//                            .doOnSubscribe(disposable -> showDialog("正在上传-错误数据..."))
                                    .subscribe((Consumer<CollectResponse>) response -> {

                                        if (response.getCode() == 0) {

                                            DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                                @Override
                                                public void onNotification(boolean result) {
                                                    if (result) {
                                                        uploadBreedingRecordDetailError();
                                                    } else {
                                                        dismissDialog();
                                                        queryCattleResumeUploadCount(true, UPLOAD_STATUS_HAVE_NOT);
                                                    }
                                                }
                                            }).deleteAsyncBatch(BreedingRecordDetailEntity.class, result);

                                        } else if (response.getCode() == 401) {
                                            dismissDialog();
                                            Bundle bundle = new Bundle();
                                            bundle.putInt("loginType", 1);
                                            startActivity(LoginActivity.class, bundle);
                                            me.goldze.mvvmhabit.utils.ToastUtils.showShort("登录过期，请重新登录");
                                        } else {
                                            me.goldze.mvvmhabit.utils.ToastUtils.showShort("服务器:" + response.getMsg());
                                            dismissDialog();
                                            queryCattleResumeUploadCount(true, UPLOAD_STATUS_HAVE_NOT);
                                        }
                                    }, (Consumer<ResponseThrowable>) throwable -> {
                                        dismissDialog();
                                        me.goldze.mvvmhabit.utils.ToastUtils.showShort(throwable.message);
                                    })
                    );

                } else {
                    dismissDialog();
                    queryCattleResumeUploadCount(true, UPLOAD_STATUS_HAVE_NOT);
                }

            }

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


    }

}
