package com.phlx.wool.ui.splash;

import android.app.Application;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
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.Label;
import com.phlx.wool.entity.Unit;
import com.phlx.wool.entity.Veterinary;
import com.phlx.wool.params.BasicParams;
import com.phlx.wool.params.CattleResponse;
import com.phlx.wool.params.PostParams;
import com.phlx.wool.ui.base.MainBarVM;
import com.phlx.wool.ui.main.MainActivity;

import org.greenrobot.greendao.query.WhereCondition;

import java.util.List;

import io.reactivex.functions.Consumer;
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 SplashVM extends MainBarVM<Repository> {

    public SingleLiveEvent<String> errorEvent = new SingleLiveEvent<>();

    private int labelPageIndex = 0;
    private int unitPageIndex = 0;

    public SplashVM(@NonNull Application application, Repository repository) {
        super(application, repository);
    }


    /**
     * 获取标签数据
     */
    public void requestLabel(int index, long inputTime, int count) {
        PostParams postParams = new PostParams();
        postParams.setInputTime(inputTime);
        postParams.setPageNum(index);
        postParams.setPageSize(count);
        postParams.setYears("2018");
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                new Gson().toJson(postParams));
        KLog.e("label", postParams.toString());
        addSubscribe(model.getLabelList(body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(disposable -> {
                })
                .subscribe((Consumer<CattleResponse<List<Label>>>) response -> {

                    if (response.getCode() == 0) {
                        if (response.getData() != null && response.getData().size() > 0) {
                            KLog.e(response.getData().size());
                            DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                @Override
                                public void onNotification(boolean result) {
                                    if (result) {
                                        labelPageIndex++;
                                        requestLabel(labelPageIndex, inputTime, count);
                                    }
                                }
                            }).insertAsyncBatch(Label.class, response.getData());
                        } else {
                            dismissDialog();
                            showDialog("正在同步数据，请勿关闭屏幕或退出程序!");
                            queryUnitInputTime(unitPageIndex, 100000);
                        }

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

    }


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

        PostParams postParams = new PostParams();
        postParams.setInputTime(inputTime);
        postParams.setPageNum(index);
        postParams.setPageSize(count);
        postParams.setYears("2018");
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                new Gson().toJson(postParams));
        KLog.e("--Unit--" + postParams.toString());
        addSubscribe(model.getUnitList(body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(disposable -> {
                })
                .subscribe((Consumer<CattleResponse<List<Unit>>>) response -> {

                    if (response.getCode() == 0) {
                        if (response.getData() != null && response.getData().size() > 0) {
                            KLog.e("--Unit--" + response.getData().size());
                            DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                @Override
                                public void onNotification(boolean result) {
                                    if (result) {
                                        unitPageIndex++;
                                        requestUnit(unitPageIndex, inputTime, count);
                                    }
                                }
                            }).insertAsyncBatch(Unit.class, response.getData());


                        } else {
                            dismissDialog();
                            showDialog("正在同步数据，请勿关闭屏幕或退出程序!");
                            requestVeterinary();
                        }

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

    }


    public void queryUnitInputTime(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();
                }
                requestUnit(index, inputTime, count);
            }

            @Override
            public void onFailed() {

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

    private void requestVeterinary() {
        PostParams postParams = new PostParams();
        postParams.setInputTime(0);
        postParams.setPageNum(1);
        postParams.setPageSize(200);
        postParams.setYears("2018");
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                new Gson().toJson(postParams));
        addSubscribe(model.getVeterinaryList(body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(disposable -> {
                })
                .subscribe((Consumer<CattleResponse<List<Veterinary>>>) response -> {
                    if (response.getCode() == 0) {
                        if (response.getData() != null && response.getData().size() > 0) {
                            KLog.e(response.getData().size());
                            DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                @Override
                                public void onNotification(boolean result) {
                                    if (result) {
                                        dismissDialog();
                                        showDialog("正在同步数据，请勿关闭屏幕或退出程序!");
                                        requestBasicInfo();
                                    }
                                }
                            }).insertAsyncBatch(Veterinary.class, response.getData());

                        } else {
                            dismissDialog();
                            errorEvent.setValue("缺少兽医基础数据，请联系管理员");
                        }

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

    private void requestBasicInfo() {
        PostParams postParams = new PostParams();
        postParams.setInputTime(0);
        postParams.setPageNum(1);
        postParams.setPageSize(200);
        postParams.setYears("2018");
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                new Gson().toJson(postParams));
        addSubscribe(model.getBasicInfo(body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(disposable -> {
                })
                .subscribe((Consumer<CattleResponse<BasicParams>>) response -> {
                    dismissDialog();
                    if (response.getCode() == 0) {
                        if (response.getData().getAncestryinfoList() != null && response.getData().getAncestryinfoList().size() > 0) {
                            model.saveVariety(response.getData().getAncestryinfoList());
                        }
                        if (response.getData().getInnocuitymanagewayinfoList() != null && response.getData().getInnocuitymanagewayinfoList().size() > 0) {
                            model.saveTreatmentMethod(response.getData().getInnocuitymanagewayinfoList());
                        }
                        SPUtils.getInstance().put("isFirst", false);
                        startActivity(MainActivity.class);
                        finish();
                    } else {
                        errorEvent.setValue("服务器 :" + response.getMsg());
                    }
                }, (Consumer<ResponseThrowable>) throwable -> {
                    dismissDialog();
                    KLog.e(throwable.message);
                    errorEvent.setValue("同步数据失败");
                })
        );
    }


}
