package com.phlx.anchorcollect_p.ui.login;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.view.View;

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


import com.azhon.appupdate.utils.ApkUtil;
import com.phlx.anchorcollect_p.Configs;
import com.phlx.anchorcollect_p.data.Repository;
import com.phlx.anchorcollect_p.data.VMFactory;
import com.phlx.anchorcollect_p.db.DbUtil;
import com.phlx.anchorcollect_p.db.gen.GenTableColumnDao;
import com.phlx.anchorcollect_p.db.gen.GenTableDao;
import com.phlx.anchorcollect_p.entity.GenTable;
import com.phlx.anchorcollect_p.entity.GenTableColumn;
import com.phlx.anchorcollect_p.entity.LoginData;
import com.phlx.anchorcollect_p.entity.UserRoleEntity;
import com.phlx.anchorcollect_p.net.NetworkUtils;
import com.phlx.anchorcollect_p.params.BaseResponse;
import com.phlx.anchorcollect_p.params.CollectResponse;
import com.phlx.anchorcollect_p.ui.main.MainActivity;
import com.phlx.anchorcollect_p.ui.splash.SplashActivity;
import com.phlx.anchorcollect_p.util.StringUtil;
import com.phlx.anchorcollect_p.util.TextUtil;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseViewModel;
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;

public class LoginVM extends BaseViewModel<Repository> {

    //用户账号输入监听
    public ObservableField<String> userName = new ObservableField<>("");
    //用户密码输入监听
    public ObservableField<String> password = new ObservableField<>("");
    //用户账号EditText监听
    public ObservableInt clearBtnVisibility = new ObservableInt();
    //版本号
    public ObservableField<String> appVersion = new ObservableField<>("");
    //监听密码显隐
    public SingleLiveEvent<Boolean> pSwitchEvent = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> exitEvent = new SingleLiveEvent<>();
    //更新app
    public SingleLiveEvent<Integer> appUpdateEvent = new SingleLiveEvent<>();


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


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

