package com.phlx.wool.ui.sync.vm;

import android.app.Application;
import android.view.View;

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

import com.google.gson.GsonBuilder;
import com.phlx.wool.Configs;
import com.phlx.wool.data.Repository;
import com.phlx.wool.db.DbUtil;
import com.phlx.wool.db.interf.DbIDUCallBack;
import com.phlx.wool.db.interf.DbQueryCallBack;
import com.phlx.wool.entity.Harmless;
import com.phlx.wool.entity.HarmlessDao;
import com.phlx.wool.entity.HarmlessDetail;
import com.phlx.wool.entity.HarmlessDetailDao;
import com.phlx.wool.entity.Marking;
import com.phlx.wool.entity.MarkingDao;
import com.phlx.wool.entity.Quarantine;
import com.phlx.wool.entity.QuarantineDao;
import com.phlx.wool.entity.QuarantineDetail;
import com.phlx.wool.entity.QuarantineDetailDao;
import com.phlx.wool.params.CattleResponse;
import com.phlx.wool.params.UploadParams;
import com.phlx.wool.ui.base.BackBarVM;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.binding.command.BindingConsumer;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * <pre>
 *     author : lei
 *     e-mail : 18600395998@163.com
 *     time   : 2020/04/29
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class UploadVM extends BackBarVM<Repository> {

    public ObservableField<Boolean> isUploadMarking = new ObservableField<Boolean>(false);
    public ObservableField<Boolean> isUploadHarmless = new ObservableField<Boolean>(false);
    public ObservableField<Boolean> isUploadQuarantine = new ObservableField<Boolean>(false);
    public ObservableField<Boolean> isUploadAll = new ObservableField<Boolean>(false);
    public ObservableInt uploadDataVisibility = new ObservableInt();

    public UploadVM(@NonNull Application application, Repository repository) {
        super(application, repository);
        if (Configs.isOnLine) {
            uploadDataVisibility.set(View.VISIBLE);
        }else {
            uploadDataVisibility.set(View.GONE);
        }
    }

    //初始化ToolBar
    public void initToolbar() {
        setBackTitleText("上传");
    }

    public BindingCommand<Boolean> onUploadMarkingCommand =
            new BindingCommand<>(new BindingConsumer<Boolean>() {
                @Override
                public void call(Boolean isChecked) {
                    isUploadMarking.set(isChecked);
                }
            });

    public BindingCommand<Boolean> onUploadHarmlessCommand =
            new BindingCommand<>(new BindingConsumer<Boolean>() {
                @Override
                public void call(Boolean isChecked) {
                    isUploadHarmless.set(isChecked);
                }
            });

    public BindingCommand<Boolean> onUploadQuarantineCommand =
            new BindingCommand<>(new BindingConsumer<Boolean>() {
                @Override
                public void call(Boolean isChecked) {
                    isUploadQuarantine.set(isChecked);
                }
            });

    public BindingCommand<Boolean> onUploadAllCommand =
            new BindingCommand<>(new BindingConsumer<Boolean>() {
                @Override
                public void call(Boolean isChecked) {
                    isUploadAll.set(isChecked);
                    isAllSelected(isChecked);
                }
            });

    private void isAllSelected(boolean isSelected) {
        isUploadMarking.set(isSelected);
        isUploadHarmless.set(isSelected);
        isUploadQuarantine.set(isSelected);
    }

    public BindingCommand onUploadClickCommand = new BindingCommand(() -> {
        if (isUploadMarking.get()) {
            QueryBuilder<Marking> builder =
                    DbUtil.getInstance().getQueryBuilder(Marking.class).
                            where(MarkingDao.Properties.Status.eq("1"));
            DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<Marking>() {
                @Override
                public void onSuccess(List<Marking> result) {
                    if (result != null && result.size() > 0) {
                        uploadMarking(result);
                    }
                }

                @Override
                public void onFailed() {
                }
            }).queryAsyncAll(Marking.class, builder);
        } else if (isUploadQuarantine.get()) {
            uploadQuarantine();
        } else if (isUploadHarmless.get()){
            uploadHarmless();
        }else {
            ToastUtils.showShort("请选择上传的项目");
        }
    });

    private void uploadMarking(List<Marking> markingList) {
        String postInfoStr =
                new GsonBuilder().serializeNulls().excludeFieldsWithoutExposeAnnotation().create().toJson(new UploadParams<List<Marking>>(markingList));
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                postInfoStr);
        KLog.e(postInfoStr);
        addSubscribe(model.submitMarking(body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(disposable -> showDialog("正在上传数据..."))
                .subscribe((Consumer<CattleResponse<List<Marking>>>) response -> {
                    KLog.e(response.getCode() + response.getMsg());
                    if (response.getCode() == 0) {
                        for (int i = 0; i < markingList.size(); i++) {
                            markingList.get(i).setStatus(0);
                        }
                        DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                            @Override
                            public void onNotification(boolean result) {
                                if (result) {
                                    dismissDialog();
                                    if (isUploadQuarantine.get()) {
                                        uploadQuarantine();
                                    } else if (isUploadHarmless.get()) {

                                    }
                                }
                            }
                        }).deleteAsyncBatch(Marking.class, markingList);
                    } else {
                        dismissDialog();
                        ToastUtils.showShort("上传失败");
                    }
                }, (Consumer<ResponseThrowable>) throwable -> {
                    dismissDialog();
                    ToastUtils.showShort(throwable.message);
                })
        );
    }


    /**
     * 上传检疫数据
     */
    private void uploadQuarantine() {
        QueryBuilder<Quarantine> builder =
                DbUtil.getInstance().getQueryBuilder(Quarantine.class).
                        where(QuarantineDao.Properties.Status.eq("1"));
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<Quarantine>() {
            @Override
            public void onSuccess(List<Quarantine> result) {
                if (result != null && result.size() > 0) {
                    KLog.e(result.toString());
                    for (Quarantine quarantine : result) {
                        if (quarantine.getList() != null && quarantine.getList().size() > 0) {
                            quarantine.setList(null);
                        }
                        QueryBuilder<QuarantineDetail> builder =
                                DbUtil.getInstance().getQueryBuilder(QuarantineDetail.class).
                                        where(QuarantineDetailDao.Properties.QuarantineId.eq(quarantine.getId()));
                        List<QuarantineDetail> quarantineDetails =
                                DbUtil.getInstance().queryAll(QuarantineDetail.class, builder);
                        quarantine.setList(quarantineDetails);
                    }
                    KLog.e(result.toString());
                    String postInfoStr =
                            new GsonBuilder().serializeNulls().excludeFieldsWithoutExposeAnnotation().create().toJson(new UploadParams<List<Quarantine>>(result));
                    RequestBody body = RequestBody.create(MediaType.parse("application/json; " +
                                    "charset=utf-8"),
                            postInfoStr);
                    KLog.e(postInfoStr);
                    addSubscribe(model.submitQuarantine(body)
                            .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                            .compose(RxUtils.schedulersTransformer())
                            .compose(RxUtils.exceptionTransformer())
                            .doOnSubscribe(disposable -> showDialog("正在上传检疫数据..."))
                            .subscribe((Consumer<CattleResponse<List<Quarantine>>>) response -> {
                                KLog.e(response.getCode() + response.getMsg());
                                dismissDialog();
                                if (response.getCode() == 0) {
                                    DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                        @Override
                                        public void onNotification(boolean result) {
                                            if (result) {
                                                DbUtil.getInstance().deleteAll(QuarantineDetail.class);
                                                if (isUploadHarmless.get()) {
                                                    uploadHarmless();
                                                }
                                            }
                                        }
                                    }).deleteAsyncBatch(Quarantine.class, result);


                                } else {
                                    ToastUtils.showShort("上传失败");
                                }
                            }, (Consumer<ResponseThrowable>) throwable -> {
                                dismissDialog();
                                ToastUtils.showShort(throwable.message);
                            })
                    );
                }
            }

            @Override
            public void onFailed() {

            }
        }).queryAsyncAll(Quarantine.class, builder);
    }


    /**
     * 上传数据
     */
    private void uploadHarmless() {
        QueryBuilder<Harmless> builder =
                DbUtil.getInstance().getQueryBuilder(Harmless.class).
                        where(HarmlessDao.Properties.Status.eq("1"));
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<Harmless>() {
            @Override
            public void onSuccess(List<Harmless> result) {
                if (result != null && result.size() > 0) {
                    KLog.e(result.toString());
                    for (Harmless harmless : result) {
                        if (harmless.getList() != null && harmless.getList().size() > 0) {
                            harmless.setList(null);
                        }
                        QueryBuilder<HarmlessDetail> builder =
                                DbUtil.getInstance().getQueryBuilder(HarmlessDetail.class).
                                        where(HarmlessDetailDao.Properties.HarmlessId.eq(harmless.getId()));
                        List<HarmlessDetail> harmlessDetails =
                                DbUtil.getInstance().queryAll(HarmlessDetail.class, builder);
                        harmless.setList(harmlessDetails);
                    }
                    KLog.e(result.toString());
                    String postInfoStr =
                            new GsonBuilder().serializeNulls().excludeFieldsWithoutExposeAnnotation().create().toJson(new UploadParams<List<Harmless>>(result));
                    RequestBody body = RequestBody.create(MediaType.parse("application/json; " +
                                    "charset=utf-8"),
                            postInfoStr);
                    KLog.e(postInfoStr);
                    addSubscribe(model.submitHarmless(body)
                            .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                            .compose(RxUtils.schedulersTransformer())
                            .compose(RxUtils.exceptionTransformer())
                            .doOnSubscribe(disposable -> showDialog("正在上传检疫数据..."))
                            .subscribe((Consumer<CattleResponse<List<Harmless>>>) response -> {
                                KLog.e(response.getCode() + response.getMsg());
                                dismissDialog();
                                if (response.getCode() == 0) {
                                    DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                        @Override
                                        public void onNotification(boolean result) {
                                            if (result) {
                                                DbUtil.getInstance().deleteAll(HarmlessDetail.class);
                                            }
                                        }
                                    }).deleteAsyncBatch(Harmless.class, result);


                                } else {
                                    ToastUtils.showShort("上传失败");
                                }
                            }, (Consumer<ResponseThrowable>) throwable -> {
                                dismissDialog();
                                ToastUtils.showShort(throwable.message);
                            })
                    );
                }
            }

            @Override
            public void onFailed() {

            }
        }).queryAsyncAll(Harmless.class, builder);
    }

}
