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

import android.app.Application;

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

import com.google.gson.Gson;
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.AncestryinfoEntity;
import com.phlx.wool.entity.CattleLabelEntity;
import com.phlx.wool.entity.Unit;
import com.phlx.wool.params.CattleResponse;
import com.phlx.wool.params.PostParams;
import com.phlx.wool.ui.base.BackBarVM;
import com.phlx.wool.ui.cattle.activity.CattleMarkActivity;
import com.phlx.wool.ui.cattle.activity.CattleUploadActivity;
import com.phlx.wool.ui.cattle.farmer.FarmerEntity;
import com.phlx.wool.ui.work.unit.UnitActivity;

import org.greenrobot.greendao.query.WhereCondition;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;

import io.reactivex.functions.Consumer;
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 me.goldze.mvvmhabit.utils.ToastUtils;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class CattleMainVM extends BackBarVM<Repository> {

    private static String unitSp;
    public SingleLiveEvent<Boolean> nullEvent = new SingleLiveEvent<>();

    private int farmerPageIndex = 0;
    private int ancestryPageIndex = 0;

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

    /**
     * 选择养殖户
     */
    public BindingCommand onFarmerClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startActivity(UnitActivity.class);
        }
    });


    /**
     * 打标
     */
    public BindingCommand onLabelClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            unitSp = SPUtils.getInstance().getString(Configs.SP_UNIT_NAME, "");
            if (unitSp.isEmpty()) {
                nullEvent.call();
            } else {
                startActivity(CattleMarkActivity.class);
            }
        }
    });

    /**
     * 上传
     */
    public BindingCommand onUploadClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startActivity(CattleUploadActivity.class);
        }
    });

    /**
     * 下载更新养殖户信息
     */
    public BindingCommand onDownloadClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
//            if (Configs.isOnLine) {
                DbUtil.getInstance().deleteAll(Unit.class);
                farmerPageIndex = 0;
                queryFarmerInputTime(farmerPageIndex, 10000);
//            }
        }
    });

    @Override
    public void onResume() {
        super.onResume();

        if (SPUtils.getInstance().getBoolean("isFirst", true)) {
            queryFarmerInputTime(farmerPageIndex, 10000);
        }
    }

    public void queryFarmerInputTime(int index, int count) {
        String sql = "TIMESTAMP IN " + "(SELECT MAX(TIMESTAMP) FROM UNIT)";
        WhereCondition.StringCondition stringCondition = new WhereCondition.StringCondition(sql);
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<Unit>() {
            @Override
            public void onSuccess(List<Unit> result) {
                long inputTime = 0;
                if (result != null && result.size() > 0) {
                    inputTime = result.get(0).getTimestamp();
                }
                requestFarmer(index, inputTime, count);
            }

            @Override
            public void onFailed() {

            }
        }).queryAsync(Unit.class, stringCondition);
    }

    private void requestFarmer(int index, long inputTime, int count) {

        PostParams postParams = new PostParams();
        postParams.setInputTime(inputTime);
        postParams.setPageNum(index);
        postParams.setPageSize(count);
        postParams.setYears("");
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                new Gson().toJson(postParams));
        KLog.e("--Farmer--" + postParams.toString());

        showDialog("正在同步养殖户数据，请勿关闭屏幕或退出程序!");
        addSubscribe(model.getCattleFarmerList(body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(disposable -> {
                })
                .subscribe((Consumer<CattleResponse<List<FarmerEntity>>>) response -> {

                    dismissDialog();
                    if (response.getCode() == 0) {
                        if (response.getData() != null && response.getData().size() > 0) {
                            KLog.e("--Farmer--" + response.getData().size());
                            List<Unit> units = new ArrayList<>();
                            for (FarmerEntity fe : response.getData()) {
                                if (fe.getDelFlag().equals("0")) {
                                    Unit _unit = new Unit();
                                    _unit.setId(Long.parseLong(fe.getId()));
                                    _unit.setIdCard(fe.getPastureUnitIdcard());
                                    _unit.setManagerCode(fe.getPastureUnitId());
                                    _unit.setManagerName(fe.getPastureUnitName());
                                    _unit.setManagerPhone(fe.getManagerPhone());
                                    _unit.setTimestamp(Long.parseLong(fe.getInputTime()));
                                    units.add(_unit);
                                }
                            }
                            DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                @Override
                                public void onNotification(boolean result) {
                                    if (result) {
                                        SPUtils.getInstance().put("isFirst", false);
                                        farmerPageIndex++;
                                        requestFarmer(farmerPageIndex, inputTime, count);
                                    }
                                }
                            }).insertAsyncBatch(Unit.class, units);

                        } else {
                            requestAncestryinfo();
                        }

                    } else {
                        ToastUtils.showShort("服务器:" + response.getMsg());
                    }
                }, (Consumer<ResponseThrowable>) throwable -> {
                    dismissDialog();
                    KLog.e(throwable.message);
                    ToastUtils.showShort("养殖户同步数据失败");
                })
        );

    }


    private void requestAncestryinfo() {

        PostParams postParams = new PostParams();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                new Gson().toJson(postParams));
        KLog.e("--Ancestryinfo--" + postParams.toString());

        showDialog("正在同步牲畜品种数据，请勿关闭屏幕或退出程序!");
        addSubscribe(model.getCattleAncestryinfoList(body)
                        .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                        .compose(RxUtils.schedulersTransformer())
                        .compose(RxUtils.exceptionTransformer())
                        .doOnSubscribe(disposable -> {
                        })
                        .subscribe((Consumer<CattleResponse<List<AncestryinfoEntity>>>) response -> {

                            dismissDialog();
                            if (response.getCode() == 0) {
                                if (response.getData() != null && response.getData().size() > 0) {
                                    KLog.e("--Ancestryinfo--" + response.getData().size());
                                    DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                        @Override
                                        public void onNotification(boolean result) {
                                            if (result) {
                                                ToastUtils.showShort("牲畜品种数据保存成功" );
                                            }else{
                                                ToastUtils.showShort("牲畜品种数据保存失败" );
                                            }
                                        }
                                    }).insertAsyncBatch(AncestryinfoEntity.class, response.getData());

                                }
//                        else {
//                            dismissDialog();
//                        }

                            } else {
                                ToastUtils.showShort("服务器:" + response.getMsg());
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            dismissDialog();
                            KLog.e(throwable.message);
                            ToastUtils.showShort("牲畜品种同步数据失败");
                        })
        );

    }
}
