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

import android.app.Application;

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

import com.google.gson.GsonBuilder;
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.CattleLabelEntity;
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.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;

public class CattleUploadVM extends BackBarVM<Repository> {

    public ObservableField<String> markingLabelNum = new ObservableField<>("补打记录");

    public CattleUploadVM(@NonNull Application application, Repository model) {
        super(application, model);
        refreshUploadCount();
    }

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

    public BindingCommand onUploadClickCommand = new BindingCommand(() -> {
        uploadMarking();
    });

    //查询每项未上传记录数量
    public void refreshUploadCount() {
        markingLabelNum.set("补打记录 " + "(" + DbUtil.getInstance().count(CattleLabelEntity.class) + ")");
    }

    private void uploadMarking() {

        QueryBuilder<CattleLabelEntity> builder =
                DbUtil.getInstance().getQueryBuilder(CattleLabelEntity.class).limit(20);
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<CattleLabelEntity>() {
            @Override
            public void onSuccess(List<CattleLabelEntity> result) {

                if (result != null && result.size() > 0) {
                    String postInfoStr =
                            new GsonBuilder().serializeNulls()
//                                    .excludeFieldsWithoutExposeAnnotation()
                                    .create().toJson(new UploadParams<List<CattleLabelEntity>>(result));
                    RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), postInfoStr);
                    KLog.e(postInfoStr);
                    addSubscribe(model.uploadCattleMark(body)
                            .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                            .compose(RxUtils.schedulersTransformer())
                            .compose(RxUtils.exceptionTransformer())
                            .doOnSubscribe(disposable -> showDialog("正在上传基础数据..."))
                            .subscribe((Consumer<CattleResponse<List<CattleLabelEntity>>>) response -> {
                                KLog.e(response.getCode() + response.getMsg());
                                if (response.getCode() == 0) {
                                        DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                            @Override
                                            public void onNotification(boolean result) {
                                                if (result) {
                                                    dismissDialog();
                                                    uploadMarking();
                                                } else {
                                                    ToastUtils.showShort("删除基础数据失败");
                                                }
                                            }
                                        }).deleteAsyncBatch(CattleLabelEntity.class, result);
                                } else {
                                    dismissDialog();
                                    ToastUtils.showShort("基础数据上传失败");
                                }
                            }, (Consumer<ResponseThrowable>) throwable -> {
                                dismissDialog();
                                ToastUtils.showShort(throwable.message);
                            })
                    );
                } else {
                    dismissDialog();
                    refreshUploadCount();
                }
            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("补打记录数据库查询失败");
            }
        }).queryAsyncAll(CattleLabelEntity.class, builder);


    }
}
