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.CattleResumeEntityDao;
import com.phlx.anchorcollect.db.gen.DictEntityDao;
import com.phlx.anchorcollect.db.gen.GenTableDao;
import com.phlx.anchorcollect.db.gen.ImmuneBatchDetailEntityDao;
import com.phlx.anchorcollect.db.gen.ImmuneBatchEntityDao;
import com.phlx.anchorcollect.db.gen.MedicalRecordEntityDao;
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.CattleResumeEntity;
import com.phlx.anchorcollect.entity.DictEntity;
import com.phlx.anchorcollect.entity.GenTable;
import com.phlx.anchorcollect.entity.GenTableColumn;
import com.phlx.anchorcollect.entity.ImmuneBatchDetailEntity;
import com.phlx.anchorcollect.entity.ImmuneBatchEntity;
import com.phlx.anchorcollect.entity.MedicalRecordEntity;
import com.phlx.anchorcollect.entity.PerformanceEntity;
import com.phlx.anchorcollect.ui.fragment.list.CollectGridItem;
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.HashSet;
import java.util.List;
import java.util.Set;

import cn.hutool.core.lang.Snowflake;
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 ImmunRecordVM 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 SingleLiveEvent<String> onShowDialogEvent = new SingleLiveEvent<>();//弹窗提示

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

    private long uuid;
    public boolean isModify = false;

    private SimpleDateFormat dateFormat;

    private List<ImmuneBatchEntity> uploadData;
    private List<ImmuneBatchDetailEntity> detailUploadData;

    public ImmunRecordVM(@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.immunebatch) {
            CollectGridItem cgi = new CollectGridItem(this, gtc, Configs.IMMUN_RECORD);
            observableList.add(cgi);
        }

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

    }

    private void initData(ImmuneBatchEntity immuneBatchEntity) {

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

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

            for (GenTableColumn gtc : Configs.immunebatch) {

                if (name.equals(gtc.getJavaField())) {
                    try {
                        Object fieldValueByName = EntityUtils.getFieldValueByName(name, immuneBatchEntity);
                        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();
                    }
                }
            }

            onNotifyAllEvent.setValue(false);
        }

    }

    public void queryImmuneBatch() {

        QueryBuilder<ImmuneBatchEntity> builder =
                DbUtil.getInstance().getQueryBuilder(ImmuneBatchEntity.class)
                        .where(ImmuneBatchEntityDao.Properties.Unid.eq(Configs.resumeId));
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<ImmuneBatchEntity>() {
            @Override
            public void onSuccess(List<ImmuneBatchEntity> 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(ImmuneBatchEntity.class, builder);

    }

    public void onItemClick(GenTableColumn entity) {

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

        if (!"1".equals(entity.getIsEdit()) && isModify) {
            ToastUtils.showShort("此数据无法修改!!");
            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.immunebatch) {
                if ("1".equals(gtc.getIsRequired()) && StringUtils.isEmpty(gtc.getContent())) {
                    onShowDialogEvent.setValue("请完成" + gtc.getColumnComment() + "的录入");
                    return;
                }
            }

            saveImmunRecord();
        }
    });

    private void saveImmunRecord() {

        JsonObject jsonObject = new JsonObject();
        for (GenTableColumn gtc : Configs.immunebatch) {
            //防止转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();
        ImmuneBatchEntity immuneBatchEntity = gson.fromJson(jsonObject, ImmuneBatchEntity.class);

        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (isModify) {//修改
            immuneBatchEntity.setUpdateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
            immuneBatchEntity.setUpdateTime(dateFormat.format(new Date()));
            immuneBatchEntity.setUnid(Configs.resumeId);
            //清除选中unid
            Configs.resumeId = null;
        } else {//新增
            uuid = IdUtil.createSnowflake(3, 1).nextId();
            immuneBatchEntity.setUnid(uuid);
            immuneBatchEntity.setDeptId(Long.parseLong(SPUtils.getInstance().getString(Configs.SP_DEPT_ID)));
            immuneBatchEntity.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));

            immuneBatchEntity.setCreateTime(dateFormat.format(new Date()));
        }
        immuneBatchEntity.setUploadStatus("0");
        immuneBatchEntity.setRemark(remarkParamEntity.getContent());

        uploadData = new ArrayList<>();
        detailUploadData = new ArrayList<>();
        uploadData.add(immuneBatchEntity);

        if (!isModify) {
            //查找所有属于这个圈舍的unid
            String circleNo = immuneBatchEntity.getCircleNo();


            QueryBuilder<CattleResumeEntity> builder =
                    DbUtil.getInstance().getQueryBuilder(CattleResumeEntity.class)
                            .where(CattleResumeEntityDao.Properties.CircleNo.eq(circleNo)
                                    , CattleResumeEntityDao.Properties.DeptId.eq(Long.parseLong(SPUtils.getInstance().getString(Configs.SP_DEPT_ID)))
                            );

            DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<CattleResumeEntity>() {
                @Override
                public void onSuccess(List<CattleResumeEntity> result) {
                    //查询圈舍内的牲畜
                    if (result != null && result.size() > 0) {

                        Snowflake snowflake = IdUtil.createSnowflake(3, 1);
                        for (CattleResumeEntity cre : result) {
                            ImmuneBatchDetailEntity immuneBatchDetailEntity = new ImmuneBatchDetailEntity();
                            immuneBatchDetailEntity.setUnid(snowflake.nextId());
                            immuneBatchDetailEntity.setCattleresumeUnid(cre.getUnid());
                            immuneBatchDetailEntity.setImmunebatchUnid(immuneBatchEntity.getUnid());
                            immuneBatchDetailEntity.setDeptId(Long.parseLong(SPUtils.getInstance().getString(Configs.SP_DEPT_ID)));
                            immuneBatchDetailEntity.setUploadStatus("0");
                            detailUploadData.add(immuneBatchDetailEntity);
                        }
                    }

                    //保存免疫主、子表
                    DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                        @Override
                        public void onNotification(boolean result) {
                            dismissDialog();
                            if (result) {
                                if (!isModify) {
                                    DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                                        @Override
                                        public void onNotification(boolean result) {
                                            dismissDialog();
                                            if (result) {
                                                onNotifyAllEvent.setValue(true);
                                                onShowDialogEvent.setValue("保存免疫记录成功!");
                                            } else {
                                                ToastUtils.showShort("保存免疫记录子表失败");
                                            }
                                        }
                                    }).insertAsyncBatch(ImmuneBatchDetailEntity.class, detailUploadData);
                                } else {
                                    onNotifyAllEvent.setValue(true);
                                    onShowDialogEvent.setValue("修改免疫记录成功!");
                                }
                            } else {
                                ToastUtils.showShort("保存免疫记录失败");
                            }
                        }
                    }).insertAsyncBatch(ImmuneBatchEntity.class, uploadData);
                }

                @Override
                public void onFailed() {
                    cn.wandersnail.commons.util.ToastUtils.showShort("查询-圈舍牲畜-失败！");
                    dismissDialog();
                }
            }).queryAsyncAll(CattleResumeEntity.class, builder);

        } else {
            ToastUtils.showShort("无法对已生成的免疫记录做修改！");
        }


    }

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

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

}
