package com.phlx.anchorcollect.ui.fragment.vm;

import android.app.Application;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;

import com.phlx.anchorcollect.BR;
import com.phlx.anchorcollect.Configs;
import com.phlx.anchorcollect.R;
import com.phlx.anchorcollect.data.Repository;
import com.phlx.anchorcollect.db.DbUtil;
import com.phlx.anchorcollect.db.gen.CardEntityDao;
import com.phlx.anchorcollect.db.gen.CattleResumeEntityDao;
import com.phlx.anchorcollect.db.gen.DictEntityDao;
import com.phlx.anchorcollect.db.interf.DbQueryCallBack;
import com.phlx.anchorcollect.entity.CardEntity;
import com.phlx.anchorcollect.entity.CattleResumeEntity;
import com.phlx.anchorcollect.entity.DictEntity;
import com.phlx.anchorcollect.entity.GenTableColumn;
import com.phlx.anchorcollect.ui.fragment.list.CollectGridItem;
import com.phlx.anchorcollect.ui.setting.SettingActivity;
import com.phlx.anchorcollect.util.EntityUtils;
import com.phlx.anchorcollect.util.StringUtil;

import org.greenrobot.greendao.query.QueryBuilder;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

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.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class BasicsCollectVM extends BaseViewModel<Repository> {

    public Drawable drawableImg;
    //照片路径
    private String imgUrl;
    private File imgFile;

    //存放非list控件
    public List<GenTableColumn> uiList = new ArrayList<>();
    public GenTableColumn currentParamEntity;
    public GenTableColumn remarkParamEntity = new GenTableColumn();

    //给RecyclerView添加ObservableList
    public ObservableList<CollectGridItem> observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<CollectGridItem> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_collect_grid);

    public SingleLiveEvent<Boolean> onCattleClickEvent = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> onCardClickEvent = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> onTagClickEvent = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> onNotifyAllEvent = new SingleLiveEvent<>();//true是清空页面

    public ObservableField<String> tag = new ObservableField<>("");
    public ObservableField<String> weight = new ObservableField<>("125.5");

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

        //ImageView的占位图片，可以解决RecyclerView中图片错误问题
        drawableImg = ContextCompat.getDrawable(getApplication(), R.drawable.no_image);
    }

    public void initGen() {

        imgUrl = Environment.getExternalStorageDirectory().getAbsolutePath() +
                "/collect/picture/"
                + "anchorCiq" + tag + ".jpg";
        imgFile = new File(imgUrl);

        int i = 0;
        for (GenTableColumn gtc : Configs.cattleresume) {
            if (i < 4) {
                uiList.add(gtc);
            } else {
                CollectGridItem cgi = new CollectGridItem(this, gtc, Configs.BASE_ARCHIVES);
                observableList.add(cgi);
            }
            i++;
        }

        //初始化一下备注
        remarkParamEntity.setColumnName("备注");
        remarkParamEntity.setContent("");
        remarkParamEntity.setShowName("");
        remarkParamEntity.setColumnComment("备注");
        remarkParamEntity.setHtmlType("input");
        remarkParamEntity.setJavaType("String");

    }

    public void initData(String tag) {

        imgUrl = Environment.getExternalStorageDirectory().getAbsolutePath() +
                "/collect/picture/"
                + "anchorCiq" + tag + ".jpg";
        imgFile = new File(imgUrl);

        queryCattleResume(tag);
    }


    public void onItemClick(GenTableColumn entity) {

        if (StringUtils.isEmpty(Configs.tempUnid)) {
            ToastUtils.showShort("请扫描耳标或者输入耳标信息");
            return;
        }

        if (!"1".equals(entity.getIsEdit())) return;

        currentParamEntity = entity;
        onCardClickEvent.call();
    }

    public String getImgUrl() {
        return imgUrl;
    }

    //输入可视耳标
    public BindingCommand onTagInputClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            onTagClickEvent.call();
        }
    });

    //设置
    public BindingCommand onSettingClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startActivity(SettingActivity.class);
        }
    });

    //当前牛信息展示
    public BindingCommand onCattleInfoClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            onCattleClickEvent.call();
        }
    });

    public void click(int id) {

        if (StringUtils.isEmpty(Configs.tempUnid)) {
            ToastUtils.showShort("请扫描耳标或者输入耳标信息");
            return;
        }

        //99备注，100照片
        if (id == 99) {
            currentParamEntity = remarkParamEntity;
        } else {
            currentParamEntity = uiList.get(id);
        }

        if (!"1".equals(currentParamEntity.getIsEdit())) return;
        onCardClickEvent.call();
    }

    private void queryCattleResume(String tag) {

        QueryBuilder<CattleResumeEntity> builder =
                DbUtil.getInstance().getQueryBuilder(CattleResumeEntity.class)
                        .where(CattleResumeEntityDao.Properties.RegistrationNo.eq(tag));
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<CattleResumeEntity>() {
            @Override
            public void onSuccess(List<CattleResumeEntity> result) {

                if (result != null && result.size() > 0) {

                    Configs.tempTag = result.get(0).getIndividualNo();
                    Configs.tempRfid = result.get(0).getRegistrationNo();
                    Configs.tempUnid = result.get(0).getUnid();
                    String[] filedName = EntityUtils.getFiledName(result.get(0));
                    for (String name : filedName) {

                        for (GenTableColumn gtc : Configs.cattleresume) {

                            if (name.equals(gtc.getJavaField())) {
                                try {
                                    Log.e("key:", name);
                                    Object fieldValueByName = EntityUtils.getFieldValueByName(name, result.get(0));
                                    String value = fieldValueByName == null ? "" : fieldValueByName.toString();
                                    Log.e("value:", value);
                                    gtc.setContent(value);
                                    String showName = value;
                                    // 如果是选择的，查字典项
                                    if (!StringUtils.isEmpty(gtc.getDictType())) {
                                        QueryBuilder<DictEntity> builder =
                                                DbUtil.getInstance().getQueryBuilder(DictEntity.class)
                                                        .where(DictEntityDao.Properties.DictType.eq(gtc.getDictType())
                                                                , DictEntityDao.Properties.DictValue.eq(value));
                                        List<DictEntity> dictEntities = DbUtil.getInstance().queryAll(DictEntity.class, builder);
                                        if (dictEntities != null && dictEntities.size() > 0) {
                                            showName = dictEntities.get(0).getDictLabel();
                                        }
                                    }
                                    gtc.setShowName(showName);

                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                }
                            }
                        }

                    }

                    onNotifyAllEvent.setValue(false);
                } else {
                    onNotifyAllEvent.setValue(true);
                    clearTempInfo();
                }

            }

            @Override
            public void onFailed() {
                clearTempInfo();
                onNotifyAllEvent.setValue(true);
                ToastUtils.showShort("基础档案数据库查询失败");
            }
        }).queryAsyncAll(CattleResumeEntity.class, builder);
    }

    private void clearTempInfo() {

        Configs.tempTag = "";
        Configs.tempUnid = "";
        Configs.tempRfid = "";
    }


    //清空数据源
    public void clearParamList() {

        //备注清除数据
        remarkParamEntity.setContent("");
        remarkParamEntity.setShowName("");
        currentParamEntity = new GenTableColumn();
        for (GenTableColumn gtc : Configs.cattleresume) {
            gtc.setShowName("");
            gtc.setContent("");
        }
    }

}
