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.BreedingRecordEntityDao;
import com.phlx.anchorcollect.db.gen.DictEntityDao;
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.BreedingRecordEntity;
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 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 BreedingRecordVM 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<>();//主表
    public ObservableList<CollectGridItem> detailObservableList = 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 BreedingRecordEntity tempEntity;
    private BreedingRecordDetailEntity tempDetailEntity;

    private SimpleDateFormat dateFormat;

    private List<BreedingRecordEntity> uploadData;
    private List<BreedingRecordDetailEntity> detailUploadData;

    private List<BreedingRecordDetailEntity> detailList;


    public BreedingRecordVM(@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.cattlematingMaster) {
            CollectGridItem cgi = new CollectGridItem(this, gtc, Configs.BREEDING_RECORD);
            observableList.add(cgi);
        }
        for (GenTableColumn gtc : Configs.cattlematingDetaill) {
            CollectGridItem cgi = new CollectGridItem(this, gtc, Configs.BREEDING_RECORD_DETAIL);
            detailObservableList.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 queryBreedingRecord() {

        QueryBuilder<BreedingRecordEntity> builder =
                DbUtil.getInstance().getQueryBuilder(BreedingRecordEntity.class)
                        .where(BreedingRecordEntityDao.Properties.CattleresumeId.eq(Configs.tempUnid)
                                , BreedingRecordEntityDao.Properties.CreateTime.like(DateUtils.getYear() + "%")
                        )
                        .orderDesc(BreedingRecordEntityDao.Properties.CreateTime);
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<BreedingRecordEntity>() {
            @Override
            public void onSuccess(List<BreedingRecordEntity> result) {

                clearDetailParamList();
                detailList = new ArrayList<>();
                if (result != null && result.size() > 0) {
                    initData(result.get(0));
                } else {
                    initData(null);
                    onNotifyAllEvent.setValue(false);
                }
            }

            @Override
            public void onFailed() {
                clearDetailParamList();
                onNotifyAllEvent.setValue(false);
                ToastUtils.showShort("配种记录主表-数据库查询失败");
            }
        }).queryAsyncAll(BreedingRecordEntity.class, builder);
    }


    //初始化主表
    private void initData(BreedingRecordEntity breedingRecordEntity) {

        tempEntity = new BreedingRecordEntity();
        if (breedingRecordEntity == null) {
            onNotifyAllEvent.setValue(true);
        } else {

            //拿到unid 创建人 创建时间 部门id
            tempEntity.setUnid(breedingRecordEntity.getUnid());
            tempEntity.setCreateBy(breedingRecordEntity.getCreateBy());
            tempEntity.setCreateTime(breedingRecordEntity.getCreateTime());
            tempEntity.setDeptId(breedingRecordEntity.getDeptId());
            tempEntity.setCattleresumeId(breedingRecordEntity.getCattleresumeId());

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

                for (GenTableColumn gtc : Configs.cattlematingMaster) {

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

            }

            initDetailList(breedingRecordEntity);
        }
    }

    //详情列表点击查询
    public void queryBreedingRecordDetail(Long clikeUnid) {

        QueryBuilder<BreedingRecordDetailEntity> builder = DbUtil.getInstance().getQueryBuilder(BreedingRecordDetailEntity.class)
                .where(BreedingRecordDetailEntityDao.Properties.Unid.eq(clikeUnid));

        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<BreedingRecordDetailEntity>() {
            @Override
            public void onSuccess(List<BreedingRecordDetailEntity> result) {
                if (result != null && result.size() > 0)
                    initDetaileData(result.get(0));
            }

            @Override
            public void onFailed() {
                clearDetailParamList();
                onNotifyAllEvent.setValue(false);
                ToastUtils.showShort("配种记录子表-数据库查询失败");
            }
        }).queryAsyncAll(BreedingRecordDetailEntity.class, builder);

    }

    //初始化子表
    public void initDetaileData(BreedingRecordDetailEntity brdEntity) {

        tempDetailEntity = brdEntity;
        if (brdEntity != null) {

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

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

                for (GenTableColumn gtc : Configs.cattlematingDetaill) {

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

    }

    //初始化详情列表
    private void initDetailList(BreedingRecordEntity breedingRecordEntity) {

        QueryBuilder<BreedingRecordDetailEntity> builder =
                DbUtil.getInstance().getQueryBuilder(BreedingRecordDetailEntity.class)
                        .where(BreedingRecordDetailEntityDao.Properties.FUnid.eq(breedingRecordEntity.getUnid()));
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<BreedingRecordDetailEntity>() {
            @Override
            public void onSuccess(List<BreedingRecordDetailEntity> result) {

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

                onNotifyAllEvent.setValue(true);
                ToastUtils.showShort("查询-配种记录子表-成功!");
            }

            @Override
            public void onFailed() {
                onNotifyAllEvent.setValue(true);
                ToastUtils.showShort("配种记录子表-数据库查询失败");
            }
        }).queryAsyncAll(BreedingRecordDetailEntity.class, builder);
    }

    //回显列表的数据
    public List<BreedingRecordDetailEntity> getDetail() {

        List<BreedingRecordDetailEntity> resultList = new ArrayList<>();

        if (detailList == null) {
            return resultList;
        }

        for (BreedingRecordDetailEntity pe : detailList) {

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

                for (GenTableColumn gtc : Configs.cattlematingDetaill) {

                    if (name.equals(gtc.getJavaField())) {
                        try {
//                                    Log.e("key:", name);
                            Object fieldValueByName = EntityUtils.getFieldValueByName(name, pe);
                            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);
                            gtc.setContent(showName);

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

            }

            //再把格式bean里的数据转换为数据bean
            JsonObject jsonObject = new JsonObject();
            for (GenTableColumn gtc : Configs.cattlematingDetaill) {
                //防止转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();
            Long unidTemp = pe.getUnid();
            pe = gson.fromJson(jsonObject, BreedingRecordDetailEntity.class);
            pe.setUnid(unidTemp);
            resultList.add(pe);

        }
        clearDetailParamList();
        return resultList;
    }

    public void onItemClick(GenTableColumn entity) {

        if (Configs.tempUnid == null) {
            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();
    }

    private void queryBreeding(String tag) {

    }

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

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

            saveBreedingRecord();
        }
    });

    //保存主表
    private void saveBreedingRecord() {

        JsonObject jsonObject = new JsonObject();
        for (GenTableColumn gtc : Configs.cattlematingMaster) {
            //防止转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();
        BreedingRecordEntity breedingRecordEntity = gson.fromJson(jsonObject, BreedingRecordEntity.class);
        if (tempEntity.getUnid() == null) {//新增
            breedingRecordEntity.setUnid(IdUtil.createSnowflake(3, 1).nextId());
            breedingRecordEntity.setDeptId(Long.parseLong(SPUtils.getInstance().getString(Configs.SP_DEPT_ID)));
            breedingRecordEntity.setCattleresumeId(Configs.tempUnid);
            dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            breedingRecordEntity.setCreateTime(dateFormat.format(new Date()));
            breedingRecordEntity.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
        } else {
            breedingRecordEntity.setUnid(tempEntity.getUnid());
            breedingRecordEntity.setCreateBy(tempEntity.getCreateBy());
            breedingRecordEntity.setCattleresumeId(tempEntity.getCattleresumeId());
            breedingRecordEntity.setCreateTime(tempEntity.getCreateTime());
            breedingRecordEntity.setDeptId(tempEntity.getDeptId());

            dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            breedingRecordEntity.setUpdateTime(dateFormat.format(new Date()));
            breedingRecordEntity.setUpdateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
        }
        breedingRecordEntity.setUploadStatus("0");
        tempDetailEntity.setfUnid(breedingRecordEntity.getUnid());//子表 外键

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

        DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
            @Override
            public void onNotification(boolean result) {
                dismissDialog();
                if (result) {
                    tempEntity = breedingRecordEntity;
                    onShowDialogEvent.setValue("保存-配种记录主表-成功!");
                    saveBreedingRecordDetail();
                } else {
                    ToastUtils.showShort("保存-配种记录主表-失败");
                }
            }
        }).insertAsyncBatch(BreedingRecordEntity.class, uploadData);
    }

    //保存子表
    private void saveBreedingRecordDetail() {

        JsonObject jsonObject = new JsonObject();
        for (GenTableColumn gtc : Configs.cattlematingDetaill) {
            //防止转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();
        BreedingRecordDetailEntity breedingRecordDetailEntity = gson.fromJson(jsonObject, BreedingRecordDetailEntity.class);
        if (tempDetailEntity.getUnid() == null) {//新增
            breedingRecordDetailEntity.setUnid(IdUtil.createSnowflake(3, 1).nextId());
            breedingRecordDetailEntity.setDeptId(Long.parseLong(SPUtils.getInstance().getString(Configs.SP_DEPT_ID)));
            breedingRecordDetailEntity.setCattleresumeId(Configs.tempUnid);
            dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            breedingRecordDetailEntity.setCreateTime(dateFormat.format(new Date()));
            breedingRecordDetailEntity.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
        } else {
            breedingRecordDetailEntity.setUnid(tempDetailEntity.getUnid());
            breedingRecordDetailEntity.setCreateBy(tempDetailEntity.getCreateBy());
            breedingRecordDetailEntity.setCreateTime(tempDetailEntity.getCreateTime());
            breedingRecordDetailEntity.setDeptId(tempDetailEntity.getDeptId());
            breedingRecordDetailEntity.setCattleresumeId(tempDetailEntity.getCattleresumeId());
            dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            breedingRecordDetailEntity.setUpdateTime(dateFormat.format(new Date()));
            breedingRecordDetailEntity.setUpdateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
        }
        breedingRecordDetailEntity.setUploadStatus("0");
        breedingRecordDetailEntity.setfUnid(tempDetailEntity.getfUnid());
        breedingRecordDetailEntity.setRemark(remarkParamEntity.getContent());

        detailUploadData = new ArrayList<>();
        detailUploadData.add(breedingRecordDetailEntity);

        DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
            @Override
            public void onNotification(boolean result) {
                dismissDialog();
                if (result) {
//                    clearDetailParamList();
                    initDetailList(tempEntity);
                } else {
                    ToastUtils.showShort("保存-配种记录子表-失败");
                }
            }
        }).insertAsyncBatch(BreedingRecordDetailEntity.class, detailUploadData);
    }

    //清空数据源
    public void clearParamList() {
        tempEntity = new BreedingRecordEntity();
        for (GenTableColumn gtc : Configs.cattlematingMaster) {
            gtc.setShowName("");
            gtc.setContent("");
        }
    }

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

        tempDetailEntity = new BreedingRecordDetailEntity();
        //备注清除数据
        remarkParamEntity.setContent("");
        remarkParamEntity.setShowName("");
        currentParamEntity = new GenTableColumn();

        for (GenTableColumn gtc : Configs.cattlematingDetaill) {
            gtc.setShowName("");
            gtc.setContent("");
        }
    }
}