        appVersion.set(ApkUtil.getVersionCode(getApplication()) + "");
//        从本地取得数据绑定到View层
        userName.set(model.getUserName());
        password.set(model.getPassword());

//        userName.set("zz");//正式测试 app
//        userName.set("test_app");//阿里云测试 app
//        password.set("123456");
    }

    //清除用户名的点击事件
    public BindingCommand clearUserNameOnClickCommand = new BindingCommand(() -> userName.set(""));
    //密码显示点击事件
    public BindingCommand passwordShowSwitchOnClickCommand =
            new BindingCommand(() -> {
                pSwitchEvent.setValue(pSwitchEvent.getValue() == null || !pSwitchEvent.getValue());
            });
    //用户名输入框焦点改变的回调事件
    public BindingCommand<Boolean> onFocusChangeCommand =
            new BindingCommand<>(hasFocus -> {
                if (hasFocus) {
                    clearBtnVisibility.set(View.VISIBLE);
                } else {
                    clearBtnVisibility.set(View.INVISIBLE);
                }
            });
    //离线,联机
    public BindingCommand<String> isOnlineCheckedChangeCommand = new BindingCommand<String>(s -> {
        if (s.equals("离线")) {
            Configs.isOnLine = false;
        } else if (s.equals("联机")) {
            Configs.isOnLine = true;
        }
    });
    //登录按钮的点击事件
    public BindingCommand loginOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (Configs.isOnLine) {
                login();
            } else {
                offLine();
            }
        }
    });

    //退出按钮的点击事件
    public BindingCommand loginOutClickCommand =
            new BindingCommand(() -> exitEvent.setValue(exitEvent.getValue() == null || !exitEvent.getValue()));


    /**
     * 登陆
     **/
    private void login() {
        if (checkPerson(userName.get(), password.get()))
            return;

        Map<String, String> loginParam = new HashMap<>();
        loginParam.put("username", userName.get());
        loginParam.put("password", password.get());

        addSubscribe(model.loginPost(loginParam)
                        .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                        .compose(RxUtils.schedulersTransformer())
                        .compose(RxUtils.exceptionTransformer())
                        .doOnSubscribe(disposable -> showDialog("正在登录..."))
                        .subscribe((Consumer<CollectResponse<LoginData>>) response -> {

                            dismissDialog();
                            KLog.e("login", response.toString());
                            if (response.getCode() == 0) {

                                //保存账号密码
                                model.saveUserName(userName.get());
                                model.savePassword(password.get());
                                if (response.getData() != null) {
                                    model.saveToken(response.getData().getToken());
//                            model.saveEmail(response.getData().getUser().getEmail());
//                            model.savePhone(response.getData().getUser().getPhonenumber());
//                            model.saveFrequencyConfig(response.getData().getUser().getFrequencyConfig());
//                            Configs.FREQUENCY_CONFIG = response.getData().getUser().getFrequencyConfig();
                                    SPUtils.getInstance().put(Configs.SP_ID, response.getData().getUser().getUserId());
                                    SPUtils.getInstance().put(Configs.SP_NAME, response.getData().getUser().getUserName());
                                    SPUtils.getInstance().put(Configs.SP_LOGIN_NAME, response.getData().getUser().getLoginName());
                                    SPUtils.getInstance().put(Configs.SP_DEPT_ID, response.getData().getUser().getDeptId());

                                    String roleIds = "";
                                    List<UserRoleEntity> roles = response.getData().getUser().getRoles();
                                    for (UserRoleEntity userRoleEntity : roles) {
                                        roleIds += userRoleEntity.getRoleId();
                                        roleIds += ",";
                                    }

                                    SPUtils.getInstance().put(Configs.SP_ROLE_ID, roleIds.substring(0, roleIds.length() - 1));
//                            SPUtils.getInstance().put(Configs.SP_FREQUENCY, response.getData().getUser().getFrequencyConfig());
                                }
                                VMFactory.getInstance(getApplication()).refreshRepository();
                                Bundle bundle = new Bundle();
                                bundle.putInt("loginType", loginType);
                                startActivity(SplashActivity.class, bundle);
                                finish();
                            } else {
                                ToastUtils.showShort("服务器:" + response.getMsg());
                            }
                        }, (Consumer<ResponseThrowable>) throwable -> {
                            dismissDialog();
                            ToastUtils.showShort(throwable.message);
                        })
        );

    }

    private boolean checkPerson(String name, String psd) {
        if (StringUtil.isSpace(name)) {
            ToastUtils.showShort("请输入账号！");
            return true;
        }
        if (StringUtil.isSpace(psd)) {
            ToastUtils.showShort("请输入密码！");
            return true;
        }
        return false;
    }


    /**
     * 离线登录
     */
    private void offLine() {
        //检测账号密码是否为空
        if (checkPerson(userName.get(), password.get()))
            return;
        //检测本地是否保存账号密码
        if (!TextUtil.isSpace(model.getUserName()) && !TextUtil.isSpace(model.getPassword())) {
            if (!model.getUserName().equals(userName.get())) {
                ToastUtils.showShort("账号错误");
                return;
            }
            if (!model.getUserName().equals(userName.get())) {
                ToastUtils.showShort("密码错误");
                return;
            }
            Configs.FREQUENCY_CONFIG = SPUtils.getInstance().getString(Configs.SP_FREQUENCY);
            getGen();
        } else {
            ToastUtils.showShort("请先联机登录");
        }

    }

    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"))
                                    .orderDesc(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);
                    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);
                    break;
            }

        }

        dismissDialog();
        ToastUtils.showShort("页面配置详情数据读取完成！");
        startActivity(MainActivity.class);
        finish();
    }

    /**
     * 判断网络，网络可用时连接服务器获取版本，不可用则忽略
     */
    public void requestVersion(Activity activity) {
        if (NetworkUtils.isAvailable(activity)) {

            addSubscribe(model.versionGet()
                    .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                    .compose(RxUtils.schedulersTransformer())
                    .compose(RxUtils.exceptionTransformer())
                    .doOnSubscribe(disposable -> showDialog("正在检测版本..."))
                    .subscribe((Consumer<BaseResponse<Double>>) response -> {
                        dismissDialog();
                        if (response.getCode() == 0) {
                            appUpdateEvent.setValue(response.getData().intValue());
                        }
                    }, (Consumer<ResponseThrowable>) throwable -> {
                        dismissDialog();
                        ToastUtils.showShort(throwable.message);
                    })
            );
        }

    }

}
