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

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

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
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.BreedingRecordDetailEntityDao;
import com.phlx.anchorcollect.db.gen.DictEntityDao;
import com.phlx.anchorcollect.db.gen.PerformanceEntityDao;
import com.phlx.anchorcollect.db.interf.DbIDUCallBack;
import com.phlx.anchorcollect.db.interf.DbQueryCallBack;
import com.phlx.anchorcollect.entity.BreedingRecordDetailEntity;
import com.phlx.anchorcollect.entity.DictEntity;
import com.phlx.anchorcollect.entity.GenTableColumn;
import com.phlx.anchorcollect.entity.PerformanceEntity;
import com.phlx.anchorcollect.ui.fragment.list.CollectGridItem;
import com.phlx.anchorcollect.util.DateUtils;
import com.phlx.anchorcollect.util.EntityUtils;
import com.phlx.anchorcollect.util.StringUtil;

import org.greenrobot.greendao.query.QueryBuilder;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.hutool.core.util.IdUtil;
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.SPUtils;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class PerformanceVM extends BaseViewModel<Repository> {

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

    public ObservableField<String> rfid = new ObservableField<>("");

    //存放非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 SingleLiveEvent<String> onShowDialogEvent = new SingleLiveEvent<>();//弹窗提示

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

    public boolean isModify = false;
    private long uuid;

    private SimpleDateFormat dateFormat;

    private List<PerformanceEntity> uploadData;


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

    public void initGen() {

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

        for (GenTableColumn gtc : Configs.performance) {

            //强制赋值为扫标签时的重量
            if (gtc.getJavaField().equals("weight")) {
                gtc.setShowName(Configs.tempWeight + "");
                gtc.setContent(Configs.tempWeight + "");
            }

            CollectGridItem cgi = new CollectGridItem(this, gtc, Configs.SIGN_MEASURE);
            observableList.add(cgi);
        }

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

    }

    public void refreshWeight() {

        for (GenTableColumn gtc : Configs.performance) {
            //强制赋值为扫标签时的重量
            if (gtc.getJavaField().equals("weight")) {
                gtc.setShowName(Configs.tempWeight + "");
                gtc.setContent(Configs.tempWeight + "");
            }
        }

    }

    private void initData(PerformanceEntity performanceEntity) {

        remarkParamEntity.setShowName(performanceEntity.getRemark());
        remarkParamEntity.setContent(performanceEntity.getRemark());

        String[] filedName = EntityUtils.getFiledName(performanceEntity);
        for (String name : filedName) {

            for (GenTableColumn gtc : Configs.performance) {

                if (name.equals(gtc.getJavaField())) {
                    try {
                        Object fieldValueByName = EntityUtils.getFieldValueByName(name, performanceEntity);
                        String value = fieldValueByName == null ? "" : fieldValueByName.toString();
//                        Log.e("fieldValue:", "key:" + name + " | 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();
                    }
                }
                //强制赋值为扫标签时的重量
                if (gtc.getJavaField().equals("weight")) {
                    gtc.setShowName(Configs.tempWeight + "");
                    gtc.setContent(Configs.tempWeight + "");
                }
            }

            onNotifyAllEvent.setValue(false);
        }

    }

    public void queryPerformance() {

        QueryBuilder<PerformanceEntity> builder =
                DbUtil.getInstance().getQueryBuilder(PerformanceEntity.class)
                        .where(PerformanceEntityDao.Properties.Unid.eq(Configs.resumeId));
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<PerformanceEntity>() {
            @Override
            public void onSuccess(List<PerformanceEntity> result) {

                if (result != null && result.size() > 0) {
                    initData(result.get(0));
                }
            }

            @Override
            public void onFailed() {

                //清除选中unid
                Configs.resumeId = null;
                onNotifyAllEvent.setValue(true);
                ToastUtils.showShort("性能测定-数据库查询失败");
            }
        }).queryAsyncAll(PerformanceEntity.class, builder);

    }

    public void onItemClick(GenTableColumn entity) {

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

        if (!"1".equals(entity.getIsEdit()) && isModify) {
            ToastUtils.showShort("此数据无法修改!!");
            return;
        }

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

        currentParamEntity = entity;
        onCardClickEvent.call();
    }

    public void click(int id) {

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

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

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


    public BindingCommand onSaveClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            //判断必填
            for (GenTableColumn gtc : Configs.performance) {
                if ("1".equals(gtc.getIsRequired()) && StringUtils.isEmpty(gtc.getContent())) {
                    onShowDialogEvent.setValue("请完成" + gtc.getColumnComment() + "的录入");
                    return;
                }
            }

            checkPerformance();
        }
    });

    private void checkPerformance() {

        JsonObject jsonObject = new JsonObject();
        for (GenTableColumn gtc : Configs.performance) {
            //防止转json类型错误
            if ("".equals(gtc.getContent())) {
                switch (gtc.getJavaType()) {
                    case "Long":
                    case "Double":
                    case "Integer":
                    case "BigDecimal":
                        gtc.setContent("0");
                        break;
                }
            }
            jsonObject.addProperty(gtc.getJavaField(), gtc.getContent());
        }

        Gson gson = new Gson();
        PerformanceEntity performanceEntity = gson.fromJson(jsonObject, PerformanceEntity.class);

        //查询此月龄是否存在，存在拿出主键 做覆盖
        QueryBuilder<PerformanceEntity> builder =
                DbUtil.getInstance().getQueryBuilder(PerformanceEntity.class)
                        .where(PerformanceEntityDao.Properties.Age.eq(performanceEntity.getAge())
                                , PerformanceEntityDao.Properties.CattleresumeId.eq(Configs.tempUnid)
                        );
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<PerformanceEntity>() {
            @Override
            public void onSuccess(List<PerformanceEntity> result) {

                if (result != null && result.size() > 0) {
                    isModify = true;
                    Configs.resumeId = result.get(0).getUnid();
                    performanceEntity.setUnid(result.get(0).getUnid());
                }
                savePerformance(performanceEntity);
                ToastUtils.showShort("查询-性能测定月龄数据-成功!");
            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("性能测定月龄数据-数据库查询失败");
            }
        }).queryAsyncAll(PerformanceEntity.class, builder);

    }

    private void savePerformance(PerformanceEntity performanceEntity) {

        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (!isModify) {//新增
            uuid = IdUtil.createSnowflake(3, 1).nextId();
            performanceEntity.setUnid(uuid);
            performanceEntity.setCattleresumeId(Configs.tempUnid);
            performanceEntity.setDeptId(Long.parseLong(SPUtils.getInstance().getString(Configs.SP_DEPT_ID)));
            performanceEntity.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));

            performanceEntity.setCreateTime(dateFormat.format(new Date()));
        } else {
            performanceEntity.setUnid(Configs.resumeId);
            performanceEntity.setCattleresumeId(Configs.tempUnid);
            performanceEntity.setUpdateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
            performanceEntity.setUpdateTime(dateFormat.format(new Date()));

            //清除选中unid
            Configs.resumeId = null;
        }
        performanceEntity.setRemark(remarkParamEntity.getContent());
        performanceEntity.setUploadStatus("0");

        uploadData = new ArrayList<>();
        uploadData.add(performanceEntity);

        DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
            @Override
            public void onNotification(boolean result) {
                dismissDialog();
                if (result) {
                    onNotifyAllEvent.setValue(true);
                    onShowDialogEvent.setValue("保存性能测定成功!");
                } else {
                    ToastUtils.showShort("保存性能测定失败");
                }
            }
        }).insertAsyncBatch(PerformanceEntity.class, uploadData);


    }

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

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


}
