package com.phlx.wool.ui.work.unit;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProviders;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout;
import com.phlx.wool.BR;
import com.phlx.wool.Configs;
import com.phlx.wool.R;
import com.phlx.wool.data.VMFactory;
import com.phlx.wool.databinding.ActivityUnitBinding;
import com.phlx.wool.db.DbUtil;
import com.phlx.wool.db.interf.DbQueryCallBack;
import com.phlx.wool.entity.Unit;
import com.phlx.wool.entity.UnitDao;
import com.phlx.wool.ui.adapter.UnitAdapter;
import com.phlx.wool.ui.base.BaseActivity;
import com.phlx.wool.ui.search.SearchUnitFragment;
import com.phlx.wool.ui.search.interf.IOnUnitSearchClickListener;
import com.phlx.wool.util.RichTextUtil;
import com.phlx.wool.util.TextUtil;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * <pre>
 *     author : lei
 *     e-mail : 18600395998@163.com
 *     time   : 2020/04/29
 *     desc   : 选择养殖场
 *     version: 1.0
 * </pre>
 */
public class UnitActivity extends BaseActivity<ActivityUnitBinding, UnitVM> implements IOnUnitSearchClickListener {

    private UnitAdapter unitAdapter;
    private SearchUnitFragment searchUnitFragment;
    private Unit unitSelected;
    private String saveUnitName;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_unit;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    @Override
    public UnitVM initViewModel() {
        VMFactory factory = VMFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(UnitVM.class);
    }

    @Override
    public void initData() {
        super.initData();
        setSupportActionBar(binding.include.toolbar);
        viewModel.initToolbar();
        searchUnitFragment = SearchUnitFragment.newInstance();
        searchUnitFragment.setIOnUnitSearchClickListener(this);
        saveUnitName = SPUtils.getInstance().getString(Configs.SP_UNIT_NAME);
        if (TextUtil.isSpace(saveUnitName)) {
            binding.countGroup.setVisibility(View.GONE);
        } else {
            binding.countGroup.setVisibility(View.VISIBLE);
            binding.breedUnitTv.setText(saveUnitName);
        }
        ProgressLayout headerView = new ProgressLayout(this);
        binding.twinklingRefreshLayout.setHeaderView(headerView);
        unitAdapter = new UnitAdapter(this);
        binding.unitRv.setAdapter(unitAdapter);
        viewModel.loadUnit();
    }

    @Override
    public void initViewObservable() {

        viewModel.showSearch.observe(this, aBoolean -> {
            searchUnitFragment.showFragment(getSupportFragmentManager(), searchUnitFragment.TAG);
        });

        viewModel.selectItemLiveData.observe(this, unitItem -> {
            if (unitAdapter != null) {
                unitAdapter.setItemSel(unitItem.getPosition());
                unitSelected = unitItem.entity.get();
            }
        });
        //监听下拉刷新完成
        viewModel.finishRefreshing.observe(this, aBoolean -> {
            binding.twinklingRefreshLayout.finishRefreshing();
        });
        //监听上拉加载完成
        viewModel.finishLoadMore.observe(this, aBoolean -> {
            binding.twinklingRefreshLayout.finishLoadmore();
        });

        viewModel.btnLiveData.observe(this, aBoolean -> {
            if (TextUtil.isSpace(saveUnitName)) {
                saveUnit(unitSelected);
            } else {
                if (unitSelected == null) {
                    ToastUtils.showShort("请选择养殖场");
                } else {
                    String contentStr = "是否确定将养殖场 " + saveUnitName + " 更改为 " + unitSelected.getManagerName() + " 养殖场?";
                    String[] keyArray = {saveUnitName,unitSelected.getManagerName()};
                    showTip(RichTextUtil.matcherSearchTitle(new Integer(Color.RED),contentStr, keyArray));
                }
            }
        });


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (unitAdapter != null) {
            unitAdapter = null;
        }
        if (searchUnitFragment != null) {
            searchUnitFragment = null;
        }
    }

    @Override
    public void OnSearchClick(String keyword) {
        QueryBuilder<Unit> builder =
                DbUtil.getInstance().getQueryBuilder(Unit.class)
                        .whereOr(UnitDao.Properties.ManagerName.like("%" + keyword + "%"),
                                UnitDao.Properties.ManagerPhone.like(keyword + "%")
                                , UnitDao.Properties.ManagerCode.like(keyword + "%")
                                , UnitDao.Properties.IdCard.like("%" + keyword));
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<Unit>() {
            @Override
            public void onSuccess(List<Unit> result) {
                if (result != null && result.size() > 0) {
                    viewModel.showRv();
                    viewModel.setSearchList(result);
                    unitAdapter.setItemSel(-1);
                } else {
                    viewModel.showEmpty();
                    setEmptyTip(keyword);
                }
            }

            @Override
            public void onFailed() {

            }
        }).queryAsyncAll(Unit.class, builder);


    }

    @Override
    public void OnSelectedClick(Unit unit) {
        viewModel.setSearchResult(unit);
        unitAdapter.setItemSel(-1);
    }


    private void showTip(CharSequence content) {

        new MaterialDialog.Builder(this).title("系统信息").content(content)
                .cancelable(false).canceledOnTouchOutside(false)
                .positiveText("确定").negativeText("取消").onPositive(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (which == DialogAction.POSITIVE) {
                    saveUnit(unitSelected);
                    dialog.dismiss();
                }
            }
        }).show();
    }

    private void saveUnit(Unit unit) {
        SPUtils.getInstance().put(Configs.SP_UNIT_NAME,
                unit.getManagerName());
        SPUtils.getInstance().put(Configs.SP_UNIT_CODE,
                unit.getManagerCode());
        SPUtils.getInstance().put(Configs.SP_UNIT_PHONE,
                unit.getManagerPhone());
        SPUtils.getInstance().put(Configs.SP_UNIT_ID_CARD,
                unit.getIdCard());
        finish();
    }

    private void setEmptyTip(String tip) {
        if (tip != null) {
            String emptyStr = "找不到和您查询的 " + tip + " 相符的内容或信息\n\n" + "建议:\n\n" + "请检查输入字词有无错误\n\n"
                    + "请尝试其他查询词\n\n" + "请改用较常见的字词\n\n";
            binding.unitEmptyTv.setText(RichTextUtil.matcherSearchTitle(new Integer(Color.RED),
                    emptyStr, tip));
        }
    }
}
