package com.phlx.anchorcollect.ui.splash;

import android.app.Application;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.phlx.anchorcollect.Configs;
import com.phlx.anchorcollect.data.Repository;
import com.phlx.anchorcollect.db.DbUtil;
import com.phlx.anchorcollect.db.gen.GenTableColumnDao;
import com.phlx.anchorcollect.db.gen.GenTableDao;
import com.phlx.anchorcollect.db.interf.DbIDUCallBack;
import com.phlx.anchorcollect.entity.DictEntity;
import com.phlx.anchorcollect.entity.GenData;
import com.phlx.anchorcollect.entity.GenTable;
import com.phlx.anchorcollect.entity.GenTableColumn;
import com.phlx.anchorcollect.params.CollectResponse;
import com.phlx.anchorcollect.params.ListResponse;
import com.phlx.anchorcollect.params.PostParams;
import com.phlx.anchorcollect.ui.base.MainBarVM;
import com.phlx.anchorcollect.ui.main.MainActivity;
import com.phlx.anchorcollect.util.StringUtil;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

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

public class SplashVM extends MainBarVM<Repository> {

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

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

    public int loginType;//登录后是否跳转， 0跳转main 1不跳转

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

    }

    public void requestDict() {

        addSubscribe(model.downloadDict()
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(disposable -> {
                })
                .subscribe((Consumer<ListResponse<DictEntity>>) response -> {

                    if (response.getCode() == 0) {
                        //清除之前的页面配置
                        DbUtil.getInstance().deleteAll(DictEntity.class);

                        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) {
                                        ToastUtils.showShort("字典项数据同步完成！");
                                    } else {
                                        errorEvent.setValue("保存字典项数据失败");
                                    }
                                }
                            }).insertAsyncBatch(DictEntity.class, response.getData());
                        } else {

                        }
                        requestGen();
                    } else {
                        errorEvent.setValue("同步字典项数据错误 :" + response.getMsg());
                    }
                }, (Consumer<ResponseThrowable>) throwable -> {
                    dismissDialog();
                    KLog.e(throwable.message);
                    errorEvent.setValue("同步字典项数据失败");
                })
        );

    }

    public void requestGen() {

        PostParams postParams = new PostParams();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(postParams));
        KLog.e("Gen", postParams.toString());
        addSubscribe(model.genGet()
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(disposable -> {
                })
                .subscribe((Consumer<CollectResponse<GenData>>) response -> {

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

                        //清除之前的页面配置
                        DbUtil.getInstance().deleteAll(GenTable.class);
                        DbUtil.getInstance().deleteAll(GenTableColumn.class);

                        if (response.getData().getGenTableColumns() != null && response.getData().getGenTables() != null) {
                            KLog.e(response.getData().getGenTables().size() + "|" + response.getData().getGenTableColumns().size());
                            DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                @Override
                                public void onNotification(boolean result) {
                                    if (result) {
                                        DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                            @Override
                                            public void onNotification(boolean result) {
                                                if (result) {
                                                    getGen();
                                                } else {
                                                    errorEvent.setValue("保存页面配置详情数据失败");
                                                }
                                            }
                                        }).insertAsyncBatch(GenTableColumn.class, response.getData().getGenTableColumns());
                                    } else {
                                        errorEvent.setValue("保存页面配置数据失败");
                                    }
                                }
                            }).insertAsyncBatch(GenTable.class, response.getData().getGenTables());
                        } else {
                            dismissDialog();
                        }
                    } else {
                        errorEvent.setValue("同步页面配置数据错误 :" + response.getMsg());
                    }
                }, (Consumer<ResponseThrowable>) throwable -> {
                    dismissDialog();
                    KLog.e(throwable.message);
                    errorEvent.setValue("同步页面配置数据失败");
                })
        );
    }

    private void getGen() {

        String roles = SPUtils.getInstance().getString(Configs.SP_ROLE_ID, "");
        QueryBuilder<GenTable> builder =
                DbUtil.getInstance().getQueryBuilder(GenTable.class)
                        .where(GenTableDao.Properties.RoleId.in(StringUtil.strToList(roles.split(","))));
        Set<GenTable> genList = new HashSet<>();
        genList.addAll(DbUtil.getInstance().queryAll(GenTable.class, builder));

        for (GenTable gt : genList) {

            /**
             * zxgl_cattleresume 基础信息
             * zxgl_performance 性能测定
             * zxgl_weight_man 称重管理
             * zxgl_medicalrecords 诊疗记录
             * zxgl_immunebatch 免疫记录
             * zxgl_cattlemating_master 配种记录主表
             * zxgl_cattlemating_detaill 配种记子表
             */
            switch (gt.getTableName()) {
                case "zxgl_cattleresume":
                    QueryBuilder<GenTableColumn> builderDetaile0 =
                            DbUtil.getInstance().getQueryBuilder(GenTableColumn.class)
                                    .where(GenTableColumnDao.Properties.TableId.eq(gt.getTableId())
                                            , GenTableColumnDao.Properties.IsQuery.eq("1"))
                                    .orderAsc(GenTableColumnDao.Properties.Sort);
                    Configs.cattleresume = DbUtil.getInstance().queryAll(GenTableColumn.class, builderDetaile0);
                    break;
                case "zxgl_performance":
                    QueryBuilder<GenTableColumn> builderDetaile1 =
                            DbUtil.getInstance().getQueryBuilder(GenTableColumn.class)
                                    .where(GenTableColumnDao.Properties.TableId.eq(gt.getTableId())
                                            , GenTableColumnDao.Properties.IsQuery.eq("1"))
                                    .orderAsc(GenTableColumnDao.Properties.Sort);
                    Configs.performance = DbUtil.getInstance().queryAll(GenTableColumn.class, builderDetaile1);
                    break;
                case "zxgl_weight_man":
                    QueryBuilder<GenTableColumn> builderDetaile2 =
                            DbUtil.getInstance().getQueryBuilder(GenTableColumn.class)
                                    .where(GenTableColumnDao.Properties.TableId.eq(gt.getTableId())
                                            , GenTableColumnDao.Properties.IsQuery.eq("1"))
                                    .orderAsc(GenTableColumnDao.Properties.Sort);
                    Configs.weightMan = DbUtil.getInstance().queryAll(GenTableColumn.class, builderDetaile2);
                    break;
                case "zxgl_medicalrecords":
                    QueryBuilder<GenTableColumn> builderDetaile3 =
                            DbUtil.getInstance().getQueryBuilder(GenTableColumn.class)
                                    .where(GenTableColumnDao.Properties.TableId.eq(gt.getTableId())
                                            , GenTableColumnDao.Properties.IsQuery.eq("1"))
                                    .orderAsc(GenTableColumnDao.Properties.Sort);
                    Configs.medicalrecords = DbUtil.getInstance().queryAll(GenTableColumn.class, builderDetaile3);
                    break;
                case "zxgl_immunebatch":
                    QueryBuilder<GenTableColumn> builderDetaile4 =
                            DbUtil.getInstance().getQueryBuilder(GenTableColumn.class)
                                    .where(GenTableColumnDao.Properties.TableId.eq(gt.getTableId())
                                            , GenTableColumnDao.Properties.IsQuery.eq("1"))
                                    .orderAsc(GenTableColumnDao.Properties.Sort);
                    Configs.immunebatch = DbUtil.getInstance().queryAll(GenTableColumn.class, builderDetaile4);
                    break;
                case "zxgl_cattlemating_master":
                    QueryBuilder<GenTableColumn> builderDetaile5 =
                            DbUtil.getInstance().getQueryBuilder(GenTableColumn.class)
                                    .where(GenTableColumnDao.Properties.TableId.eq(gt.getTableId())
                                            , GenTableColumnDao.Properties.IsQuery.eq("1"))
                                    .orderAsc(GenTableColumnDao.Properties.Sort);
                    Configs.cattlematingMaster = DbUtil.getInstance().queryAll(GenTableColumn.class, builderDetaile5);
                    //取主表列表表头
                    QueryBuilder<GenTableColumn> builderDetaile9 =
                            DbUtil.getInstance().getQueryBuilder(GenTableColumn.class)
                                    .where(GenTableColumnDao.Properties.TableId.eq(gt.getTableId())
                                            , GenTableColumnDao.Properties.IsList.eq("1")
                                    )
                                    .orderAsc(GenTableColumnDao.Properties.Sort);
                    Configs.cattlematingMasterList = DbUtil.getInstance().queryAll(GenTableColumn.class, builderDetaile9);
                    break;
                case "zxgl_cattlemating_detaill":
                    QueryBuilder<GenTableColumn> builderDetaile6 =
                            DbUtil.getInstance().getQueryBuilder(GenTableColumn.class)
                                    .where(GenTableColumnDao.Properties.TableId.eq(gt.getTableId())
                                            , GenTableColumnDao.Properties.IsQuery.eq("1")
                                    )
                                    .orderAsc(GenTableColumnDao.Properties.Sort);
                    Configs.cattlematingDetaill = DbUtil.getInstance().queryAll(GenTableColumn.class, builderDetaile6);
                    //取详情列表表头
                    QueryBuilder<GenTableColumn> builderDetaile7 =
                            DbUtil.getInstance().getQueryBuilder(GenTableColumn.class)
                                    .where(GenTableColumnDao.Properties.TableId.eq(gt.getTableId())
                                            , GenTableColumnDao.Properties.IsList.eq("1")
                                    )
                                    .orderAsc(GenTableColumnDao.Properties.Sort);
                    Configs.cattlematingDetaillList = DbUtil.getInstance().queryAll(GenTableColumn.class, builderDetaile7);
                    break;
            }

        }
        if (Configs.cattlematingMasterList == null) {
            Configs.cattlematingMasterList = new ArrayList<>();
        }
        if (Configs.cattlematingDetaillList != null)
            Configs.cattlematingMasterList.addAll(Configs.cattlematingDetaillList);

        dismissDialog();
        ToastUtils.showShort("页面配置详情数据更新完成！");
        SPUtils.getInstance().put("isFirst", false);
        if (loginType == 0)
            startActivity(MainActivity.class);
        finish();
    }

}
